title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is No...
103
2009-02-20T09:58:11Z
569,090
<p>A NumPy array is a very different data structure from a list and is designed to be used in different ways. Your use of <code>hstack</code> is potentially very inefficient... every time you call it, all the data in the existing array is copied into a new one. (The <code>append</code> function will have the same issu...
42
2009-02-20T10:44:19Z
[ "python", "arrays", "numpy" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is No...
103
2009-02-20T09:58:11Z
7,326,319
<p>If you absolutely don't know the final size of the array, you can increment the size of the array like this:</p> <pre><code>my_arr = numpy.zeros((0,5)) for i in range(3): my_arr=numpy.concatenate( ( my_arr, numpy.ones((1,5)) ) ) print(my_arr) [[ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1.]...
2
2011-09-06T21:20:44Z
[ "python", "arrays", "numpy" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is No...
103
2009-02-20T09:58:11Z
15,926,110
<p>I looked into this a lot because I needed to use a numpy.array as a set in one of my school projects and I needed to be initialized empty... I didn't found any relevant answer here on Stack Overflow, so I started doodling something. </p> <pre><code># Initialize your variable as an empty list first In [32]: x=[] # a...
8
2013-04-10T12:39:58Z
[ "python", "arrays", "numpy" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is No...
103
2009-02-20T09:58:11Z
22,978,734
<p>To create an empty multidimensional array in NumPy (e.g. a 2D array <code>m*n</code> to store your matrix), in case you don't know <code>m</code> how many rows you will append and don't care about the computational cost Stephen Simmons mentioned (namely re-buildinging the array at each append), you can squeeze to 0 ...
13
2014-04-10T04:34:58Z
[ "python", "arrays", "numpy" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is No...
103
2009-02-20T09:58:11Z
32,893,787
<p>You can apply it to build any kind of array, like zeros:</p> <pre><code>a = range(5) a = [i*0 for i in a] print a [0, 0, 0, 0, 0] </code></pre>
1
2015-10-01T17:50:36Z
[ "python", "arrays", "numpy" ]
How do I create an empty array/matrix in NumPy?
568,962
<p>I can't figure out how to use an array or matrix in the way that I would normally use a list. I want to create an empty array (or matrix) and then add one column (or row) to it at a time.</p> <p>At the moment the only way I can find to do this is like:</p> <pre><code>mat = None for col in columns: if mat is No...
103
2009-02-20T09:58:11Z
39,431,787
<p>Depending on what you are using this for, you may need to specify the data type (see <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html" rel="nofollow">'dtype'</a>).</p> <p>For example, to create a 2D array of 8-bit values (suitable for use as a monochrome image):</p> <pre><code>myarray ...
0
2016-09-11T00:28:42Z
[ "python", "arrays", "numpy" ]
How to programmatically insert comments into a Microsoft Word document?
568,972
<p>Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and implementable in a non-Windows environment (ideally using Python and/or Common Li...
9
2009-02-20T10:02:47Z
569,040
<p>If this is server side (non-interactive) use of the Word application itself is unsupported (but I see this is not applicable). So either take that route or use the <a href="http://msdn.microsoft.com/en-us/library/bb448854.aspx" rel="nofollow">OpenXML SDK</a> to learn the markup needed to create a comment. With that ...
2
2009-02-20T10:27:54Z
[ "python", "ms-word", "common-lisp", "openxml" ]
How to programmatically insert comments into a Microsoft Word document?
568,972
<p>Looking for a way to programmatically insert comments (using the comments feature in Word) into a specific location in a MS Word document. I would prefer an approach that is usable across recent versions of MS Word standard formats and implementable in a non-Windows environment (ideally using Python and/or Common Li...
9
2009-02-20T10:02:47Z
569,092
<p>Here is what I did:</p> <ol> <li>Create a simple document with word (i.e. a very small one)</li> <li>Add a comment in Word</li> <li>Save as docx.</li> <li>Use the zip module of python to access the archive (docx files are ZIP archives).</li> <li>Dump the content of the entry "word/document.xml" in the archive. This...
7
2009-02-20T10:44:49Z
[ "python", "ms-word", "common-lisp", "openxml" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
569,763
<p>"I want to hide some of the fields and do some complex validation."</p> <p>I start with the built-in admin interface.</p> <ol> <li><p>Build the ModelForm to show the desired fields.</p></li> <li><p>Extend the Form with the validation rules within the form. Usually this is a <code>clean</code> method.</p> <p>Be s...
2
2009-02-20T14:38:37Z
[ "python", "django", "design", "django-forms" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
575,133
<p>This really isn't too hard to implement with <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#topics-forms-modelforms">ModelForms</a>. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.</p> <pre><code>if request.POST(): ...
56
2009-02-22T16:09:05Z
[ "python", "django", "design", "django-forms" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
606,318
<p>I very recently had the some problem and just figured out how to do this. Assuming you have three classes, Primary, B, C and that B,C have a foreign key to primary</p> <pre><code> class PrimaryForm(ModelForm): class Meta: model = Primary class BForm(ModelForm): class Meta: ...
19
2009-03-03T13:05:53Z
[ "python", "django", "design", "django-forms" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
985,901
<p>I just was in about the same situation a day ago, and here are my 2 cents:</p> <p>1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: <a href="http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/">http://collingrady.wo...
60
2009-06-12T09:50:28Z
[ "python", "django", "design", "django-forms" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
10,217,798
<p>I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.</p> <p>Am I missing something here ?</p> <pre><code>class UserProfileForm(ModelForm): def __init__(self, instance=None, *args, **kwargs...
3
2012-04-18T20:53:18Z
[ "python", "django", "design", "django-forms" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
10,762,684
<p>According to Django documentation, inline formsets are for this purpose: "Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key".</p> <p>See <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-forms...
0
2012-05-26T00:16:10Z
[ "python", "django", "design", "django-forms" ]
Django: multiple models in one template using forms
569,468
<p>I'm building a support ticket tracking app and have a few models I'd like to create from one page. Tickets belong to a Customer via a ForeignKey. Notes belong to Tickets via a ForeignKey as well. I'd like to have the option of selecting a Customer (that's a whole separate project) OR creating a new Customer, then cr...
85
2009-02-20T12:50:26Z
33,213,960
<p>The <a href="https://django-betterforms.readthedocs.org/en/latest/multiform.html#working-with-modelforms">MultiModelForm</a> from <a href="https://github.com/fusionbox/django-betterforms"><code>django-betterforms</code></a> is a convenient wrapper to do what is described in <a href="http://stackoverflow.com/a/985901...
6
2015-10-19T12:05:43Z
[ "python", "django", "design", "django-forms" ]
Getting Forms on Page in Python
569,477
<p>I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method.</p> <p>I had the idea to make it extract the form data/names from all the pages on the website, bu...
0
2009-02-20T12:54:57Z
569,483
<p>Are you asking how to use <a href="http://www.python.org/doc/2.5.2/lib/module-urllib2.html" rel="nofollow">urllib2</a> to execute a POST method?</p> <p>You might want to look at the <a href="http://www.python.org/doc/2.5.2/lib/urllib2-examples.html" rel="nofollow">examples</a>.</p> <p>After trying some of that, yo...
1
2009-02-20T12:57:53Z
[ "python" ]
Getting Forms on Page in Python
569,477
<p>I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method.</p> <p>I had the idea to make it extract the form data/names from all the pages on the website, bu...
0
2009-02-20T12:54:57Z
569,487
<p>Use <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> for screen scraping.</p> <p>For heavier scripting, use <a href="http://twill.idyll.org/" rel="nofollow">twill</a> :</p> <blockquote> <p>twill is a simple language that allows users to browse the Web from a command-line i...
3
2009-02-20T12:58:39Z
[ "python" ]
Getting Forms on Page in Python
569,477
<p>I'm working on a web vulnerability scanner. I have completed 30% of the program, in that it can scan only HTTP GET methods. But I've hit a snag now: I have no idea how I shall make the program pentest the POST method.</p> <p>I had the idea to make it extract the form data/names from all the pages on the website, bu...
0
2009-02-20T12:54:57Z
569,728
<p>If you know how to collect the data/names from the form, you just need a way to deal with http POST method. I guess you will need a solution for sending multipart form-data.</p> <p>You should look at the MultipartPostHandler:</p> <p><a href="http://odin.himinbi.org/MultipartPostHandler.py" rel="nofollow">http://od...
0
2009-02-20T14:28:49Z
[ "python" ]
What's a good embedded browser for a pygtk application?
569,547
<p>I'm planning on using an embedded browser in my pygtk application and I'm debating between gtkmozembed and pywebkitgtk. Is there any compelling difference between the two? Are there any third options that I don't know about?</p> <p>It should be noted that I won't be using this to access content on the web. I'm m...
3
2009-02-20T13:19:32Z
569,784
<p>if you judge by the web pages then definitely pywebkitgtk </p> <p><a href="http://sourceforge.net/projects/pygtkmoz" rel="nofollow">pygtkmoz</a> from this page</p> <p>"Note: this project is no longer maintained. Please use gnome-python-extras (<a href="http://www.pygtk.org" rel="nofollow">http://www.pygtk.org</a>)...
2
2009-02-20T14:44:31Z
[ "python", "user-interface", "gtk", "webkit", "mozilla" ]
What's a good embedded browser for a pygtk application?
569,547
<p>I'm planning on using an embedded browser in my pygtk application and I'm debating between gtkmozembed and pywebkitgtk. Is there any compelling difference between the two? Are there any third options that I don't know about?</p> <p>It should be noted that I won't be using this to access content on the web. I'm m...
3
2009-02-20T13:19:32Z
636,369
<p>gtkmozembed is not available on Windows, although you can use the gecko embedding interface directly. This would require you to write some C++ code.</p> <p>As far as I know, the gtk webkit port is not available on Windows yet, and still appears to be undergoing a lot of change.</p> <p>For an example of a cross-pla...
6
2009-03-11T21:06:20Z
[ "python", "user-interface", "gtk", "webkit", "mozilla" ]
How to keep track of thread progress in Python without freezing the PyQt GUI?
569,650
<h2><strong>Questions:</strong></h2> <ol> <li>What is the best practice for keeping track of a tread's progress without locking the GUI ("Not Responding")?</li> <li>Generally, what are the best practices for threading as it applies to GUI development?</li> </ol> <h2><strong>Question Background:</strong></h2> <ul>...
18
2009-02-20T14:00:06Z
570,770
<p>You are always going to have this problem in Python. Google GIL "global interpretor lock" for more background. There are two generally recommended ways to get around the problem that you are experiencing: use <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a>, or use a module similar to the <a hre...
0
2009-02-20T18:43:44Z
[ "python", "multithreading", "user-interface", "pyqt" ]
How to keep track of thread progress in Python without freezing the PyQt GUI?
569,650
<h2><strong>Questions:</strong></h2> <ol> <li>What is the best practice for keeping track of a tread's progress without locking the GUI ("Not Responding")?</li> <li>Generally, what are the best practices for threading as it applies to GUI development?</li> </ol> <h2><strong>Question Background:</strong></h2> <ul>...
18
2009-02-20T14:00:06Z
572,456
<p>If your method "processDoc" doesn't change any other data (just looks for some data and return it and don't change variables or properties of parent class) you may use Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macroses ( <a href="http://www.python.org/doc/2.4/api/threads.html" rel="nofollow">see here for detai...
1
2009-02-21T05:44:14Z
[ "python", "multithreading", "user-interface", "pyqt" ]
How to keep track of thread progress in Python without freezing the PyQt GUI?
569,650
<h2><strong>Questions:</strong></h2> <ol> <li>What is the best practice for keeping track of a tread's progress without locking the GUI ("Not Responding")?</li> <li>Generally, what are the best practices for threading as it applies to GUI development?</li> </ol> <h2><strong>Question Background:</strong></h2> <ul>...
18
2009-02-20T14:00:06Z
572,577
<p>I recommend you to use Queue instead of signaling. Personally I find it a much more robust and understandable way of programming, because it's more synchronous.</p> <p>Threads should get "jobs" from a Queue, and put back results on another Queue. Yet a third Queue can be used by the threads for notifications and me...
4
2009-02-21T07:18:06Z
[ "python", "multithreading", "user-interface", "pyqt" ]
How to keep track of thread progress in Python without freezing the PyQt GUI?
569,650
<h2><strong>Questions:</strong></h2> <ol> <li>What is the best practice for keeping track of a tread's progress without locking the GUI ("Not Responding")?</li> <li>Generally, what are the best practices for threading as it applies to GUI development?</li> </ol> <h2><strong>Question Background:</strong></h2> <ul>...
18
2009-02-20T14:00:06Z
574,130
<p>If you want to use signals to indicate progress to the main thread then you should really be using PyQt's QThread class instead of the Thread class from Python's threading module.</p> <p>A simple example which uses QThread, signals and slots can be found on the PyQt Wiki:</p> <p><a href="https://wiki.python.org/mo...
10
2009-02-22T01:33:00Z
[ "python", "multithreading", "user-interface", "pyqt" ]
How to keep track of thread progress in Python without freezing the PyQt GUI?
569,650
<h2><strong>Questions:</strong></h2> <ol> <li>What is the best practice for keeping track of a tread's progress without locking the GUI ("Not Responding")?</li> <li>Generally, what are the best practices for threading as it applies to GUI development?</li> </ol> <h2><strong>Question Background:</strong></h2> <ul>...
18
2009-02-20T14:00:06Z
1,020,072
<p>Native python queues won't work because you have to block on queue get(), which bungs up your UI. </p> <p>Qt essentially implements a queuing system on the inside for cross thread communication. Try this call from any thread to post a call to a slot.</p> <p>QtCore.QMetaObject.invokeMethod()</p> <p>It's clunky a...
5
2009-06-19T21:21:59Z
[ "python", "multithreading", "user-interface", "pyqt" ]
Lazy choices in Django form
569,696
<p>I have a Django my_forms.py like this:</p> <pre><code>class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=bodystyle_choices()) </code></pre> <p>Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.</p> <pre><code>d...
16
2009-02-20T14:18:37Z
569,748
<p>Try using a ModelChoiceField instead of a simple ChoiceField. I think you will be able to achieve what you want by tweaking your models a bit. Take a look at the <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield">docs</a> for more.</p> <p>I would also add that ModelChoiceFields are <c...
16
2009-02-20T14:33:58Z
[ "python", "django", "forms", "lazy-evaluation" ]
Lazy choices in Django form
569,696
<p>I have a Django my_forms.py like this:</p> <pre><code>class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=bodystyle_choices()) </code></pre> <p>Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.</p> <pre><code>d...
16
2009-02-20T14:18:37Z
845,140
<p>You can use the "lazy" function :)</p> <pre><code>from django.utils.functional import lazy class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)()) </code></pre> <p>very nice util function !</p>
39
2009-05-10T11:21:16Z
[ "python", "django", "forms", "lazy-evaluation" ]
Lazy choices in Django form
569,696
<p>I have a Django my_forms.py like this:</p> <pre><code>class CarSearchForm(forms.Form): # lots of fields like this bodystyle = forms.ChoiceField(choices=bodystyle_choices()) </code></pre> <p>Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.</p> <pre><code>d...
16
2009-02-20T14:18:37Z
29,517,662
<p>Expanding on what Baishampayan Ghose said, this should probably be considered the most direct approach:</p> <pre><code>from django.forms import ModelChoiceField class BodystyleChoiceField(ModelChoiceField): def label_from_instance(self, obj): return '%s (%s cars)' % (obj.bodystyle_name, obj.car_set.cou...
0
2015-04-08T14:32:53Z
[ "python", "django", "forms", "lazy-evaluation" ]
How to tell for which object attribute pickle fails?
569,754
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p> <pre><code>PicklingError: Can't pickle &lt;type 'instancemethod'&gt;: attribute lookup __builtin__.instancemethod failed </code></pre> <p>Is there any way to tell which attribute caused th...
28
2009-02-20T14:36:09Z
570,910
<p>You could file a bug against Python for not including more helpful error messages. In the meantime, modify the <code>_reduce_ex()</code> function in <code>copy_reg.py</code>.</p> <pre><code>if base is self.__class__: print self # new raise TypeError, "can't pickle %s objects" % base.__name__ </code></pre...
14
2009-02-20T19:30:46Z
[ "python", "serialization" ]
How to tell for which object attribute pickle fails?
569,754
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p> <pre><code>PicklingError: Can't pickle &lt;type 'instancemethod'&gt;: attribute lookup __builtin__.instancemethod failed </code></pre> <p>Is there any way to tell which attribute caused th...
28
2009-02-20T14:36:09Z
7,218,986
<p>I had the same problem as you, but my classes were a bit more complicated (i.e. a large tree of similar objects) so the printing didn't help much so I hacked together a helper function. It is not complete and is only intended for use with pickling protocol 2: It was enough so I could locate my problems. If you want ...
7
2011-08-28T04:04:50Z
[ "python", "serialization" ]
How to tell for which object attribute pickle fails?
569,754
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p> <pre><code>PicklingError: Can't pickle &lt;type 'instancemethod'&gt;: attribute lookup __builtin__.instancemethod failed </code></pre> <p>Is there any way to tell which attribute caused th...
28
2009-02-20T14:36:09Z
7,843,281
<p>I have found that if you subclass Pickler and wrap the Pickler.save() method in a try, except block</p> <pre><code>import pickle class MyPickler (pickle.Pickler): def save(self, obj): try: pickle.Pickler.save(self, obj) except Exception, e: import pdb;pdb.set_trace() </co...
3
2011-10-20T23:01:38Z
[ "python", "serialization" ]
How to tell for which object attribute pickle fails?
569,754
<p>When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:</p> <pre><code>PicklingError: Can't pickle &lt;type 'instancemethod'&gt;: attribute lookup __builtin__.instancemethod failed </code></pre> <p>Is there any way to tell which attribute caused th...
28
2009-02-20T14:36:09Z
25,171,609
<p>If you use <code>dill</code>, your example doesn't fail to pickle...</p> <pre><code>&gt;&gt;&gt; import dill &gt;&gt;&gt; import new &gt;&gt;&gt; &gt;&gt;&gt; class Test(object): ... pass ... &gt;&gt;&gt; def test_func(self): ... pass ... &gt;&gt;&gt; test = Test() &gt;&gt;&gt; dill.dumps(test) '\x80\x02...
2
2014-08-06T22:55:07Z
[ "python", "serialization" ]
Statistics with numpy
570,137
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p> <p>Is there a simple way to do...
1
2009-02-20T16:04:25Z
570,169
<p>Say you have</p> <pre><code>&gt;&gt;&gt; prices = array([100, 200, 150, 145, 300]) &gt;&gt;&gt; base_prices = array([90, 220, 100, 350, 350]) </code></pre> <p>Then the number of prices that are more than 10% above the base price are</p> <pre><code>&gt;&gt;&gt; sum(prices &gt; 1.10 * base_prices) 2 </code></pre>
7
2009-02-20T16:12:39Z
[ "python", "numpy" ]
Statistics with numpy
570,137
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p> <p>Is there a simple way to do...
1
2009-02-20T16:04:25Z
570,197
<p>In addition to df's answer, if you want to know the specific prices that are above the base prices, you can do:</p> <p>prices[prices > (1.10 * base_prices)]</p>
1
2009-02-20T16:19:14Z
[ "python", "numpy" ]
Statistics with numpy
570,137
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p> <p>Is there a simple way to do...
1
2009-02-20T16:04:25Z
570,204
<p>I don't think you need numpy ...</p> <pre><code>prices = [40.0, 150.0, 35.0, 65.0, 90.0] baseprices = [45.0, 130.0, 40.0, 80.0, 100.0] x = .1 y = .5 # how many are within 10% len([p for p,bp in zip(prices,baseprices) if p &lt;= (1+x)*bp]) # 1 # how many are within 50% len([p for p,bp in zip(prices,baseprices) if ...
0
2009-02-20T16:21:24Z
[ "python", "numpy" ]
Statistics with numpy
570,137
<p>I am working at some plots and statistics for work and I am not sure how I can do some statistics using numpy: I have a list of prices and another one of basePrices. And I want to know how many prices are with X percent above basePrice, how many are with Y percent above basePrice.</p> <p>Is there a simple way to do...
1
2009-02-20T16:04:25Z
570,372
<p>Just for amusement, here's a slightly different take on dF's answer:</p> <pre><code>&gt;&gt;&gt; prices = array([100, 200, 150, 145, 300]) &gt;&gt;&gt; base_prices = array([90, 220, 100, 350, 350]) &gt;&gt;&gt; ratio = prices / base_prices </code></pre> <p>Then you can extract the number that are 5% above, 10% abo...
2
2009-02-20T16:58:35Z
[ "python", "numpy" ]
admin template for manytomany
570,138
<p>I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:</p> <pre><code>class Pathology(models.Mode...
1
2009-02-20T16:05:00Z
570,198
<p>Unless you are using a intermediate table as documented here <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models</a>, I don't think you need...
1
2009-02-20T16:19:30Z
[ "python", "django", "django-admin", "many-to-many" ]
admin template for manytomany
570,138
<p>I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:</p> <pre><code>class Pathology(models.Mode...
1
2009-02-20T16:05:00Z
582,818
<p>I realize now that Django is great for the administration (data entry) of a website, simple searching and template inheritance, but Django and Python are not very good for complex web applications, where data is moved back and forth between a database and an html template. I have decided to combine Django and PHP, ...
0
2009-02-24T17:57:57Z
[ "python", "django", "django-admin", "many-to-many" ]
admin template for manytomany
570,138
<p>I have a manytomany relationship between publication and pathology. Each publication can have many pathologies. When a publication appears in the admin template, I need to be able to see the many pathologies associated with that publication. Here is the model statement:</p> <pre><code>class Pathology(models.Mode...
1
2009-02-20T16:05:00Z
596,600
<p>That looks more like a one-to-many relationship to me, tho I'm somewhat unclear on what exactly Pathologies are. Also, so far as I understand, Inlines don't work on manytomany. That should work if you flip the order of the models, remove the manytomany and add a ForeignKey field to Publication in Pathology.</p> <...
0
2009-02-27T20:41:15Z
[ "python", "django", "django-admin", "many-to-many" ]
With Twisted, how can 'connectionMade' fire a specific Deferred?
570,397
<p>This is part of a larger program; I'll explain only the relevant parts. Basically, my code wants to create a new connection to a remote host. This should return a Deferred, which fires once the connection is established, so I can send something on it.</p> <p>I'm creating the connection with <code>twisted.internet...
2
2009-02-20T17:03:48Z
570,561
<p>Looking at this some more, I think I've come up with a solution, although hopefully there is a better way; this seems kind of weird.</p> <p>Twisted has a class, <code>ClientCreator</code> that is used for producing simple single-use connections. It in theory does what I want; connects and returns a <code>Deferred<...
0
2009-02-20T17:39:22Z
[ "python", "connection", "twisted", "reactor" ]
How can I get the newest file from an FTP server?
570,433
<p>I am using Python to connect to an FTP server that contains a new list of data once every hour. I am only connecting once a day, and I only want to download the newest file in the directory. Is there a way to do this?</p>
3
2009-02-20T17:10:20Z
571,363
<p>Look at ftplib in your current version of python. You can see a function to handle the result of the LIST command that you would issue to do a dir, if you know a last time that you run a successful script then you can parse the result from the LIST and act on the new files on the directory. See the <a href="http:/...
0
2009-02-20T21:49:10Z
[ "python", "ftp" ]
How can I get the newest file from an FTP server?
570,433
<p>I am using Python to connect to an FTP server that contains a new list of data once every hour. I am only connecting once a day, and I only want to download the newest file in the directory. Is there a way to do this?</p>
3
2009-02-20T17:10:20Z
571,410
<p>Seems like any system that is automatically generating a file once an hour is likely to be using an automated naming scheme. Are you over thinking the problem by asking the server for the newest file instead of more easily parsing the file names? </p> <p>This wouldn't work in all cases, and if the directory got l...
1
2009-02-20T22:02:56Z
[ "python", "ftp" ]
How do I add plain text info to forms in a formset in Django?
570,522
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p> <p>sample template code:</p> <pre><code>{% for form, data in zipped_data %} &lt;div class="row"&gt; &lt;div class="first_col"&gt; &lt;span class=...
3
2009-02-20T17:30:00Z
571,334
<p>Instead of zipping your forms with the additional data, you can override the constructor on your form and hold your title/description as <em>instance-level</em> member variables. This is a bit more object-oriented and learning how to do this will help you solve other problems down the road such as dynamic choice fi...
8
2009-02-20T21:39:03Z
[ "python", "django", "django-forms" ]
How do I add plain text info to forms in a formset in Django?
570,522
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p> <p>sample template code:</p> <pre><code>{% for form, data in zipped_data %} &lt;div class="row"&gt; &lt;div class="first_col"&gt; &lt;span class=...
3
2009-02-20T17:30:00Z
574,345
<p>I just created a read-only widget by subclassing the text input field one:</p> <pre><code>class ReadOnlyText(forms.TextInput): input_type = 'text' def render(self, name, value, attrs=None): if value is None: value = '' return value </code></pre> <p>And: </p> <pre><code>class ReportForm(fo...
3
2009-02-22T04:35:57Z
[ "python", "django", "django-forms" ]
How do I add plain text info to forms in a formset in Django?
570,522
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p> <p>sample template code:</p> <pre><code>{% for form, data in zipped_data %} &lt;div class="row"&gt; &lt;div class="first_col"&gt; &lt;span class=...
3
2009-02-20T17:30:00Z
866,227
<p>I had to solve a similar problem and like your idea Andrei. I had some issues using it though, as, if there were validation errors, the value of the read-only field would get lost. To solve this, I did something similar but overrode HiddenInput instead and kept the value in a hidden form field. ie:</p> <pre><cod...
1
2009-05-14T22:37:37Z
[ "python", "django", "django-forms" ]
How do I add plain text info to forms in a formset in Django?
570,522
<p>I want to show a title and description from a db query in each form, but I don't want it to be in a charfield, I want it to be html-formatted text.</p> <p>sample template code:</p> <pre><code>{% for form, data in zipped_data %} &lt;div class="row"&gt; &lt;div class="first_col"&gt; &lt;span class=...
3
2009-02-20T17:30:00Z
20,201,594
<p>I think you can get it with "{{ field.value }}". Maybe it's the easier way.</p> <pre><code>{% for form in formset %} {% for field in form %} {% if forloop.counter = 1 %} &lt;td&gt;&lt;img src="{{ MEDIA_URL }}{{ field.value }}"/&gt;&lt;/td&gt; {% endif %} {% if forloop.counter...
0
2013-11-25T19:30:00Z
[ "python", "django", "django-forms" ]
Detect when a Python module unloads
570,636
<p>I have a module that uses ctypes to wrap some functionality from a static library into a class. When the module loads, it calls an initialize function in the static library. When the module is unloaded (presumably when the interpreter exits), there's an unload function in the library that I'd like to be called. How ...
7
2009-02-20T18:00:23Z
570,704
<p>Use the <a href="http://docs.python.org/library/atexit.html">atexit</a> module:</p> <pre><code>import mymodule import atexit # call mymodule.unload('param1', 'param2') when the interpreter exits: atexit.register(mymodule.unload, 'param1', 'param2') </code></pre> <p>Another simple example from the docs, using <a h...
12
2009-02-20T18:19:37Z
[ "python" ]
Python c-api and unicode strings
570,781
<p>I need to convert between python objects and c strings of various encodings. Going from a c string to a unicode object was fairly simple using PyUnicode_Decode, however Im not sure how to go the other way</p> <pre><code>//char* can be a wchar_t or any other element size, just make sure it is correctly terminated fo...
4
2009-02-20T18:47:34Z
570,896
<blockquote> <p>I suspect it has somthing to do with PyUnicode_AsEncodedString however that returns a PyObject so I'm not sure how to put that into my buffer...</p> </blockquote> <p>The PyObject returned is a PyStringObject, so you just need to use <code>PyString_Size</code> and <code>PyString_AsString</code> to get...
3
2009-02-20T19:26:50Z
[ "python", "c", "python-c-api" ]
Django "SuspiciousOperation" Error While Deleting Uploaded File
570,952
<p>I'm developing in Django on Windows XP using the <code>manage.py runserver</code> command to serve files. Apache isn't involved. When I login to the administration and try to delete a file I get a "SuspiciousOperation" error.</p> <p>Here's the traceback:<br /> <a href="http://dpaste.com/123112/" rel="nofollow">http...
2
2009-02-20T19:41:08Z
571,047
<p>What is your <code>MEDIA_ROOT</code> in <code>settings.py</code>? From the back-trace, it seems you have set your <code>MEDIA_ROOT</code> to <code>/static/</code>.</p> <p>This error is coming since Django is trying to access <code>/static/</code> to which it has no access. Put an absolute pathname for <code>MEDIA_R...
5
2009-02-20T20:08:44Z
[ "python", "windows", "django" ]
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
571,083
<p>I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or...
3
2009-02-20T20:20:18Z
571,093
<p><a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> should cover all of this.</p> <p>Here's a <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6" rel="nofollow">Basic Authentication example</a>.</p> <p>Here's a <a href="http://code.activestate.com/recipes/146306/" r...
3
2009-02-20T20:23:05Z
[ "python", "authentication", "cookies", "post" ]
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
571,083
<p>I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or...
3
2009-02-20T20:20:18Z
571,106
<p>Try <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a> module.</p>
2
2009-02-20T20:25:44Z
[ "python", "authentication", "cookies", "post" ]
In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?
571,083
<p>I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or...
3
2009-02-20T20:20:18Z
571,182
<p>You should look at the MultipartPostHandler:</p> <p><a href="http://odin.himinbi.org/MultipartPostHandler.py" rel="nofollow">http://odin.himinbi.org/MultipartPostHandler.py</a></p> <p>And if you need to support unicode file names , see a fix at: <a href="http://peerit.blogspot.com/2007/07/multipartposthandler-does...
0
2009-02-20T20:47:51Z
[ "python", "authentication", "cookies", "post" ]
Split tags in python
571,186
<p>I have a file that contains this:</p> <pre class="lang-none prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hello! - {{ today }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} &lt;/body&gt; &lt;/h...
3
2009-02-20T20:50:04Z
571,231
<p>try <a href="http://code.google.com/p/templatemaker/" rel="nofollow">templatemaker</a>, a reverse-template maker. it can actually learn them automatically from examples!</p>
3
2009-02-20T21:08:00Z
[ "python", "split", "template-engine" ]
Split tags in python
571,186
<p>I have a file that contains this:</p> <pre class="lang-none prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hello! - {{ today }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} &lt;/body&gt; &lt;/h...
3
2009-02-20T20:50:04Z
571,238
<p>Mmkay, well here's a generator solution that seems to work well for me. You can also provide different open and close tags if you like.</p> <pre><code>def get_tags(s, open_delim ='{{', close_delim ='}}' ): while True: # Search for the next two delimiters in the source text start ...
7
2009-02-20T21:09:48Z
[ "python", "split", "template-engine" ]
Split tags in python
571,186
<p>I have a file that contains this:</p> <pre class="lang-none prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hello! - {{ today }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} &lt;/body&gt; &lt;/h...
3
2009-02-20T20:50:04Z
571,240
<p>If the data is that straightforward, a simple regex would do the trick.</p>
0
2009-02-20T21:10:17Z
[ "python", "split", "template-engine" ]
Split tags in python
571,186
<p>I have a file that contains this:</p> <pre class="lang-none prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hello! - {{ today }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} &lt;/body&gt; &lt;/h...
3
2009-02-20T20:50:04Z
571,257
<p>I know you said no regex/split, but I couldn't help but try for a one-liner solution:</p> <pre><code>import re for s in re.findall("\{\{.*\}\}",thedata): print s.replace("{","").replace("}","") </code></pre> <p>EDIT: JFS</p> <p>Compare:</p> <pre><code>&gt;&gt;&gt; re.findall('\{\{.*\}\}', '{{a}}b{{c}}') ...
2
2009-02-20T21:14:03Z
[ "python", "split", "template-engine" ]
Split tags in python
571,186
<p>I have a file that contains this:</p> <pre class="lang-none prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hello! - {{ today }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ runner_up }} avasd {{ blabla }} sdvas {{ oooo }} &lt;/body&gt; &lt;/h...
3
2009-02-20T20:50:04Z
571,314
<p>J.F. Sebastian wrote this in a comment but I thought it was good enough to deserve its own answer:</p> <pre><code>re.findall(r'{{(.+?)}}', thestring) </code></pre> <p>I know the OP was asking for a way that didn't involve splits or regexes - so maybe this doesn't <em>quite</em> answer the question as stated. But t...
1
2009-02-20T21:34:59Z
[ "python", "split", "template-engine" ]
triangle numbers in python
571,488
<p>I'm trying to solve the problem:</p> <blockquote> <p>What is the value of the first triangle number to have over five hundred divisors?</p> </blockquote> <p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p> <p>I'm pretty sure that this is working code but I don't...
10
2009-02-20T22:27:36Z
571,518
<p>You're not updating the value of <code>one</code>, so your program will never end.</p>
5
2009-02-20T22:36:25Z
[ "python" ]
triangle numbers in python
571,488
<p>I'm trying to solve the problem:</p> <blockquote> <p>What is the value of the first triangle number to have over five hundred divisors?</p> </blockquote> <p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p> <p>I'm pretty sure that this is working code but I don't...
10
2009-02-20T22:27:36Z
571,526
<p>Hints:</p> <ul> <li>what is the formula for <code>n</code>-th triangular number?</li> <li><code>n</code> and <code>n+1</code> have no common factors (except <code>1</code>). Question: given number of factors in <code>n</code> and <code>n+1</code> how to calculate number of factors in <code>n*(n+1)</code>? What abou...
27
2009-02-20T22:39:49Z
[ "python" ]
triangle numbers in python
571,488
<p>I'm trying to solve the problem:</p> <blockquote> <p>What is the value of the first triangle number to have over five hundred divisors?</p> </blockquote> <p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p> <p>I'm pretty sure that this is working code but I don't...
10
2009-02-20T22:27:36Z
572,562
<p>You'll have to think more and use less brute force to solve Project Euler questions.</p> <p>In this case you should investigate which and how many divisors triangle numbers have. Start at the beginning, look for patterns, try to understand the problem.</p>
6
2009-02-21T06:59:57Z
[ "python" ]
triangle numbers in python
571,488
<p>I'm trying to solve the problem:</p> <blockquote> <p>What is the value of the first triangle number to have over five hundred divisors?</p> </blockquote> <p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p> <p>I'm pretty sure that this is working code but I don't...
10
2009-02-20T22:27:36Z
573,935
<p>Just for sanity's sake, you should use</p> <pre><code>while True: </code></pre> <p>and get rid of <code>one</code>.</p>
5
2009-02-21T23:42:47Z
[ "python" ]
triangle numbers in python
571,488
<p>I'm trying to solve the problem:</p> <blockquote> <p>What is the value of the first triangle number to have over five hundred divisors?</p> </blockquote> <p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p> <p>I'm pretty sure that this is working code but I don't...
10
2009-02-20T22:27:36Z
3,821,619
<p>Your current brute force algorithm is too inefficient to solve this problem in the Project Euler time limit of 1 minute. Instead, I suggest looking at the Divisor Function:</p> <p><a href="http://www.artofproblemsolving.com/Wiki/index.php/Divisor_function" rel="nofollow">http://www.artofproblemsolving.com/Wiki/inde...
3
2010-09-29T12:38:12Z
[ "python" ]
triangle numbers in python
571,488
<p>I'm trying to solve the problem:</p> <blockquote> <p>What is the value of the first triangle number to have over five hundred divisors?</p> </blockquote> <p><em>A triangle number is a number in the sequence of the sum of numbers i.e. 1+2+3+4+5...</em></p> <p>I'm pretty sure that this is working code but I don't...
10
2009-02-20T22:27:36Z
11,820,553
<p>First of all, the people telling you that you can't solve this problem with brute force in under a minute are wrong. A brute force algorithm for a problem this size will run in a few seconds.</p> <p>Second, the code that you posted has several problems, some of them already mentioned.</p> <ul> <li>You should term...
5
2012-08-05T22:21:32Z
[ "python" ]
Are there any declaration keywords in Python?
571,514
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p> <pre><code>x = 5; </code></pre> <ul> <li>Creates a new variable.</li> </ul> <p>or</p> <ul> <li>Sets an existing one.</li> </ul>
9
2009-02-20T22:34:34Z
571,546
<p>An important thing to understand about Python is there are no variables, only "names".</p> <p>In your example, you have an object "5" and you are creating a name "x" that references the object "5".</p> <p>If later you do:</p> <pre><code>x = "Some string" </code></pre> <p>that is still perfectly valid. Name "x" ...
14
2009-02-20T22:46:25Z
[ "python", "variables" ]
Are there any declaration keywords in Python?
571,514
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p> <pre><code>x = 5; </code></pre> <ul> <li>Creates a new variable.</li> </ul> <p>or</p> <ul> <li>Sets an existing one.</li> </ul>
9
2009-02-20T22:34:34Z
571,559
<p>It doesn't look like the asker is trying to assign a type, just to specify that this a declaration, not an assignment.</p> <p>Looks like you are looking for something like javascript has:</p> <pre><code>var x = 5; </code></pre> <p>The concept of the declaration keyword in javascript is to ensure that you are maki...
4
2009-02-20T22:53:07Z
[ "python", "variables" ]
Are there any declaration keywords in Python?
571,514
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p> <pre><code>x = 5; </code></pre> <ul> <li>Creates a new variable.</li> </ul> <p>or</p> <ul> <li>Sets an existing one.</li> </ul>
9
2009-02-20T22:34:34Z
571,610
<p>It's worth mentioning that there is a global keyword, so if you want to refer to the global x:</p> <pre><code>x = 4 def foo(): x = 7 # x is local to your function </code></pre> <p>You need to do this:</p> <pre><code>x = 4 def foo(): global x # let python know you want to use the top-level x x = 7 </co...
11
2009-02-20T23:09:54Z
[ "python", "variables" ]
Are there any declaration keywords in Python?
571,514
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p> <pre><code>x = 5; </code></pre> <ul> <li>Creates a new variable.</li> </ul> <p>or</p> <ul> <li>Sets an existing one.</li> </ul>
9
2009-02-20T22:34:34Z
571,757
<p>I really like the understanding that Van Gale is providing, but it doesn't really answer the question of, "how do you know if this statement: creates a new variable or sets an existing variable?"</p> <p>If you want to know how to recognize it when looking at code, you simply look for a previous assignment. Avoid g...
11
2009-02-21T00:21:28Z
[ "python", "variables" ]
Are there any declaration keywords in Python?
571,514
<p>Are there any declaration keywords in python, like local, global, private, public etc. I know it's type free but how do you know if this statement:</p> <pre><code>x = 5; </code></pre> <ul> <li>Creates a new variable.</li> </ul> <p>or</p> <ul> <li>Sets an existing one.</li> </ul>
9
2009-02-20T22:34:34Z
2,112,033
<p>I just realized there's a more direct answer too:</p> <pre><code>x = 5 def test(): print 'x' in globals() if __name__ == "__main__": test() </code></pre> <p>So if 'variablename' in globals(): the statement is an assignment otherwise the statement is a declaration</p>
-1
2010-01-21T19:04:35Z
[ "python", "variables" ]
What's the reason of providing some of the default methods in the global scope in Python?
571,522
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p> <pre><code>list.len() </code></pre> <p>instead of:</p> <pre><code>len (list) </code></pre> <p>I find methods like len to be harder to discover than inst...
1
2009-02-20T22:37:44Z
571,550
<p>You can write</p> <pre><code>re.match(r"\w+", "dog") </code></pre> <p>instead of</p> <pre><code>pattern = re.compile(r"\w+") pattern.match("dog") </code></pre> <p>Like You noticed, sometimes it doesn't make sense.</p>
-1
2009-02-20T22:47:28Z
[ "python", "function" ]
What's the reason of providing some of the default methods in the global scope in Python?
571,522
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p> <pre><code>list.len() </code></pre> <p>instead of:</p> <pre><code>len (list) </code></pre> <p>I find methods like len to be harder to discover than inst...
1
2009-02-20T22:37:44Z
571,552
<p>Once you learn the "len" method, you know you can apply it to any sequence. You don't have to read the doc for each sequence you encounter to find out whether or not it has a len method. There's an expectation that it does.</p> <p>Built-in functions are not harder to discover because there's a list of built-in me...
2
2009-02-20T22:48:28Z
[ "python", "function" ]
What's the reason of providing some of the default methods in the global scope in Python?
571,522
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p> <pre><code>list.len() </code></pre> <p>instead of:</p> <pre><code>len (list) </code></pre> <p>I find methods like len to be harder to discover than inst...
1
2009-02-20T22:37:44Z
571,626
<p><a href="http://www.python.org/doc/faq/general/#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" rel="nofollow">This FAQ entry</a> might answer your question:</p> <blockquote> <p>4.7 Why does Python use methods for some functionality (e.g. list.index()) b...
4
2009-02-20T23:17:55Z
[ "python", "function" ]
What's the reason of providing some of the default methods in the global scope in Python?
571,522
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p> <pre><code>list.len() </code></pre> <p>instead of:</p> <pre><code>len (list) </code></pre> <p>I find methods like len to be harder to discover than inst...
1
2009-02-20T22:37:44Z
571,632
<p>This question is very similar to <a href="http://stackoverflow.com/questions/83983/why-isnt-the-len-function-inherited-by-dictionaries-and-lists-in-python">this one</a>. And the answers is the same:</p> <p>Because Guido van Rossum, the creator of Python, thinks that prefix notation is more readable in some cases. <...
6
2009-02-20T23:21:22Z
[ "python", "function" ]
What's the reason of providing some of the default methods in the global scope in Python?
571,522
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p> <pre><code>list.len() </code></pre> <p>instead of:</p> <pre><code>len (list) </code></pre> <p>I find methods like len to be harder to discover than inst...
1
2009-02-20T22:37:44Z
571,636
<p>Besides the FAQ answer provided by MrTopf, lists (and other objects) do have a length method <strong>__len__()</strong></p> <p>The len() function is just a shorthand for calling that method.</p>
2
2009-02-20T23:23:03Z
[ "python", "function" ]
What's the reason of providing some of the default methods in the global scope in Python?
571,522
<p>What's the reason of providing some of the default methods in the global scope, like the len function, instead of providing them on an instance level, like:</p> <pre><code>list.len() </code></pre> <p>instead of:</p> <pre><code>len (list) </code></pre> <p>I find methods like len to be harder to discover than inst...
1
2009-02-20T22:37:44Z
571,926
<p>They are fairly discoverable:</p> <pre><code>&gt;&gt;&gt; import __builtin__ &gt;&gt;&gt; dir(__builtin__) ['ArithmeticError', 'AssertionError', ... ... </code></pre> <p>or better</p> <pre><code>&gt;&gt;&gt; help(__builtin__) Help on built-in module __builtin__: NAME __builtin__ - Built-in functions, except...
0
2009-02-21T01:53:36Z
[ "python", "function" ]
The `%` operator
571,538
<p>I want to find all the numbers divisble by all the numbers between 1 and 5. how do I write the program so that if the remainder of 'start' divided by all the numbers that x goes through is equal to 0 that it will print start. Is there any syntax that will calculate what I'm looking for. thanks.</p> <p>import math</...
0
2009-02-20T22:43:06Z
571,618
<p>if I understood correctly you want something like this:</p> <pre><code>start = 1 while (True): flgEvenlyDiv = True for x in range(1, 5): if (start % x != 0): flgEvenlyDiv = False break if (flgEvenlyDiv == True): print start sta...
0
2009-02-20T23:13:19Z
[ "python", "math" ]
The `%` operator
571,538
<p>I want to find all the numbers divisble by all the numbers between 1 and 5. how do I write the program so that if the remainder of 'start' divided by all the numbers that x goes through is equal to 0 that it will print start. Is there any syntax that will calculate what I'm looking for. thanks.</p> <p>import math</...
0
2009-02-20T22:43:06Z
571,647
<p>First of all, you seem to ask for all multiples of 60. Those can be rendered easily like this (beware, this is an infinite loop):</p> <pre><code>from itertools import count for i in count(): print i*60 </code></pre> <p>If you just oversimplified your example, this is a more pythonic (and correct) solution of ...
3
2009-02-20T23:27:58Z
[ "python", "math" ]
Adding elements to python generators
571,850
<p>Is it possible to append elements to a python generator?</p> <p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this singl...
15
2009-02-21T01:11:36Z
571,875
<pre><code>def files_gen(topdir='.'): for root, dirs, files in os.walk(topdir): # ... do some stuff with files for f in files: yield os.path.join(root, f) # ... do other stuff for f in files_gen(): print f </code></pre>
4
2009-02-21T01:25:53Z
[ "python", "append", "generator" ]
Adding elements to python generators
571,850
<p>Is it possible to append elements to a python generator?</p> <p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this singl...
15
2009-02-21T01:11:36Z
571,881
<p>Like this.</p> <pre><code>def threeGens( i, j, k ): for x in range(i): yield x for x in range(j): yield x for x in range(k): yield x </code></pre> <p>Works well. </p>
-1
2009-02-21T01:28:36Z
[ "python", "append", "generator" ]
Adding elements to python generators
571,850
<p>Is it possible to append elements to a python generator?</p> <p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this singl...
15
2009-02-21T01:11:36Z
571,888
<p>You are looking for <a href="http://docs.python.org/library/itertools.html"><code>itertools.chain</code></a>. It will combine multiple iterables into a single one, like this:</p> <pre><code>&gt;&gt;&gt; for i in itertools.chain([1,2,3], [4,5,6]): ... print i ... 1 2 3 4 5 6 </code></pre>
13
2009-02-21T01:31:45Z
[ "python", "append", "generator" ]
Adding elements to python generators
571,850
<p>Is it possible to append elements to a python generator?</p> <p>I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this singl...
15
2009-02-21T01:11:36Z
571,928
<p>This should do it, where <code>directories</code> is your list of directories:</p> <pre><code>import os import itertools generators = [os.walk(d) for d in directories] for root, dirs, files in itertools.chain(*generators): print root, dirs, files </code></pre>
13
2009-02-21T01:54:52Z
[ "python", "append", "generator" ]
Django and Sqlite Concurrency issue
572,009
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following c...
4
2009-02-21T02:48:27Z
572,052
<p>In the following method function</p> <pre><code>def add_active_residents(self): ssa_res = SSA_Resident.objects.select_related(depth=1).filter(ssa=self.ssa, active=True) for r in ssa_res: self.residents.add(r.resident) # Fails Here self.save() </code></pre> <p>Why is there a select_related? You...
4
2009-02-21T03:16:22Z
[ "python", "django", "sqlite", "concurrency" ]
Django and Sqlite Concurrency issue
572,009
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following c...
4
2009-02-21T02:48:27Z
572,181
<p>Sounds like you are actually running a multithreaded application, despite what you say. I am a bit clueless about Django, but I would assume that even though it might be single-threaded, whatever debugging server, or production server you run your application in won't be "inherently single threaded".</p>
1
2009-02-21T03:48:31Z
[ "python", "django", "sqlite", "concurrency" ]
Django and Sqlite Concurrency issue
572,009
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following c...
4
2009-02-21T02:48:27Z
572,280
<p>Are you using Python 2.6?</p> <p>If so, this is (apparently) a known issue that can be mitigated by adding:</p> <pre><code>DATABASE_OPTIONS = {'timeout': 30} </code></pre> <p>to your settings.py</p> <p>See <a href="http://code.djangoproject.com/ticket/9409" rel="nofollow">http://code.djangoproject.com/ticket/940...
2
2009-02-21T04:33:57Z
[ "python", "django", "sqlite", "concurrency" ]
Django and Sqlite Concurrency issue
572,009
<p>I've done a bit of reading related to the concurrency issues with sqlite, but I don't see how they'd apply to Django since it's inherently single threaded. I'm not using any multiprocess modules either. I have absolutely no experience with concurrent programming either, so if someone can identify WHY the following c...
4
2009-02-21T02:48:27Z
575,107
<p>My understanding is that only write operations will result in a db-locked condition. <a href="http://www.sqlite.org/lockingv3.html" rel="nofollow">http://www.sqlite.org/lockingv3.html</a></p> <p>It's hard to say what the problem is without knowing how django is handling sqlite internally.</p> <p>Speaking from usi...
2
2009-02-22T15:53:42Z
[ "python", "django", "sqlite", "concurrency" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
572,554
<p>Order of inputs and labels is provided via normal_row parameter of the form and there are no different row patterns for checkboxes. So there are two ways to do this (in 0.96 version exactly):<br /> 1. override _html_output of the form<br /> 2. use CSS to change position of the label and checkbox</p>
1
2009-02-21T06:52:58Z
[ "python", "django", "checkbox" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
574,460
<p>Here's what I ended up doing. I wrote a custom template stringfilter to switch the tags around. Now, my template code looks like this:</p> <pre><code>{% load pretty_forms %} &lt;form action="." method="POST"&gt; {{ form.as_p|pretty_checkbox }} &lt;p&gt;&lt;input type="submit" value="Submit"&gt;&lt;/p&gt; &lt;/form&...
1
2009-02-22T06:25:08Z
[ "python", "django", "checkbox" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
2,045,308
<p>Here's a solution I've come up with (Django v1.1):</p> <pre><code>{% load myfilters %} [...] {% for field in form %} [...] {% if field.field.widget|is_checkbox %} {{ field }}{{ field.label_tag }} {% else %} {{ field.label_tag }}{{ field }} {% endif %} [...] {% endfor %} </code></pr...
30
2010-01-11T22:06:27Z
[ "python", "django", "checkbox" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
2,308,693
<p>I took the answer from romkyns and made it a little more general</p> <pre><code>def field_type(field, ftype): try: t = field.field.widget.__class__.__name__ return t.lower() == ftype except: pass return False </code></pre> <p>This way you can check the widget type directly with ...
13
2010-02-22T03:52:58Z
[ "python", "django", "checkbox" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
15,308,315
<p>All presented solutions involve template modifications, which are in general rather inefficient concerning performance. Here's a custom widget that does the job:</p> <pre><code>from django import forms from django.forms.fields import BooleanField from django.forms.util import flatatt from django.utils.encoding impo...
10
2013-03-09T07:18:55Z
[ "python", "django", "checkbox" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
17,808,895
<p>I know that the user excluded CSS, but considered the top answers take half an hour of work to so such a small thing, but knowing that details like these are important on a website, I'd settle for the CSS solution.</p> <p>checkbox.css</p> <pre><code>input[type="checkbox"] { float: left; margin-right: 10px;...
1
2013-07-23T11:27:15Z
[ "python", "django", "checkbox" ]
How do I create a Django form that displays a checkbox label to the right of the checkbox?
572,263
<p>When I define a Django form class similar to this:</p> <pre><code>def class MyForm(forms.Form): check = forms.BooleanField(required=True, label="Check this") </code></pre> <p>It expands to HTML that looks like this:</p> <pre><code>&lt;form action="." id="form" method=POST&gt; &lt;p&gt;&lt;label for="check"&gt...
28
2009-02-21T04:18:17Z
28,530,013
<p>Changing checkbox position in Django admin can be quite tricky, but luckily there is a simple solution using custom widget:</p> <pre><code>from django.forms.widgets import Widget, CheckboxInput, boolean_check class RightCheckbox(Widget): render = CheckboxInput().render def __init__(self, attrs=None, check...
0
2015-02-15T19:11:24Z
[ "python", "django", "checkbox" ]
Solr search with escaping solr reserved keywords
572,599
<p>How do i query fields that contain solr reserved keywords as ":" in solr?</p> <p>For instance,</p> <pre><code>q = 'uri:http://www.example.com' </code></pre> <p>throws up an error for "http://www.example.com" containing reserved word ":"</p>
4
2009-02-21T07:46:45Z
572,725
<p>Escape/replace Lucene reserved characters during indexing and store original value in separate field (<code>stored="true" indexed="false"</code> in schema). If you replace reserved characters with space, you'll get <code>http www.example.com</code> in indexed field and <code>http://www.example.com</code> in stored. ...
1
2009-02-21T10:07:15Z
[ "python", "solr", "pysolr" ]
Solr search with escaping solr reserved keywords
572,599
<p>How do i query fields that contain solr reserved keywords as ":" in solr?</p> <p>For instance,</p> <pre><code>q = 'uri:http://www.example.com' </code></pre> <p>throws up an error for "http://www.example.com" containing reserved word ":"</p>
4
2009-02-21T07:46:45Z
573,082
<p>I just tested this and it seem that simply escaping ":" like "\:" does the trick:</p> <pre><code>q = 'uri:http\://www.example.com' </code></pre> <p>For my the index of my own site I tend to simply store the path of the URL though as I know the domain myself so that wasn't an issue for me before. But if you index e...
5
2009-02-21T14:10:54Z
[ "python", "solr", "pysolr" ]
CPython internal structures
572,780
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element p...
3
2009-02-21T10:41:40Z
572,789
<p>I'm a bit confused as to what you're asking. In that code example, nothing should be garbage collected, as you're never actually killing off any references. You're holding a reference to the top level list in a and you're adding nested lists (held in b at each iteration) inside of that. If you remove the 'a =', <...
0
2009-02-21T10:47:02Z
[ "python", "google-app-engine", "data-structures", "internals", "cpython" ]
CPython internal structures
572,780
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element p...
3
2009-02-21T10:41:40Z
572,821
<p>What are you trying to accomplish with the</p> <pre><code>a = b = [] </code></pre> <p>and</p> <pre><code>b = b[0] </code></pre> <p>statements? It's certainly odd to see statements like that in Python, because they don't do what you might naively expect: in that example, <code>a</code> and <code>b</code> are two ...
0
2009-02-21T11:20:33Z
[ "python", "google-app-engine", "data-structures", "internals", "cpython" ]
CPython internal structures
572,780
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element p...
3
2009-02-21T10:41:40Z
573,021
<p>On a 32-bit system, each of the 8000000 lists you create will allocate 20 bytes for the list object itself, plus 16 bytes for a vector of list elements. So you are trying to allocate at least (20+16) * 8000000 = 20168000000 bytes, about 20 GB. And that's in the best case, if the system malloc only allocates exactly ...
8
2009-02-21T13:43:26Z
[ "python", "google-app-engine", "data-structures", "internals", "cpython" ]
CPython internal structures
572,780
<p>GAE has various limitations, one of which is size of biggest allocatable block of memory amounting to 1Mb (now 10 times more, but that doesn't change the question). The limitation means that one cannot put more then some number of items in list() as CPython would try to allocate contiguous memory block for element p...
3
2009-02-21T10:41:40Z
573,452
<p>So that you're aware of it, Python has its own allocator. You can disable it using --without-pyalloc during the configure step.</p> <p>However, the largest arena is 256KB so that shouldn't be the problem. You can also compile Python with debugging enabled, using --with-pydebug. This would give you more information ...
0
2009-02-21T17:43:43Z
[ "python", "google-app-engine", "data-structures", "internals", "cpython" ]
Drawing a chart with proportional X axis in Python
572,808
<p><br /> Is there an easy way to draw a date/value chart in Python, if the "dates" axis had non-equidistant values?<br /> For example, given these: </p> <p>2009-02-01: 10<br /> 2009-02-02: 13<br /> 2009-02-07: 25<br /> 2009-03-01: 80</p> <p>I'd like the chart to show that between the 2nd and 3nd value there's a lon...
2
2009-02-21T11:06:21Z
572,811
<p>If it is enough for you to get a PNG with the chart, you can use <a href="http://code.google.com/intl/de-DE/apis/chart/" rel="nofollow">Google Chart API</a> which will give you a PNG image you can save. You could also use your data to parse the URL using Python.</p> <p>EDIT: <a href="http://chart.apis.google.com/ch...
1
2009-02-21T11:11:21Z
[ "python", "charts" ]
Drawing a chart with proportional X axis in Python
572,808
<p><br /> Is there an easy way to draw a date/value chart in Python, if the "dates" axis had non-equidistant values?<br /> For example, given these: </p> <p>2009-02-01: 10<br /> 2009-02-02: 13<br /> 2009-02-07: 25<br /> 2009-03-01: 80</p> <p>I'd like the chart to show that between the 2nd and 3nd value there's a lon...
2
2009-02-21T11:06:21Z
573,380
<p>you should be able to do this with <a href="http://matplotlib.sourceforge.net/" rel="nofollow">matplotlib</a> barchart. you can use xticks to give the x-axis date values, and the 'left' sizes don't have to be homogeneous. see the <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar"...
2
2009-02-21T17:04:36Z
[ "python", "charts" ]
Python C-API Object Allocation‏
573,275
<p>I want to use the new and delete operators for creating and destroying my objects.</p> <p>The problem is python seems to break it into several stages. tp_new, tp_init and tp_alloc for creation and tp_del, tp_free and tp_dealloc for destruction. However c++ just has new which allocates and fully constructs the objec...
5
2009-02-21T16:01:45Z
573,300
<p>I don't know the python APIs at all, but if python splits up allocation and initialization, you should be able to use placement new.</p> <p>e.g.:</p> <pre><code> // tp_alloc void *buffer = new char[sizeof(MyExtensionObject)]; // tp_init or tp_new (not sure what the distinction is there) new (buffer) MyExtension...
0
2009-02-21T16:16:58Z
[ "c++", "python", "c", "python-3.x", "python-c-api" ]