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 |
|---|---|---|---|---|---|---|---|---|---|
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 717,563
|
<p>It's a technique less practised in Python, in part because "core" classes in Python (those implemented in C) are not really modifiable. In Ruby, on the other hand, because of the way it's implemented internally (not better, just different) just about anything can be modified dynamically.</p>
<p>Philosophically, it's something that tends to be frowned on within the Python community, distinctly less so in the Ruby world. I don't know why you assert that it's more controversial (can you link to an authoritative reference?) - my experience has been that monkey-patching is an accepted technique if one where the user should be aware of possible consequences.</p>
| 20
|
2009-04-04T18:22:54Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 717,947
|
<p>Actually in Python it's a bit harder to modify basic types. </p>
<p>For example imagine, that you redefine integer.</p>
<p>Ruby:</p>
<pre><code>class Fixnum
def *(n)
5
end
end
</code></pre>
<p>Now 2*2 yields 5.</p>
<p>Python:</p>
<pre><code>>>> class int(int):
def __mul__(self, x):
return 5
>>> 2*2
4
>>> int(2)*int(2)
5
</code></pre>
| 2
|
2009-04-04T22:27:42Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 718,062
|
<p>As a Python programmer who has had a taste of Ruby (and likes it), I think there is somewhat of an ironic parallel to when Python was beginning to become popular.</p>
<p>C and Java programmers would âbashâ Python, stating that it wasn't a real language, and that the dynamic nature of its types would be dangerous, and allow people to create âbadâ code. As Python became more popular, and the advantages of its rapid development time became apparent, not to mention the less verbose syntax:</p>
<pre class="lang-java prettyprint-override"><code>// Java
Person p = new Person();
</code></pre>
<pre class="lang-python prettyprint-override"><code># Python
p = Person()
</code></pre>
<p>we began to see some more dynamic features appear in later versions of Java. Autoboxing and -unboxing make it less troublesome to deal with primitives, and Generics allow us to code once and apply it to many types.</p>
<p>It was with some amusement that I saw one of the key flexible features of Ruby â Monkey Patching, being touted as dangerous by the Python crowd. Having started teaching Ruby to students this year, I think that being able to âfixâ the implementation of an existing class, even one that is part of the system, is very powerful.</p>
<p>Sure, you can screw up badly and your program can crash. I can segfault in C pretty easily, too. And Java apps can die flaming death.</p>
<p>The truth is, I see Monkey Patching as the next step in dynamic and meta-programming. Funny, since it has been around since Smalltalk.</p>
| 16
|
2009-04-04T23:48:08Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 718,259
|
<p>In Python, any literal (<code>""</code>, <code>{}</code>, <code>1.0</code>, etc) creates an instance of the standard class, even if you tried to monkeypatch it and redefined the corresponding class in your namespace.</p>
<p>It just won't work how you intended:</p>
<pre class="lang-python prettyprint-override"><code>class str():
# define your custom string type
...
a = "foo" # still a real Python string
a = str("foo") # only this uses your custom class
</code></pre>
| 3
|
2009-04-05T02:57:28Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 721,025
|
<p>I think that monkey patching should only be used as the last solution.</p>
<p>Normally Python programmers know how a class or a method behave. They know that class xxx is doing things in a certain way.</p>
<p>When you monkey patch a class or a method, you are changing it's behavior. Other Python programmers using this class can be very surprised if that class is behaving differently.</p>
<p>The normal way of doing things is subclassing. That way, other programmers know that they are using a different object. They can use the original class or the subclass if they choose to.</p>
| 2
|
2009-04-06T11:18:34Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
| 717,506
|
<p>In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns. </p>
<p>However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language. </p>
<p>Why this distinction? </p>
<p>Does Python include different types of safeguards to minimize the risks of this feature?</p>
| 12
|
2009-04-04T17:54:50Z
| 726,497
|
<p>If you want to do some monkey patching in Python, it is relatively easy, as long as you are not modifying a built-in type (int, float, str).</p>
<pre><code>class SomeClass:
def foo(self):
print "foo"
def tempfunc(self):
print "bar"
SomeClass.bar = tempfunc
del tempfunc
</code></pre>
<p>This will add the bar method to SomeClass and even existing instances of that class can use that injected method.</p>
| 1
|
2009-04-07T16:08:35Z
|
[
"python",
"ruby",
"language-features",
"monkeypatching"
] |
Python and sockets +upnp
| 717,687
|
<p>I have a question about python and sockets. As I understand, if you have router you must open a port before you can use it in your program. But if user can't do that...
I heard something about UPnP. I don't know will it help with my problem, so I've asked you.
Best regards.</p>
| 0
|
2009-04-04T19:46:03Z
| 718,777
|
<p>For UPnP support you can use <a href="http://miniupnp.free.fr" rel="nofollow">MiniUPnP</a> library, it has python support.</p>
| 2
|
2009-04-05T11:18:12Z
|
[
"python"
] |
Python and sockets +upnp
| 717,687
|
<p>I have a question about python and sockets. As I understand, if you have router you must open a port before you can use it in your program. But if user can't do that...
I heard something about UPnP. I don't know will it help with my problem, so I've asked you.
Best regards.</p>
| 0
|
2009-04-04T19:46:03Z
| 27,227,364
|
<p>In usual setups, if you have a home router your machine doesn't have a public IP address, only the router has and does NAT for other machines to access the Internet.</p>
<p>In order to open a "listening" socket so internet machines can reach your private machine, you have to redirect a public port to your local machine.
For example public 1.2.3.4 port 2222 would be redirected to private 192.168.1.42 port 22 so you can ssh your machine from everywhere</p>
<p>Such redirections can be either configured manually on the router, or through protocols such as UPnP IGD, NAT-PMP and PCP</p>
<p>UPNP IGD is the most widespread one. See Miniupnp <a href="http://miniupnp.free.fr/" rel="nofollow">http://miniupnp.free.fr/</a> to the UPNP feature of your router. It has python bindings.</p>
| 0
|
2014-12-01T11:24:28Z
|
[
"python"
] |
Does the Python library httplib2 cache URIs with GET strings?
| 717,700
|
<p>In the following example what is cached correctly? Is there a Vary-Header I have to set server-side for the GET string?</p>
<pre><code>import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://test.com/list/")
resp, content = h.request("http://test.com/list?limit=10")
resp, content = h.request("http://test.com/list?limit=50")
</code></pre>
| 1
|
2009-04-04T19:50:11Z
| 717,829
|
<p>httplib2 uses the full URI for the cache key, so in this case each of the URLs you have in your example will be cached separately by the client.</p>
<p>For the chapter and verse from the <code>__init__.py</code> file for httplib2, if you would like proof, have a look at call to the cache on around line 1000:</p>
<pre><code>cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
</code></pre>
<p>The defrag_uri is defined by the function <code>urlnorm</code> (line 170ish) and includes the scheme, authority, path, and query.</p>
<p>Of course, as you know, the server may interpret the definition of "resource" quite differently and, so, may still return cached content. Since it sounds like you're controlling the server in this case, you have full control there, so no issues. Either way, on the client side, there would be no client-cached values used for the first call to each of the 3 URLs in your examples.</p>
| 4
|
2009-04-04T21:14:14Z
|
[
"python",
"caching",
"httplib2"
] |
can pylons + authkit ignore particular responses with 401 status?
| 717,776
|
<p>i am writing a pylons app, and I am using authkit for authentication/authorization. if a user is not logged in and hits a page that requires authorization, authkit swallows the 401 (not authenticated) response and redirects to a login page. this is great for the web interface, but not great for our web services. when an unauthenticated user this a protected web service, we'd like to set the status of the response to 401.</p>
<p>is there are way to slip some 401 responses past authkit in pylons, but not all?</p>
<p>thanks,
matt</p>
| 2
|
2009-04-04T20:38:46Z
| 719,344
|
<p>It looks like the <a href="http://wiki.pylonshq.com/display/authkitcookbook/Configuration" rel="nofollow">authkit.setup.intercept</a> option is designed to do precisely this.</p>
| 1
|
2009-04-05T17:34:31Z
|
[
"python",
"http",
"pylons",
"authkit"
] |
Self-repairing Python threads
| 717,831
|
<p>I've created a web spider that accesses both a US and EU server. The US and EU servers are the same data structure, but have different data inside them, and I want to collate it all. In order to be nice to the server, there's a wait time between each request. As the program is exactly the same, in order to speed up processing, I've threaded the program so it can access the EU and US servers simultaneously.</p>
<p>This crawling will take on the order of weeks, not days. There will be exceptions, and while I've tried to handle everything inside the program, it's likely something weird might crop up. To be truly defensive about this, I'd like to catch a thread that's failed, log the error and restart it. Worst case I lose a handful of pages out of thousands, which is better than having a thread fail and lose 50% of speed. However, from what I've read, Python threads die silently. Does anyone have any ideas?</p>
<pre><code>class AccessServer(threading.Thread):
def __init__(self, site):
threading.Thread.__init__(self)
self.site = site
self.qm = QueueManager.QueueManager(site)
def run(self):
# Do stuff here
def main():
us_thread = AccessServer(u"us")
us_thread.start()
eu_thread = AccessServer(u"eu")
eu_thread.start()
</code></pre>
| 4
|
2009-04-04T21:14:32Z
| 717,845
|
<p>Can you have e.g. the main thread function as a monitoring thread? E.g. require that the worker thread regularly update some thread-specific timestamp value, and if a thread hasn't updated it's timestamp within a suitable time, have the monitoring thread kill it and restart?</p>
<p>Or, see <a href="http://stackoverflow.com/questions/394895/python-threads-stacksize-and-segfaults">this answer</a></p>
| 3
|
2009-04-04T21:25:17Z
|
[
"python",
"multithreading"
] |
Self-repairing Python threads
| 717,831
|
<p>I've created a web spider that accesses both a US and EU server. The US and EU servers are the same data structure, but have different data inside them, and I want to collate it all. In order to be nice to the server, there's a wait time between each request. As the program is exactly the same, in order to speed up processing, I've threaded the program so it can access the EU and US servers simultaneously.</p>
<p>This crawling will take on the order of weeks, not days. There will be exceptions, and while I've tried to handle everything inside the program, it's likely something weird might crop up. To be truly defensive about this, I'd like to catch a thread that's failed, log the error and restart it. Worst case I lose a handful of pages out of thousands, which is better than having a thread fail and lose 50% of speed. However, from what I've read, Python threads die silently. Does anyone have any ideas?</p>
<pre><code>class AccessServer(threading.Thread):
def __init__(self, site):
threading.Thread.__init__(self)
self.site = site
self.qm = QueueManager.QueueManager(site)
def run(self):
# Do stuff here
def main():
us_thread = AccessServer(u"us")
us_thread.start()
eu_thread = AccessServer(u"eu")
eu_thread.start()
</code></pre>
| 4
|
2009-04-04T21:14:32Z
| 717,847
|
<p>Just use a <code>try: ... except: ...</code> block in the <code>run</code> method. If something weird happens that causes the thread to fail, it's highly likely that an error will be thrown somewhere in your code (as opposed to in the threading subsystem itself); this way you can catch it, log it, and restart the thread. It's your call whether you want to actually shut down the thread and start a new one, or just enclose the <code>try/except</code> block in a <code>while</code> loop so the same thread keeps running.</p>
<p>Another solution, if you suspect that something really weird might happen which you can't detect through Python's error handling mechanism, would be to start a monitor thread that periodically checks to see that the other threads are running properly.</p>
| 8
|
2009-04-04T21:25:52Z
|
[
"python",
"multithreading"
] |
Paypal NVP API with Django
| 717,911
|
<p>I am looking into using the paypal NVP API to allow users to pay on my website for a recurring subscription. </p>
<p>I have a few questions about the requirements. Will my site have to meet the "PCI Compliance" stuff. I guess I will have to get an SSL certificate and is there anything else that is required or that I need to know about? </p>
| 3
|
2009-04-04T22:06:58Z
| 717,974
|
<p>There is nothing forcing you to meet PCI Compliance and use SSL, but you should anyway to limit your liability and inspire a little customer trust. </p>
<p>I thought I read something on the <a href="http://satchmoproject.com" rel="nofollow">Satchmo</a> Developer's Google group about a person implementing PayPal NVP and having a patch.</p>
| 0
|
2009-04-04T22:44:59Z
|
[
"python",
"django",
"paypal"
] |
Paypal NVP API with Django
| 717,911
|
<p>I am looking into using the paypal NVP API to allow users to pay on my website for a recurring subscription. </p>
<p>I have a few questions about the requirements. Will my site have to meet the "PCI Compliance" stuff. I guess I will have to get an SSL certificate and is there anything else that is required or that I need to know about? </p>
| 3
|
2009-04-04T22:06:58Z
| 1,290,156
|
<p>I know this question is a bit out of date, but I wanted to add a note that I've recently released an <a href="http://www.chickenwingsw.com/scratches/python/paypal-on-python" rel="nofollow">open source Python API to the PayPal NVP interface</a>.</p>
| 0
|
2009-08-17T20:12:32Z
|
[
"python",
"django",
"paypal"
] |
How to install SimpleJson Package for Python
| 718,040
|
<p><a href="http://pypi.python.org/pypi/simplejson">http://pypi.python.org/pypi/simplejson</a></p>
<p>I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..</p>
<p>I am on a Windows System</p>
| 32
|
2009-04-04T23:31:10Z
| 718,073
|
<p>I would recommend <a href="http://pypi.python.org/pypi/setuptools#windows">EasyInstall</a>, a package management application for Python.</p>
<p>Once you've installed EasyInstall, you should be able to go to a command window and type:</p>
<pre><code>easy_install simplejson
</code></pre>
<p>This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like <code>C:\Python25\Scripts</code>).</p>
| 43
|
2009-04-04T23:54:42Z
|
[
"python",
"simplejson"
] |
How to install SimpleJson Package for Python
| 718,040
|
<p><a href="http://pypi.python.org/pypi/simplejson">http://pypi.python.org/pypi/simplejson</a></p>
<p>I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..</p>
<p>I am on a Windows System</p>
| 32
|
2009-04-04T23:31:10Z
| 718,097
|
<p>If you have Python 2.6 installed then you already have simplejson - just import <code>json</code>; it's the same thing.</p>
| 15
|
2009-04-05T00:12:08Z
|
[
"python",
"simplejson"
] |
How to install SimpleJson Package for Python
| 718,040
|
<p><a href="http://pypi.python.org/pypi/simplejson">http://pypi.python.org/pypi/simplejson</a></p>
<p>I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..</p>
<p>I am on a Windows System</p>
| 32
|
2009-04-04T23:31:10Z
| 3,674,861
|
<p>Download the source code, unzip it to and directory, and execute python setup.py install. </p>
| 3
|
2010-09-09T08:16:35Z
|
[
"python",
"simplejson"
] |
How to install SimpleJson Package for Python
| 718,040
|
<p><a href="http://pypi.python.org/pypi/simplejson">http://pypi.python.org/pypi/simplejson</a></p>
<p>I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..</p>
<p>I am on a Windows System</p>
| 32
|
2009-04-04T23:31:10Z
| 12,865,599
|
<p>You can import json as simplejson like this:</p>
<pre><code>import json as simplejson
</code></pre>
<p>and keep backward compatibility.</p>
| 4
|
2012-10-12T19:12:25Z
|
[
"python",
"simplejson"
] |
How to install SimpleJson Package for Python
| 718,040
|
<p><a href="http://pypi.python.org/pypi/simplejson">http://pypi.python.org/pypi/simplejson</a></p>
<p>I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..</p>
<p>I am on a Windows System</p>
| 32
|
2009-04-04T23:31:10Z
| 16,538,587
|
<p>Really simple way is:</p>
<pre><code>pip install simplejson
</code></pre>
| 17
|
2013-05-14T08:39:32Z
|
[
"python",
"simplejson"
] |
Unable to put Python code to Joomla
| 718,498
|
<p>I have a Python code from Google app engine.
I need to implement it to Joomla.</p>
<p><strong>How can you implement Python code to Joomla?</strong></p>
<p><strong>[edit after the 1st answer]</strong></p>
<p>It is enough for me that I can put the code to a module position.</p>
| 0
|
2009-04-05T07:08:27Z
| 718,511
|
<p>Joomla is PHP based whereas Google App Engine is Python based (and tends to use Django). Your best bet is to either find an alternative to the python code, find someone to translate it, or learn python and manually translate it. </p>
<p>There's no straight python to php conversion though.</p>
<p>EDIT: but if you really want to be adventurous, you can try the Python in PHP project which is still early phase and looks to be someone's side project: <a href="http://www.csh.rit.edu/~jon/projects/pip/" rel="nofollow">http://www.csh.rit.edu/~jon/projects/pip/</a></p>
| 2
|
2009-04-05T07:17:23Z
|
[
"python",
"joomla"
] |
Changing the title of a Tab in wx.Notebook
| 718,546
|
<p>I'm experimenting with wxPython,</p>
<p>I have a tabbed interface (notebook) and each tab is basically a file list view (yes, I'm trying to make a file manager)</p>
<p>The file list inherits from wx.ListCtrl, and the tabbed interface inherits from wx.Notebook</p>
<p>I'm just starting .. and I had it so double clicking on a folder will cd into that folder, but I want to also change the title of the tab.</p>
<p>How do I do that?</p>
<p>I have the object that represents the file list and the title I want to set it to,</p>
<p><code>[</code> <strong>EDIT</strong> <code>Notebook.SetPageText()</code> takes a number, so I can't pass the tab object directly to it <code>]</code></p>
<p>my current approach is to cycle through the tabs until one of them matches my tab:</p>
<pre><code> for tab_id in range(self.GetPageCount()):
if self.GetPage(tab_id) == tab:
self.SetPageText(tab_id, title)
break
</code></pre>
<p>This seems rather naive though, isn't there a smarter approach?</p>
| 3
|
2009-04-05T07:49:10Z
| 718,566
|
<p>As .GetPage returns a wx.Window, I think <code>tab.Label = title</code> should work.</p>
| -1
|
2009-04-05T08:08:05Z
|
[
"python",
"wxpython",
"wxwidgets",
"tabbed-interface"
] |
Changing the title of a Tab in wx.Notebook
| 718,546
|
<p>I'm experimenting with wxPython,</p>
<p>I have a tabbed interface (notebook) and each tab is basically a file list view (yes, I'm trying to make a file manager)</p>
<p>The file list inherits from wx.ListCtrl, and the tabbed interface inherits from wx.Notebook</p>
<p>I'm just starting .. and I had it so double clicking on a folder will cd into that folder, but I want to also change the title of the tab.</p>
<p>How do I do that?</p>
<p>I have the object that represents the file list and the title I want to set it to,</p>
<p><code>[</code> <strong>EDIT</strong> <code>Notebook.SetPageText()</code> takes a number, so I can't pass the tab object directly to it <code>]</code></p>
<p>my current approach is to cycle through the tabs until one of them matches my tab:</p>
<pre><code> for tab_id in range(self.GetPageCount()):
if self.GetPage(tab_id) == tab:
self.SetPageText(tab_id, title)
break
</code></pre>
<p>This seems rather naive though, isn't there a smarter approach?</p>
| 3
|
2009-04-05T07:49:10Z
| 718,597
|
<p>I think doing something like this helps :</p>
<pre><code>
notebook.get_tab_label(notebook.get_nth_page(your_page_number)).set_text("Your text")
</code></pre>
<p>If you want to have a reference to the current tab always, you must connect the "switch-page" signal, and save the page in a variable.</p>
| 0
|
2009-04-05T08:48:31Z
|
[
"python",
"wxpython",
"wxwidgets",
"tabbed-interface"
] |
Changing the title of a Tab in wx.Notebook
| 718,546
|
<p>I'm experimenting with wxPython,</p>
<p>I have a tabbed interface (notebook) and each tab is basically a file list view (yes, I'm trying to make a file manager)</p>
<p>The file list inherits from wx.ListCtrl, and the tabbed interface inherits from wx.Notebook</p>
<p>I'm just starting .. and I had it so double clicking on a folder will cd into that folder, but I want to also change the title of the tab.</p>
<p>How do I do that?</p>
<p>I have the object that represents the file list and the title I want to set it to,</p>
<p><code>[</code> <strong>EDIT</strong> <code>Notebook.SetPageText()</code> takes a number, so I can't pass the tab object directly to it <code>]</code></p>
<p>my current approach is to cycle through the tabs until one of them matches my tab:</p>
<pre><code> for tab_id in range(self.GetPageCount()):
if self.GetPage(tab_id) == tab:
self.SetPageText(tab_id, title)
break
</code></pre>
<p>This seems rather naive though, isn't there a smarter approach?</p>
| 3
|
2009-04-05T07:49:10Z
| 718,621
|
<p>I don't know wxPython, but I assume it wraps all the methods of the C++ classes.</p>
<p>There is <em>wxNotebook::GetSelection()</em> which returns <em>wxNOT_FOUND</em> or the index of the selected page, which can then be used to call <em>wxNotebook::SetPageText()</em>.</p>
<p>Or use <em>wxNotebook::GetPage()</em> with this index to check whether it is equal to <em>tab</em>.</p>
| 2
|
2009-04-05T09:12:20Z
|
[
"python",
"wxpython",
"wxwidgets",
"tabbed-interface"
] |
App Engine - problem trying to set a Model property value
| 718,553
|
<p>I'm pretty new to app engine, and I'm trying to set a bit of text into the app engine database for the first time.</p>
<p>Here's my code:</p>
<pre><code>def setVenueIntroText(text):
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
venue_obj.intro_text = text # Works if I comment out
db.put(venue_obj) # These two lines
</code></pre>
<p>This throws some sort of exception - I can't tell what it is though because of my django 1.02 setup. </p>
<p>Ok, I gave the code in the answer below a go, and it worked after deleting my datastores, but I'm still not satisfied.</p>
<p>Here's an update:</p>
<p>I've modified my code to something that looks like it makes sense to me. The getVenueIntroText doesn't complain when I call it - I haven't got any items in the database btw.</p>
<p>When I call setVenueIntroText, it doesn't like what I'm doing for some reason - if someone knows the reason why, I'd really like to know :)</p>
<p>Here's my latest attempt:</p>
<pre><code>def getVenueIntroText():
venue_info = ""
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
if venue_obj is not None:
venue_info = venue_obj.intro_text
return venue_info
def setVenueIntroText(text):
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
if venue_obj is None:
venue_obj = Venue(intro_text = text)
else:
venue_obj.intro_text = text
db.put(venue_obj)
</code></pre>
| 1
|
2009-04-05T07:59:07Z
| 718,584
|
<p>I think this should work:</p>
<pre><code>def setVenueIntroText(text):
query = db.GqlQuery("SELECT * FROM Venue")
for result in query:
result.intro_text = text
db.put(result)
</code></pre>
| 1
|
2009-04-05T08:30:22Z
|
[
"python",
"google-app-engine",
"bigtable"
] |
App Engine - problem trying to set a Model property value
| 718,553
|
<p>I'm pretty new to app engine, and I'm trying to set a bit of text into the app engine database for the first time.</p>
<p>Here's my code:</p>
<pre><code>def setVenueIntroText(text):
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
venue_obj.intro_text = text # Works if I comment out
db.put(venue_obj) # These two lines
</code></pre>
<p>This throws some sort of exception - I can't tell what it is though because of my django 1.02 setup. </p>
<p>Ok, I gave the code in the answer below a go, and it worked after deleting my datastores, but I'm still not satisfied.</p>
<p>Here's an update:</p>
<p>I've modified my code to something that looks like it makes sense to me. The getVenueIntroText doesn't complain when I call it - I haven't got any items in the database btw.</p>
<p>When I call setVenueIntroText, it doesn't like what I'm doing for some reason - if someone knows the reason why, I'd really like to know :)</p>
<p>Here's my latest attempt:</p>
<pre><code>def getVenueIntroText():
venue_info = ""
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
if venue_obj is not None:
venue_info = venue_obj.intro_text
return venue_info
def setVenueIntroText(text):
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
if venue_obj is None:
venue_obj = Venue(intro_text = text)
else:
venue_obj.intro_text = text
db.put(venue_obj)
</code></pre>
| 1
|
2009-04-05T07:59:07Z
| 719,551
|
<p>I think the main problem was that I couldn't see the error messages - really stupid of me, I forgot to put DEBUG = True in my settings.py</p>
<p>It turns out I needed a multiline=True in my StringProperty</p>
<p>Django is catching my exceptions for me.</p>
| 1
|
2009-04-05T19:42:56Z
|
[
"python",
"google-app-engine",
"bigtable"
] |
Reversible version of compile() in Python
| 718,769
|
<p>I'm trying to make a function in Python that does the equivalent of compile(), but also lets me get the original string back. Let's call those two functions comp() and decomp(), for disambiguation purposes. That is,</p>
<pre><code>a = comp("2 * (3 + x)", "", "eval")
eval(a, dict(x=3)) # => 12
decomp(a) # => "2 * (3 + x)"
</code></pre>
<p>The returned string does not have to be <em>identical</em> ("2*(3+x)" would be acceptable), but it needs to be basically the same ("2 * x + 6" would not be).</p>
<p>Here's what I've tried that <em>doesn't</em> work:</p>
<ul>
<li>Setting an attribute on the code object returned by compile. You can't set custom attributes on code objects.</li>
<li>Subclassing code so I can add the attribute. code cannot be subclassed.</li>
<li>Setting up a WeakKeyDictionary mapping code objects to the original strings. code objects cannot be weakly referenced.</li>
</ul>
<p>Here's what does work, with issues:</p>
<ul>
<li>Passing in the original code string for the filename to compile(). However, I lose the ability to actually keep a filename there, which I'd like to also do.</li>
<li>Keeping a real dictionary mapping code objects to strings. This leaks memory, although since compiling is rare, it's acceptable for my current use case. I could probably run the keys through gc.get_referrers periodically and kill off dead ones, if I had to.</li>
</ul>
| 3
|
2009-04-05T11:12:02Z
| 718,878
|
<p>My approach would be to wrap the code object in another object. Something like this:</p>
<pre><code>class CodeObjectEnhanced(object):
def __init__(self, *args):
self.compiled = compile(*args)
self.original = args[0]
def comp(*args):
return CodeObjectEnhanced(*args)
</code></pre>
<p>Then whenever you need the code object itself, you use a.compiled, and whenever you need the original, you use a.original. There may be a way to get eval to treat the new class as though it were an ordinary code object, redirecting the function to call eval(self.compiled) instead.</p>
<p>One advantage of this is the original string is deleted at the same time as the code object. However you do this, I think storing the original string is probably the best approach, as you end up with the exact string you used, not just an approximation.</p>
| 4
|
2009-04-05T12:39:41Z
|
[
"python",
"metaprogramming"
] |
Reversible version of compile() in Python
| 718,769
|
<p>I'm trying to make a function in Python that does the equivalent of compile(), but also lets me get the original string back. Let's call those two functions comp() and decomp(), for disambiguation purposes. That is,</p>
<pre><code>a = comp("2 * (3 + x)", "", "eval")
eval(a, dict(x=3)) # => 12
decomp(a) # => "2 * (3 + x)"
</code></pre>
<p>The returned string does not have to be <em>identical</em> ("2*(3+x)" would be acceptable), but it needs to be basically the same ("2 * x + 6" would not be).</p>
<p>Here's what I've tried that <em>doesn't</em> work:</p>
<ul>
<li>Setting an attribute on the code object returned by compile. You can't set custom attributes on code objects.</li>
<li>Subclassing code so I can add the attribute. code cannot be subclassed.</li>
<li>Setting up a WeakKeyDictionary mapping code objects to the original strings. code objects cannot be weakly referenced.</li>
</ul>
<p>Here's what does work, with issues:</p>
<ul>
<li>Passing in the original code string for the filename to compile(). However, I lose the ability to actually keep a filename there, which I'd like to also do.</li>
<li>Keeping a real dictionary mapping code objects to strings. This leaks memory, although since compiling is rare, it's acceptable for my current use case. I could probably run the keys through gc.get_referrers periodically and kill off dead ones, if I had to.</li>
</ul>
| 3
|
2009-04-05T11:12:02Z
| 719,902
|
<p>This is kind of a weird problem, and my initial reaction is that you might be better off doing something else entirely to accomplish whatever it is you're trying to do. But it's still an interesting question, so here's my crack at it: I make the original code source an unused constant of the code object.</p>
<pre><code>import types
def comp(source, *args, **kwargs):
"""Compile the source string; takes the same arguments as builtin compile().
Modifies the resulting code object so that the original source can be
recovered with decomp()."""
c = compile(source, *args, **kwargs)
return types.CodeType(c.co_argcount, c.co_nlocals, c.co_stacksize,
c.co_flags, c.co_code, c.co_consts + (source,), c.co_names,
c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno,
c.co_lnotab, c.co_freevars, c.co_cellvars)
def decomp(code_object):
return code_object.co_consts[-1]
</code></pre>
<p><hr /></p>
<pre><code>>>> a = comp('2 * (3 + x)', '', 'eval')
>>> eval(a, dict(x=3))
12
>>> decomp(a)
'2 * (3 + x)'
</code></pre>
| 6
|
2009-04-05T23:51:08Z
|
[
"python",
"metaprogramming"
] |
Django Template - New Variable Declaration
| 719,127
|
<p>Let me preface by I am just starting Python so if this is really a simple question ^_^</p>
<p>I have a html file with the following content:</p>
<pre><code> {%for d in results%}
<div class="twt">
<img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
<span class="date">{{ d.created_at }}</span>
</div>
{% endfor %}
</code></pre>
<p>which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.</p>
<p>I tried doing:</p>
<pre><code>{{ RowNumber = 0}}
{{ RowNumber ++ }}
</code></pre>
<p>But it doesn't seem to allow me to declare RowNumber.</p>
| 13
|
2009-04-05T15:37:15Z
| 719,132
|
<p>Check out the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for">documentation</a> on the <code>for</code> loop.</p>
<p>It automatically creates a variable called <code>forloop.counter</code> that holds the current iteration index.</p>
<p>As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags">custom tags</a> but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#add">add</a> filter. Likewise, you can <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters">create your own filters</a> just like with tags.</p>
| 20
|
2009-04-05T15:38:44Z
|
[
"python",
"django",
"django-templates"
] |
Django Template - New Variable Declaration
| 719,127
|
<p>Let me preface by I am just starting Python so if this is really a simple question ^_^</p>
<p>I have a html file with the following content:</p>
<pre><code> {%for d in results%}
<div class="twt">
<img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
<span class="date">{{ d.created_at }}</span>
</div>
{% endfor %}
</code></pre>
<p>which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.</p>
<p>I tried doing:</p>
<pre><code>{{ RowNumber = 0}}
{{ RowNumber ++ }}
</code></pre>
<p>But it doesn't seem to allow me to declare RowNumber.</p>
| 13
|
2009-04-05T15:37:15Z
| 5,040,262
|
<p>If you want to set any variable inside a Django template, you can use <a href="http://www.soyoucode.com/2011/set-variable-django-template" rel="nofollow">this small template tag I've written</a>.</p>
| 7
|
2011-02-18T10:38:13Z
|
[
"python",
"django",
"django-templates"
] |
Django Template - New Variable Declaration
| 719,127
|
<p>Let me preface by I am just starting Python so if this is really a simple question ^_^</p>
<p>I have a html file with the following content:</p>
<pre><code> {%for d in results%}
<div class="twt">
<img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
<span class="date">{{ d.created_at }}</span>
</div>
{% endfor %}
</code></pre>
<p>which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.</p>
<p>I tried doing:</p>
<pre><code>{{ RowNumber = 0}}
{{ RowNumber ++ }}
</code></pre>
<p>But it doesn't seem to allow me to declare RowNumber.</p>
| 13
|
2009-04-05T15:37:15Z
| 8,127,934
|
<p>In template:</p>
<pre><code>{% for outer_obj in outer_list %}
{% for inner_obj in inner_list %}
{% increment_counter forloop.counter0 forloop.parentloop.counter0 outer_list.count %}
{% endfor %}
{% endfor %}
</code></pre>
<p>Templatetag:</p>
<pre><code>@register.simple_tag
def increment_counter(outer, inner, outer_loop_length):
return outer + inner * outer_loop_length + inner * (outer_loop_length - 1)
</code></pre>
<p>Result: 0 1 2 3 ...</p>
| 2
|
2011-11-14T20:51:48Z
|
[
"python",
"django",
"django-templates"
] |
Django Template - New Variable Declaration
| 719,127
|
<p>Let me preface by I am just starting Python so if this is really a simple question ^_^</p>
<p>I have a html file with the following content:</p>
<pre><code> {%for d in results%}
<div class="twt">
<img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
<span class="date">{{ d.created_at }}</span>
</div>
{% endfor %}
</code></pre>
<p>which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.</p>
<p>I tried doing:</p>
<pre><code>{{ RowNumber = 0}}
{{ RowNumber ++ }}
</code></pre>
<p>But it doesn't seem to allow me to declare RowNumber.</p>
| 13
|
2009-04-05T15:37:15Z
| 19,348,859
|
<p>this is how to do it:</p>
<pre><code>{% with name="World" greeting="Hello" %}
<html>
<div>{{ greeting }} {{name}}!</div>
</html>
{% endwith %}
</code></pre>
<p>see also: <a href="https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#with" rel="nofollow">with tag</a></p>
<p>by <a href="http://stackoverflow.com/users/52207/john">john</a> and <a href="http://stackoverflow.com/users/1178000/yardenst">yarden</a> from this post:
<a href="http://stackoverflow.com/questions/1070398/how-to-set-a-value-of-a-variable-inside-a-template-code">How to set a value of a variable inside a template code?</a></p>
| 3
|
2013-10-13T18:43:18Z
|
[
"python",
"django",
"django-templates"
] |
How can you make a vote-up-down button like in Stackoverflow?
| 719,194
|
<p><strong>Problems</strong></p>
<ol>
<li>how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease</li>
<li>how to save the action af an user to an variable NumberOfVotesOfQuestionID</li>
</ol>
<p>I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes.</p>
<p><strong>How can you solve those problems?</strong></p>
<p>[edit]</p>
<p>The server-side programming language is Python.</p>
| 30
|
2009-04-05T16:07:30Z
| 719,249
|
<p>I thnk the answers for these questions are to long for stackoverflow.</p>
<p>I'd recommend storing the votes in a Database.</p>
<p>You don't mention a server-side programming language.</p>
<p>please give us some more information</p>
<p><a href="http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=109" rel="nofollow">This</a> might help you get started</p>
| 0
|
2009-04-05T16:28:28Z
|
[
"javascript",
"python",
"html",
"ajax"
] |
How can you make a vote-up-down button like in Stackoverflow?
| 719,194
|
<p><strong>Problems</strong></p>
<ol>
<li>how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease</li>
<li>how to save the action af an user to an variable NumberOfVotesOfQuestionID</li>
</ol>
<p>I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes.</p>
<p><strong>How can you solve those problems?</strong></p>
<p>[edit]</p>
<p>The server-side programming language is Python.</p>
| 30
|
2009-04-05T16:07:30Z
| 719,293
|
<p>You create the buttons, which can be links or images or whatever. Now hook a JavaScript function up to each button's click event. On clicking, the function fires and</p>
<ul>
<li>Sends a request to the server code that says, more or less, +1 or -1.</li>
<li>Server code takes over. This will vary wildly depending on what framework you use (or don't) and a bunch of other things.</li>
<li>Code connects to the database and runs a query to +1 or -1 the score. How this happens will vary wildly depending on your database design, but it'll be something like <code>UPDATE posts SET score=score+1 WHERE score_id={{insert id here}};</code>.</li>
<li>Depending on what the database says, the server returns a success code or a failure code as the AJAX request response.</li>
<li>Response gets sent to AJAX, asynchronously.</li>
<li>The JS response function updates the score if it's a success code, displays an error if it's a failure.</li>
</ul>
<p>You <em>can</em> store the code in a variable, but this is complicated and depends on how well you know the semantics of your code's runtime environment. It eventually needs to be pushed to persistent storage anyway, so using the database 100% is a good initial solution. When the time for optimizing performance comes, there are enough software in the world to cache database queries to make you feel woozy so it's not that big a deal.</p>
| 3
|
2009-04-05T17:02:04Z
|
[
"javascript",
"python",
"html",
"ajax"
] |
How can you make a vote-up-down button like in Stackoverflow?
| 719,194
|
<p><strong>Problems</strong></p>
<ol>
<li>how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease</li>
<li>how to save the action af an user to an variable NumberOfVotesOfQuestionID</li>
</ol>
<p>I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes.</p>
<p><strong>How can you solve those problems?</strong></p>
<p>[edit]</p>
<p>The server-side programming language is Python.</p>
| 30
|
2009-04-05T16:07:30Z
| 719,475
|
<p>This is a dirty/untested theoretical implementation using jQuery/Django.</p>
<p>We're going to assume the voting up and down is for questions/answers like on this site, but that can obviously be adjusted to your real life use case.</p>
<h3>The template</h3>
<pre><code><div id="answer_595" class="answer">
<img src="vote_up.png" class="vote up">
<div class="score">0</div>
<img src="vote_down.png" class="vote down">
Blah blah blah this is my answer.
</div>
<div id="answer_596" class="answer">
<img src="vote_up.png" class="vote up">
<div class="score">0</div>
<img src="vote_down.png" class="vote down">
Blah blah blah this is my other answer.
</div>
</code></pre>
<h3>Javascript</h3>
<pre><code>$(function() {
$('div.answer img.vote').click(function() {
var id = $(this).parents('div.answer').attr('id').split('_')[1];
var vote_type = $(this).hasClass('up') ? 'up' : 'down';
if($(this).hasClass('selected')) {
$.post('/vote/', {id: id, type: vote_type}, function(json) {
if(json.success == 'success') {
$('#answer_' + id)
.find('img.' + vote_type);
.attr('src', 'vote_' + vote_type + '_selected.png')
.addClass('selected');
$('div.score', '#answer_' + id).html(json.score);
}
});
} else {
$.post('/remove_vote/', {id: id, type: vote_type}, function(json) {
if(json.success == 'success') {
$('#answer_' + id)
.find('img.' + vote_type);
.attr('src', 'vote_' + vote_type + '.png')
.removeClass('selected');
$('div.score', '#answer_' + id).html(json.score);
}
});
}
});
});
</code></pre>
<h3>Django views</h3>
<pre><code>def vote(request):
if request.method == 'POST':
try:
answer = Answer.objects.get(pk=request.POST['id'])
except Answer.DoesNotExist:
return HttpResponse("{'success': 'false'}")
try:
vote = Vote.objects.get(answer=answer, user=request.user)
except Vote.DoesNotExist:
pass
else:
return HttpResponse("{'success': 'false'}")
if request.POST['type'] == 'up':
answer.score = answer.score + 1
else:
answer.score = answer.score - 1
answer.save()
Vote.objects.create(answer=answer,
user=request.user,
type=request.POST['type'])
return HttpResponse("{'success':'true', 'score':" + answer.score + "}")
else:
raise Http404('What are you doing here?')
def remove_vote(request):
if request.method == 'POST':
try:
answer = Answer.objects.get(pk=request.POST['id'])
except Answer.DoesNotExist:
return HttpResponse("{'success': 'false'}")
try:
vote = Vote.objects.get(answer=answer, user=request.user)
except Vote.DoesNotExist:
return HttpResponse("{'success': 'false'}")
else:
vote.delete()
if request.POST['type'] == 'up':
answer.score = answer.score - 1
else:
answer.score = answer.score + 1
answer.save()
return HttpResponse("{'success':'true', 'score':" + answer.score + "}")
else:
raise Http404('What are you doing here?')
</code></pre>
<p>Yikes. When I started answering this question I didn't mean to write this much but I got carried away a little bit. You're still missing an initial request to get all the votes when the page is first loaded and such, but I'll leave that as an exercise to the reader. Anyhow, if you <em>are</em> in fact using Django and are interested in a more tested/real implemention of the Stackoverflow voting, I suggest you check out the <a href="http://cnprog.googlecode.com/svn/trunk/">source code</a> for cnprog.com, a Chinese clone of Stackoverflow written in Python/Django. They released their code and it is pretty decent.</p>
| 57
|
2009-04-05T18:55:08Z
|
[
"javascript",
"python",
"html",
"ajax"
] |
How can you make a vote-up-down button like in Stackoverflow?
| 719,194
|
<p><strong>Problems</strong></p>
<ol>
<li>how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease</li>
<li>how to save the action af an user to an variable NumberOfVotesOfQuestionID</li>
</ol>
<p>I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes.</p>
<p><strong>How can you solve those problems?</strong></p>
<p>[edit]</p>
<p>The server-side programming language is Python.</p>
| 30
|
2009-04-05T16:07:30Z
| 719,606
|
<p>A couple of points no one has mentioned:</p>
<ul>
<li>You don't want to use GET when changing the state of your database. Otherwise I could put an image on my site with <code>src="http://stackoverflow.com/question_555/vote/up/answer_3/"</code>.</li>
<li>You also need <a href="http://docs.djangoproject.com/en/dev/ref/contrib/csrf/">csrf (Cross Site Request Forgery) protection</a></li>
<li>You must record <strong>who makes each vote</strong> to avoid people voting more than once for a particular question. Whether this is by IP address or userid.</li>
</ul>
| 7
|
2009-04-05T20:16:48Z
|
[
"javascript",
"python",
"html",
"ajax"
] |
Python 3: formatting zip module arguments correctly (newb)
| 719,503
|
<p>Please tell me why this code fails. I am new and I don't understand why my formatting of my zip arguments is incorrect. Since I am unsure how to communicate best so I will show the code, the error message, and what I believe is happening.</p>
<pre><code>#!c:\python30
# Filename: backup_ver5.py
import os
import time
import zipfile
source = r'"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list"'
target_dir = r'C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir'
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = input('Enter a comment --> ')
if len(comment) == 0:
target = '"' + today + os.sep + now + '.zip' + '"'
else:
target = '"' + today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip' + '"'
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
print(target)
print(source)
zip_command = zipfile.ZipFile(target, 'w').write(source)
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
enter code here
</code></pre>
<p>I recieve this error message:</p>
<pre><code>Enter a comment -->
"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir\20090
405\134614.zip"
"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list"
Traceback (most recent call last):
File "C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_ve
r5.py", line 32, in <module>
zip_command = zipfile.ZipFile(target, 'w').write(source)
File "c:\python30\lib\zipfile.py", line 683, in __init__
self.fp = io.open(file, modeDict[mode])
File "C:\Python30\lib\io.py", line 222, in open
closefd)
File "C:\Python30\lib\io.py", line 615, in __init__
_fileio._FileIO.__init__(self, name, mode, closefd)
IOError: [Errno 22] Invalid argument: '"C:\\Documents and Settings\\Benjamin Ser
rato\\My Documents\\python\\backup_dir\\20090405\\134614.zip"'
</code></pre>
<p>The two print tests before <code>zip_command</code> is assigned tell me that the two strings are being passed to <code>zipfile.ZipFile()</code> correctly. The traceback tells me I am not calling <code>zipfile.ZipFile()</code> correctly. The error in <code>__init__</code> makes me more sure of this. Last, the problem seems to be that I am causing my path string to have double backslashes. I can't follow why the IOError shows that.</p>
<p>I used <a href="http://docs.python.org/dev/3.0/library/zipfile.html" rel="nofollow">this site</a> to figure out how to use <code>zipfile</code>. <code>zipfile</code> is a class, I import it at the start of the program then I use it and its primary method. I pass the file I would like to write to <code>zipfile.ZipFile('file to write', 'mode')</code> and set the program to open an object set to be writable. Then the command writes the file to the destination folder with a sub-method like so, <code>"".zipfile('files to write')</code>.</p>
<p>Where am I going wrong?</p>
| 1
|
2009-04-05T19:16:12Z
| 719,516
|
<p>Looks like it's because you have an extra pair of double quotes around your pathname. Remove the double quotes, and see if it works.</p>
| 3
|
2009-04-05T19:21:44Z
|
[
"python",
"zip"
] |
Python 3: formatting zip module arguments correctly (newb)
| 719,503
|
<p>Please tell me why this code fails. I am new and I don't understand why my formatting of my zip arguments is incorrect. Since I am unsure how to communicate best so I will show the code, the error message, and what I believe is happening.</p>
<pre><code>#!c:\python30
# Filename: backup_ver5.py
import os
import time
import zipfile
source = r'"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list"'
target_dir = r'C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir'
today = target_dir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')
comment = input('Enter a comment --> ')
if len(comment) == 0:
target = '"' + today + os.sep + now + '.zip' + '"'
else:
target = '"' + today + os.sep + now + '_' + \
comment.replace(' ', '_') + '.zip' + '"'
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
print(target)
print(source)
zip_command = zipfile.ZipFile(target, 'w').write(source)
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
enter code here
</code></pre>
<p>I recieve this error message:</p>
<pre><code>Enter a comment -->
"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_dir\20090
405\134614.zip"
"C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_list"
Traceback (most recent call last):
File "C:\Documents and Settings\Benjamin Serrato\My Documents\python\backup_ve
r5.py", line 32, in <module>
zip_command = zipfile.ZipFile(target, 'w').write(source)
File "c:\python30\lib\zipfile.py", line 683, in __init__
self.fp = io.open(file, modeDict[mode])
File "C:\Python30\lib\io.py", line 222, in open
closefd)
File "C:\Python30\lib\io.py", line 615, in __init__
_fileio._FileIO.__init__(self, name, mode, closefd)
IOError: [Errno 22] Invalid argument: '"C:\\Documents and Settings\\Benjamin Ser
rato\\My Documents\\python\\backup_dir\\20090405\\134614.zip"'
</code></pre>
<p>The two print tests before <code>zip_command</code> is assigned tell me that the two strings are being passed to <code>zipfile.ZipFile()</code> correctly. The traceback tells me I am not calling <code>zipfile.ZipFile()</code> correctly. The error in <code>__init__</code> makes me more sure of this. Last, the problem seems to be that I am causing my path string to have double backslashes. I can't follow why the IOError shows that.</p>
<p>I used <a href="http://docs.python.org/dev/3.0/library/zipfile.html" rel="nofollow">this site</a> to figure out how to use <code>zipfile</code>. <code>zipfile</code> is a class, I import it at the start of the program then I use it and its primary method. I pass the file I would like to write to <code>zipfile.ZipFile('file to write', 'mode')</code> and set the program to open an object set to be writable. Then the command writes the file to the destination folder with a sub-method like so, <code>"".zipfile('files to write')</code>.</p>
<p>Where am I going wrong?</p>
| 1
|
2009-04-05T19:16:12Z
| 719,521
|
<p>To answer your other question: the double backslashes are there because they are <a href="http://www.codecodex.com/wiki/index.php?title=Escape%5Fsequences#Python" rel="nofollow">escaped</a>.</p>
| 1
|
2009-04-05T19:24:31Z
|
[
"python",
"zip"
] |
What is the purpose of python's inner classes?
| 719,705
|
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
| 58
|
2009-04-05T21:13:28Z
| 719,718
|
<p>Quoted from <a href="http://www.geekinterview.com/question_details/64739">http://www.geekinterview.com/question_details/64739</a>:</p>
<blockquote>
<h3>Advantages of inner class:</h3>
<ul>
<li><strong>Logical grouping of classes</strong>: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.</li>
<li><strong>Increased encapsulation</strong>: Consider two top-level classes A and B where B needs access to members of A that would otherwise be declared private. By hiding class B within class A A's members can be declared private and B can access them. In addition B itself can be hidden from the outside world.</li>
<li><strong>More readable, maintainable code</strong>: Nesting small classes within top-level classes places the code closer to where it is used.</li>
</ul>
</blockquote>
<p>The main advantage is organization. Anything that can be accomplished with inner classes <strong>can</strong> be accomplished without them.</p>
| 56
|
2009-04-05T21:24:34Z
|
[
"python",
"class",
"oop",
"language-features"
] |
What is the purpose of python's inner classes?
| 719,705
|
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
| 58
|
2009-04-05T21:13:28Z
| 722,036
|
<p>Nesting classes within classes:</p>
<ul>
<li><p>Nested classes bloat the class definition making it harder to see whats going on.</p></li>
<li><p>Nested classes can create coupling that would make testing more difficult.</p></li>
<li><p>In Python you can put more than one class in a file/module, unlike Java, so the class still remains close to top level class and could even have the class name prefixed with an "_" to help signify that others shouldn't be using it.</p></li>
</ul>
<p>The place where nested classes can prove useful is within functions</p>
<pre><code>def some_func(a, b, c):
class SomeClass(a):
def some_method(self):
return b
SomeClass.__doc__ = c
return SomeClass
</code></pre>
<p>The class captures the values from the function allowing you to dynamically create a class like template metaprogramming in C++</p>
| 9
|
2009-04-06T15:43:54Z
|
[
"python",
"class",
"oop",
"language-features"
] |
What is the purpose of python's inner classes?
| 719,705
|
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
| 58
|
2009-04-05T21:13:28Z
| 722,175
|
<blockquote>
<p>Is there something that can't be accomplished without them?</p>
</blockquote>
<p>No. They are absolutely equivalent to defining the class normally at top level, and then copying a reference to it into the outer class.</p>
<p>I don't think there's any special reason nested classes are âallowedâ, other than it makes no particular sense to explicitly âdisallowâ them either.</p>
<p>If you're looking for a class that exists within the lifecycle of the outer/owner object, and always has a reference to an instance of the outer classâââinner classes as Java does itâââthen Python's nested classes are not that thing. But you can hack up something <em>like</em> that thing:</p>
<pre><code>import weakref, new
class innerclass(object):
"""Descriptor for making inner classes.
Adds a property 'owner' to the inner class, pointing to the outer
owner instance.
"""
# Use a weakref dict to memoise previous results so that
# instance.Inner() always returns the same inner classobj.
#
def __init__(self, inner):
self.inner= inner
self.instances= weakref.WeakKeyDictionary()
# Not thread-safe - consider adding a lock.
#
def __get__(self, instance, _):
if instance is None:
return self.inner
if instance not in self.instances:
self.instances[instance]= new.classobj(
self.inner.__name__, (self.inner,), {'owner': instance}
)
return self.instances[instance]
# Using an inner class
#
class Outer(object):
@innerclass
class Inner(object):
def __repr__(self):
return '<%s.%s inner object of %r>' % (
self.owner.__class__.__name__,
self.__class__.__name__,
self.owner
)
>>> o1= Outer()
>>> o2= Outer()
>>> i1= o1.Inner()
>>> i1
<Outer.Inner inner object of <__main__.Outer object at 0x7fb2cd62de90>>
>>> isinstance(i1, Outer.Inner)
True
>>> isinstance(i1, o1.Inner)
True
>>> isinstance(i1, o2.Inner)
False
</code></pre>
<p>(This uses class decorators, which are new in Python 2.6 and 3.0. Otherwise you'd have to say âInner= innerclass(Inner)â after the class definition.)</p>
| 40
|
2009-04-06T16:23:21Z
|
[
"python",
"class",
"oop",
"language-features"
] |
What is the purpose of python's inner classes?
| 719,705
|
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
| 58
|
2009-04-05T21:13:28Z
| 722,237
|
<p>There's something you need to wrap your head around to be able to understand this. In most languages, class definitions are directives to the compiler. That is, the class is created before the program is ever run. In python, all statements are executable. That means that this statement:</p>
<pre><code>class foo(object):
pass
</code></pre>
<p>is a statement that is executed at runtime just like this one:</p>
<pre><code>x = y + z
</code></pre>
<p>This means that not only can you create classes within other classes, you can create classes anywhere you want to. Consider this code:</p>
<pre><code>def foo():
class bar(object):
...
z = bar()
</code></pre>
<p>Thus, the idea of an "inner class" isn't really a language construct; it's a programmer construct. Guido has a very good summary of how this came about <a href="http://python-history.blogspot.com/2009/03/how-everything-became-executable.html">here</a>. But essentially, the basic idea is this simplifies the language's grammar.</p>
| 18
|
2009-04-06T16:38:01Z
|
[
"python",
"class",
"oop",
"language-features"
] |
What is the purpose of python's inner classes?
| 719,705
|
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
| 58
|
2009-04-05T21:13:28Z
| 10,376,716
|
<p>I understand the arguments against nested classes, but there is a case for using them in some occasions. Imagine I'm creating a doubly-linked list class, and I need to create a node class for maintaing the nodes. I have two choices, create Node class inside the DoublyLinkedList class, or create the Node class outside the DoublyLinkedList class. I prefer the first choice in this case, because the Node class is only meaningful inside the DoublyLinkedList class. While there's no hiding/encapsulation benefit, there is a grouping benefit of being able to say the Node class is part of the DoublyLinkedList class.</p>
| 4
|
2012-04-29T22:52:04Z
|
[
"python",
"class",
"oop",
"language-features"
] |
What is the purpose of python's inner classes?
| 719,705
|
<p>Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?</p>
| 58
|
2009-04-05T21:13:28Z
| 28,581,492
|
<p>I have used Python's inner classes to create deliberately buggy subclasses within unittest functions (i.e. inside <code>def test_something():</code>) in order to get closer to 100% test coverage (e.g. testing very rarely triggered logging statements by overriding some methods).</p>
<p>In retrospect it's similar to Ed's answer <a href="http://stackoverflow.com/a/722036/1101109">http://stackoverflow.com/a/722036/1101109</a></p>
<p>Such inner classes <em>should</em> go out of scope and be ready for garbage collection once all references to them have been removed. For instance, take the following <code>inner.py</code> file:</p>
<pre><code>class A(object):
pass
def scope():
class Buggy(A):
"""Do tests or something"""
assert isinstance(Buggy(), A)
</code></pre>
<p>I get the following curious results under OSX Python 2.7.6:</p>
<pre><code>>>> from inner import A, scope
>>> A.__subclasses__()
[]
>>> scope()
>>> A.__subclasses__()
[<class 'inner.Buggy'>]
>>> del A, scope
>>> from inner import A
>>> A.__subclasses__()
[<class 'inner.Buggy'>]
>>> del A
>>> import gc
>>> gc.collect()
0
>>> gc.collect() # Yes I needed to call the gc twice, seems reproducible
3
>>> from inner import A
>>> A.__subclasses__()
[]
</code></pre>
<p>Hint - Don't go on and try doing this with Django models, which seemed to keep other (cached?) references to my buggy classes.</p>
<p>So in general, I wouldn't recommend using inner classes for this kind of purpose unless you really do value that 100% test coverage and can't use other methods. Though I think it's nice to be aware that if you use the <code>__subclasses__()</code>, that it can <em>sometimes</em> get polluted by inner classes. Either way if you followed this far, I think we're pretty deep into Python at this point, private dunderscores and all.</p>
| 0
|
2015-02-18T10:37:54Z
|
[
"python",
"class",
"oop",
"language-features"
] |
How do I set Session name with Cherrypy?
| 719,710
|
<p>In PHP I would do it like this:</p>
<pre><code>session_name("special_session_name");
</code></pre>
<p>So how do I do it with Cherrypy?
Just need to find exact equivalent for it.
PHP manual page:
<a href="http://fi2.php.net/session_name" rel="nofollow">http://fi2.php.net/session_name</a></p>
| 0
|
2009-04-05T21:15:20Z
| 719,780
|
<p>Reading the docs and the source most probably you have to set "tools.sessions.name" in your config file:</p>
<pre><code>cherrypy.config.update({'tools.sessions.name': "special_session_name"})
</code></pre>
| 3
|
2009-04-05T22:00:49Z
|
[
"php",
"python",
"session",
"cherrypy"
] |
What is the best ordered dict implementation in python?
| 719,744
|
<p>I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard?</p>
<p>What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP.</p>
<p>odict from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a> seems like a strong candidate, but it's not totally clear that it is the winner.</p>
| 6
|
2009-04-05T21:40:44Z
| 719,772
|
<p>I haven't seen a standard; everyone seems to roll their own (see answers to <a href="http://stackoverflow.com/questions/60848/how-do-you-retrieve-items-from-a-dictionary-in-the-order-that-theyre-inserted">this question</a>). If you can use the <code>OrderedDict</code> <a href="http://bugs.python.org/issue5397">patch</a> from PEP 372, that's your best bet. Anything that's included in the stdlib has a very high chance of being what everyone uses a year or two from now.</p>
| 8
|
2009-04-05T21:56:17Z
|
[
"python",
"dictionary",
"ordereddictionary"
] |
What is the best ordered dict implementation in python?
| 719,744
|
<p>I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard?</p>
<p>What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP.</p>
<p>odict from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a> seems like a strong candidate, but it's not totally clear that it is the winner.</p>
| 6
|
2009-04-05T21:40:44Z
| 2,030,935
|
<p>This one by Raymond Hettinger is a drop-in substitute for the collections.OrderedDict that will appear in Python 2.7: <a href="http://pypi.python.org/pypi/ordereddict">http://pypi.python.org/pypi/ordereddict</a></p>
<p>The dev version of the collections docs say it's equivalent to what will be in Python 2.7, so it's probably pretty likely to be a smooth transition to the one that will come with Python. </p>
<p>I've put it in PyPI, so you can install it with <code>easy_install ordereddict</code>, and use it like so:</p>
<pre><code>from ordereddict import OrderedDict
d = OrderedDict([("one", 1), ("two", 2)])
</code></pre>
| 12
|
2010-01-08T21:37:05Z
|
[
"python",
"dictionary",
"ordereddictionary"
] |
What is the best ordered dict implementation in python?
| 719,744
|
<p>I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard?</p>
<p>What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP.</p>
<p>odict from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a> seems like a strong candidate, but it's not totally clear that it is the winner.</p>
| 6
|
2009-04-05T21:40:44Z
| 15,743,916
|
<p>Python 2.7 and later have OrderedDict in the <code>collections</code> module, so you should consider that as 'standard'. If its functionality is enough you should probably be using that.</p>
<p>However its implementation approach is minimalistic and if that is not enough you should look at <a href="http://www.voidspace.org.uk/python/odict.html" rel="nofollow">odict</a> by Foord/Larossa or <a href="http://anthon.home.xs4all.nl/Python/ordereddict/" rel="nofollow">ordereddict</a> (by me) as in that case those are a better fit. Both implementations are a superset of the functionality provided by <code>collections.OrderedDict</code>. The difference between the two being, that <code>odict</code> is pure python and <code>ordereddict</code> a much faster <code>C</code> extension module.</p>
<p>A minimalistic approach is not necessarily better even if it provides all the functionality you need: e.g. <code>collections.OrderedDict</code> did initially have a <a href="http://bugs.python.org/issue9826" rel="nofollow">bug</a> when returning the <code>repr()</code> of a <code>OrderedDict</code> nested in one of its own values. A bug that could have been found earlier, had the subset, the small subset OrderedDict can handle, of unittests of the older <code>ordereddict</code> been used.</p>
| 1
|
2013-04-01T12:56:31Z
|
[
"python",
"dictionary",
"ordereddictionary"
] |
What is the best ordered dict implementation in python?
| 719,744
|
<p>I've seen (and written) a number of implementations of this. Is there one that is considered the best or is emerging as a standard?</p>
<p>What I mean by ordered dict is that the object has some concept of the order of the keys in it, similar to an array in PHP.</p>
<p>odict from <a href="http://www.python.org/dev/peps/pep-0372/">PEP 372</a> seems like a strong candidate, but it's not totally clear that it is the winner.</p>
| 6
|
2009-04-05T21:40:44Z
| 27,007,361
|
<p><code>collections.OrderedDict</code> should now be widely available, but if performance is concern, you might consider using my package <a href="https://github.com/shoyer/cyordereddict" rel="nofollow">cyordereddict</a> as an alternative. It's a direct port of standard library's OrderedDict to Cython that is 2-6x faster.</p>
| 2
|
2014-11-19T01:26:23Z
|
[
"python",
"dictionary",
"ordereddictionary"
] |
How can domain aliases be set up using Django?
| 719,771
|
<p>I am working on creating a website in Django which consists of two parts: the website itself, and the forum. They will both be on separate domains, i.e. example.com and exampleforum.com. How can this be done in Django, when the forum and main site are part of the same instance?</p>
| 0
|
2009-04-05T21:55:34Z
| 719,821
|
<p>This is done at the web server level. Django doesn't care about the domain on the incoming request.</p>
<p>If you are using Apache just put multiple ServerAlias directives inside your virtual host like this:</p>
<pre><code><VirtualHost *:80>
ServerName www.mydomain.com
ServerAlias mydomain.com
ServerAlias forum.mydomain.com
... other directives as needed ...
</VirtualHost>
</code></pre>
<p>This tells Apache to direct requests for all of those domains into the same instance.</p>
<p>For nginx your config file would look something like:</p>
<pre><code>server {
listen 80;
server_name www.mydomain.com mydomain.com forum.mydomain.com;
... other directives as needed ...
}
</code></pre>
| 4
|
2009-04-05T22:35:38Z
|
[
"python",
"django",
"dns",
"cross-domain"
] |
Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL
| 719,886
|
<p>I am trying to do the schedule for the upcoming season for my simulation baseball team. I have an existing Postgresql database that contains the old schedule.</p>
<p>There are 648 rows in the database: 27 weeks of series for 24 teams. The problem is that the schedule has gotten predictable and allows teams to know in advance about weak parts of their schedule. What I want to do is take the existing schedule and randomize it. That way teams are still playing each other the proper number of times but not in the same order as before.</p>
<p>There is one rule that has been tripping me up: each team can only play one home and one road series PER week. I had been fooling around with SELECT statements based on ORDER BY RANDOM() but I haven't figured out how to make sure a team only has one home and one road series per week.</p>
<p>Now, I <em>could</em> do this in PHP (which is the language I am most comfortable with) but I am trying to make the shift to Python so I'm not sure how to get this done in Python. I know that Python doesn't seem to handle two dimensional arrays very well.</p>
<p>Any help would be greatly appreciated.</p>
| 0
|
2009-04-05T23:34:32Z
| 719,909
|
<p>I'm not sure I fully understand the problem, but here is how I would do it:
1. create a complete list of matches that need to happen
2. iterate over the weeks, selecting which match needs to happen in this week.</p>
<p>You can use Python lists to represent the matches that still need to happen, and, for each week, the matches that are happening in this week.</p>
<p>In step 2, selecting a match to happen would work this way:
a. use random.choice to select a random match to happen.
b. determine which team has a home round for this match, using random.choice([1,2]) (if it could have been a home round for either team)
c. temporarily remove all matches that get blocked by this selection. a match is blocked if one of its teams has already two matches in the week, or if both teams already have a home match in this week, or if both teams already have a road match in this week.
d. when there are no available matches anymore for a week, proceed to the next week, readding all the matches that got blocked for the previous week.</p>
| 1
|
2009-04-05T23:57:31Z
|
[
"python",
"postgresql"
] |
Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL
| 719,886
|
<p>I am trying to do the schedule for the upcoming season for my simulation baseball team. I have an existing Postgresql database that contains the old schedule.</p>
<p>There are 648 rows in the database: 27 weeks of series for 24 teams. The problem is that the schedule has gotten predictable and allows teams to know in advance about weak parts of their schedule. What I want to do is take the existing schedule and randomize it. That way teams are still playing each other the proper number of times but not in the same order as before.</p>
<p>There is one rule that has been tripping me up: each team can only play one home and one road series PER week. I had been fooling around with SELECT statements based on ORDER BY RANDOM() but I haven't figured out how to make sure a team only has one home and one road series per week.</p>
<p>Now, I <em>could</em> do this in PHP (which is the language I am most comfortable with) but I am trying to make the shift to Python so I'm not sure how to get this done in Python. I know that Python doesn't seem to handle two dimensional arrays very well.</p>
<p>Any help would be greatly appreciated.</p>
| 0
|
2009-04-05T23:34:32Z
| 719,913
|
<p>Have you considered keeping your same "schedule", and just shuffling the teams? Generating a schedule where everyone plays each other the proper number of times is possible, but if you already have such a schedule then it's much easier to just shuffle the teams.</p>
<p>You could keep your current table, but replace each team in it with an id (0-23, or A-X, or whatever), then randomly generate into another table where you assign each team to each id (0 = TeamJoe, 1 = TeamBob, etc). Then when it's time to shuffle again next year, just regenerate that mapping table.</p>
<p>Not sure if this answers the question the way you want, but is probably what I would go with (and is actually how I do it on my fantasy football website).</p>
| 2
|
2009-04-05T23:59:14Z
|
[
"python",
"postgresql"
] |
Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL
| 719,886
|
<p>I am trying to do the schedule for the upcoming season for my simulation baseball team. I have an existing Postgresql database that contains the old schedule.</p>
<p>There are 648 rows in the database: 27 weeks of series for 24 teams. The problem is that the schedule has gotten predictable and allows teams to know in advance about weak parts of their schedule. What I want to do is take the existing schedule and randomize it. That way teams are still playing each other the proper number of times but not in the same order as before.</p>
<p>There is one rule that has been tripping me up: each team can only play one home and one road series PER week. I had been fooling around with SELECT statements based on ORDER BY RANDOM() but I haven't figured out how to make sure a team only has one home and one road series per week.</p>
<p>Now, I <em>could</em> do this in PHP (which is the language I am most comfortable with) but I am trying to make the shift to Python so I'm not sure how to get this done in Python. I know that Python doesn't seem to handle two dimensional arrays very well.</p>
<p>Any help would be greatly appreciated.</p>
| 0
|
2009-04-05T23:34:32Z
| 719,966
|
<p>I think I've understood your question correctly, but anyhow, you can make use of Python's set datatype and generator functionality:</p>
<pre><code>import random
def scheduler(teams):
""" schedule generator: only accepts an even number of teams! """
if 0 != len(teams) % 2:
return
while teams:
home_team = random.choice(list(teams))
teams.remove(home_team)
away_team = random.choice(list(teams))
teams.remove(away_team)
yield(home_team, away_team)
# team list from sql select statement
teams = set(["TEAM A", "TEAM B", "TEAM C", "TEAM D"])
for team in scheduler(teams):
print(team)
</code></pre>
<p>This keeps SQL processing to a minimum and should be very easy to add to new rules, like the ones I didn't understand ;) Good luck</p>
<p><strong>EDIT:</strong></p>
<p>Ah, makes more sense now, should have had one less beer! In which case, I'd definitely recommend <a href="http://numpy.scipy.org//" rel="nofollow">NumPy</a>. Take a look through the <a href="http://www.scipy.org/Tentative%5FNumPy%5FTutorial" rel="nofollow">tutorial</a> and look at consuming the 2-dimensional home-away teams array as you are grabbing random fixtures. It would probably be best to feed the home and away teams from the home day into the away day, so you can ensure there that each team plays home and away each week.</p>
| 1
|
2009-04-06T00:45:28Z
|
[
"python",
"postgresql"
] |
How do I apply Django model Meta options to models that I did not write?
| 720,083
|
<p>I want to apply the <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering">"ordering"</a> Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to modify the User model?</p>
| 5
|
2009-04-06T02:21:26Z
| 720,090
|
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/models/#specifying-the-parent-link-field" rel="nofollow">This is how the Django manual recommends you do it</a>:</p>
<blockquote>
<p>You could also use a proxy model to define a different default ordering on a model. The standard User model has no ordering defined on it (intentionally; sorting is expensive and we don't want to do it all the time when we fetch users). You might want to regularly order by the username attribute when you use the proxy. This is easy:</p>
</blockquote>
<pre><code>class OrderedUser(User):
class Meta:
ordering = ["username"]
proxy = True
</code></pre>
<blockquote>
<p>Now normal User queries will be unorderd and OrderedUser queries will be ordered by username.</p>
</blockquote>
<p><b>Note that for this to work you will need to have a trunk checkout of Django as it is fairly new.</b></p>
<p>If you don't have access to it, you will need to get rid of the proxy part and implement it that way, which can get cumbersome. <a href="http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/" rel="nofollow">Check out this article on how to accomplish this.</a></p>
| 9
|
2009-04-06T02:26:08Z
|
[
"python",
"django"
] |
How do I apply Django model Meta options to models that I did not write?
| 720,083
|
<p>I want to apply the <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering">"ordering"</a> Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to modify the User model?</p>
| 5
|
2009-04-06T02:21:26Z
| 720,093
|
<p>You can either subclass User:</p>
<pre><code>class OrderedUser(User):
class Meta:
ordering = ['-id', 'username']
</code></pre>
<p>Or you could use the ordering in ModelAdmin:</p>
<pre><code>class UserAdmin(admin.ModelAdmin):
ordering = ['-id', 'username']
# unregister user since its already been registered by auth
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
</code></pre>
<p>Note: the ModelAdmin method will only change the ordering in the admin, it won't change the ordering of queries.</p>
| 3
|
2009-04-06T02:27:28Z
|
[
"python",
"django"
] |
How do I apply Django model Meta options to models that I did not write?
| 720,083
|
<p>I want to apply the <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering">"ordering"</a> Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to modify the User model?</p>
| 5
|
2009-04-06T02:21:26Z
| 720,114
|
<p>Contact the author and ask them to make a change.</p>
| 0
|
2009-04-06T02:37:57Z
|
[
"python",
"django"
] |
How do I apply Django model Meta options to models that I did not write?
| 720,083
|
<p>I want to apply the <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#ordering">"ordering"</a> Meta option to the Django model User from django.contrib.auth.models. Normally I would just put the Meta class in the model's definition, but in this case I did not define the model. So where do I put the Meta class to modify the User model?</p>
| 5
|
2009-04-06T02:21:26Z
| 720,187
|
<p>Paolo's answer is great; I wasn't previously aware of the new proxy support. The only issue with it is that you need to target your code to the OrderedUser model - which is in a sense similar to simply doing a <code>User.objects.filter(....).order_by('username')</code>. In other words, it's less verbose but you need to explicitly write your code to target it. (Of course, as mentioned, you'd also have to be on trunk.)</p>
<p>My sense is that you want <i>all</i> <code>User</code> queries to be ordered, including in third party apps that you don't control. In such a circumstance, monkeypatching the base class is relatively easy and very unlikely to cause any problems. In a central location (such as your settings.py), you could do:</p>
<pre><code>from django.contrib.auth.models import User
User.Meta.ordering = ['username']
</code></pre>
<p>UPDATE: Django 1.5 now supports <a href="https://docs.djangoproject.com/en/dev/releases/1.5-alpha-1/#configurable-user-model" rel="nofollow">configurable User models</a>.</p>
| 6
|
2009-04-06T03:35:39Z
|
[
"python",
"django"
] |
Find Hyperlinks in Text using Python (twitter related)
| 720,113
|
<p>How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of <code><a href="http://test.com">test</a></code> but just <code>http://test.com</code></p>
<p>Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.</p>
<p>I found an example in this thread:</p>
<p><a href="http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string">Easiest way to convert a URL to a hyperlink in a C# string?</a></p>
<p>but was unable to reproduce it in python :(</p>
| 12
|
2009-04-06T02:37:48Z
| 720,137
|
<p>Here's a Python port of <a href="http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string/32648#32648">http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string/32648#32648</a>:</p>
<pre><code>import re
myString = "This is my tweet check it out http://tinyurl.com/blah"
r = re.compile(r"(http://[^ ]+)")
print r.sub(r'<a href="\1">\1</a>', myString)
</code></pre>
<p>Output:</p>
<pre><code>This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/blah</a>
</code></pre>
| 20
|
2009-04-06T02:53:17Z
|
[
"python",
"regex"
] |
Find Hyperlinks in Text using Python (twitter related)
| 720,113
|
<p>How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of <code><a href="http://test.com">test</a></code> but just <code>http://test.com</code></p>
<p>Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.</p>
<p>I found an example in this thread:</p>
<p><a href="http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string">Easiest way to convert a URL to a hyperlink in a C# string?</a></p>
<p>but was unable to reproduce it in python :(</p>
| 12
|
2009-04-06T02:37:48Z
| 2,102,648
|
<p><a href="http://mail.python.org/pipermail/tutor/2002-September/017228.html">Here</a> is a much more sophisticated regexp from 2002.</p>
| 8
|
2010-01-20T15:45:58Z
|
[
"python",
"regex"
] |
Find Hyperlinks in Text using Python (twitter related)
| 720,113
|
<p>How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of <code><a href="http://test.com">test</a></code> but just <code>http://test.com</code></p>
<p>Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.</p>
<p>I found an example in this thread:</p>
<p><a href="http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string">Easiest way to convert a URL to a hyperlink in a C# string?</a></p>
<p>but was unable to reproduce it in python :(</p>
| 12
|
2009-04-06T02:37:48Z
| 8,982,755
|
<p>Django also has a solution that doesn't just use regex. It is <a href="https://github.com/django/django/blob/master/django/utils/html.py#L236" rel="nofollow">django.utils.html.urlize()</a>. I found this to be very helpful, especially if you happen to be using django.</p>
<p>You can also extract the <a href="https://github.com/django/django/blob/master/django/utils/html.py#L236" rel="nofollow">code</a> to use in your own project.</p>
| 5
|
2012-01-24T06:16:53Z
|
[
"python",
"regex"
] |
Find Hyperlinks in Text using Python (twitter related)
| 720,113
|
<p>How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of <code><a href="http://test.com">test</a></code> but just <code>http://test.com</code></p>
<p>Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.</p>
<p>I found an example in this thread:</p>
<p><a href="http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string">Easiest way to convert a URL to a hyperlink in a C# string?</a></p>
<p>but was unable to reproduce it in python :(</p>
| 12
|
2009-04-06T02:37:48Z
| 13,078,582
|
<p>Jinja2 (Flask uses this) has a filter <code>urlize</code> which does the same.</p>
<p><a href="http://jinja.pocoo.org/docs/templates/#urlize" rel="nofollow">Docs</a></p>
| 1
|
2012-10-25T22:57:03Z
|
[
"python",
"regex"
] |
How do i use Django session to read/set cookies?
| 720,329
|
<p>I am trying to use the Django sessions to read and set my cookies, but when i do the following the program just does not respond!</p>
<p><strong>sessionID = request.session["userid"]</strong></p>
<p>The program does not pass this point!</p>
<p>Any ideas?</p>
| 1
|
2009-04-06T05:16:05Z
| 720,394
|
<p>First, Django already creates a user object for you so you don't need to store it in the session. Just access it as:</p>
<pre><code>request.user
</code></pre>
<p>For example, to get the username you would use:</p>
<pre><code>request.user.username
</code></pre>
<p>Next, if you want to store information in the session you don't need to worry about it at the cookie level. Simply write key / value pairs to the <code>request.session</code> dictionary.</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#examples" rel="nofollow">Here are some examples</a> from the Django documentation.</p>
<p><strong>Edit</strong>: The reason your program isn't responding is because a KeyError exception is being raised. 'userid' doesn't exist as a key in the session dictionary (unless you have added it yourself).</p>
<p>This is why it is better to program dictionary reads like this:</p>
<pre><code>id = request.session.get('somekey', False)
</code></pre>
<p>Which will return False if 'somekey' doesn't exist in the dictionary.</p>
| 4
|
2009-04-06T06:43:15Z
|
[
"python",
"django"
] |
Function definition in Python
| 720,621
|
<p>I am new to Python. I was trying to define and run a simple function in a class.</p>
<p>Can anybody please tell me what's wrong in my code:</p>
<pre><code>class A :
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
>>> a = A()
>>> a.m1('X',12,'XXXX')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.m1('X',12,'XXXX')
</code></pre>
<p>I am getting below error <br>
<strong>TypeError: m1() takes exactly 3 positional arguments (4 given)</strong></p>
| 2
|
2009-04-06T08:36:23Z
| 720,631
|
<p>By convention, methods in a class instance receive an object reference as the 1st argument, named <code>self</code>.</p>
<pre><code>>>> class A:
... def m1(self,name,age,address):
... print('Name -->',name)
... print('Age -->',age)
... print('Address -->',address)
...
>>> a=A()
>>> a.m1('X',12,'XXXX')
('Name -->', 'X')
('Age -->', 12)
('Address -->', 'XXXX')
>>>
</code></pre>
| 4
|
2009-04-06T08:40:32Z
|
[
"python"
] |
Function definition in Python
| 720,621
|
<p>I am new to Python. I was trying to define and run a simple function in a class.</p>
<p>Can anybody please tell me what's wrong in my code:</p>
<pre><code>class A :
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
>>> a = A()
>>> a.m1('X',12,'XXXX')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.m1('X',12,'XXXX')
</code></pre>
<p>I am getting below error <br>
<strong>TypeError: m1() takes exactly 3 positional arguments (4 given)</strong></p>
| 2
|
2009-04-06T08:36:23Z
| 720,632
|
<p>Instance methods take instance as first argument:</p>
<pre><code>class A :
def m1(self, name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
</code></pre>
<p>You can also use <a href="http://docs.python.org/library/functions.html#staticmethod" rel="nofollow">@staticmethod decorator</a> to create static function:</p>
<pre><code>class A :
@staticmethod
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
</code></pre>
| 19
|
2009-04-06T08:40:47Z
|
[
"python"
] |
Function definition in Python
| 720,621
|
<p>I am new to Python. I was trying to define and run a simple function in a class.</p>
<p>Can anybody please tell me what's wrong in my code:</p>
<pre><code>class A :
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
>>> a = A()
>>> a.m1('X',12,'XXXX')
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a.m1('X',12,'XXXX')
</code></pre>
<p>I am getting below error <br>
<strong>TypeError: m1() takes exactly 3 positional arguments (4 given)</strong></p>
| 2
|
2009-04-06T08:36:23Z
| 720,633
|
<p>The first parameter is always the object itself.</p>
<pre><code>class A :
def m1(self, name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
</code></pre>
| 4
|
2009-04-06T08:41:13Z
|
[
"python"
] |
Removing specific items from Django's cache?
| 720,800
|
<p>I'm using site wide caching with <a href="http://en.wikipedia.org/wiki/Memcached">memcached</a> as the backend. I would like to invalidate pages in the cache when the underlying database object changes. </p>
<p>If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs.</p>
<p>If just the page content changes then I'd like to invalidate the cache of just that page.</p>
<p>Is there an easy way to do this? </p>
| 8
|
2009-04-06T09:36:35Z
| 721,749
|
<p>I haven't done a lot of caching with Django, but I think what you want here are <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="nofollow"><code>signals</code></a>.</p>
<p>You can set up a <code>post_save</code> signal on the underlying object, and have the callback function invalidate that page in the cache.</p>
<pre><code>from django.core.signals import post_save
from django.core.cache import cache
def invalidate_cache(sender, **kwargs):
# invalidate cache
cache.delete(sender.get_absolute_url()) # or any other pertinent keys
post_save.connect(invalidate_cache, sender=UnderlyingModel)
</code></pre>
<p>This should properly remove the item from the cache when it is updated.</p>
| 4
|
2009-04-06T14:36:44Z
|
[
"python",
"django",
"caching",
"memcached"
] |
Removing specific items from Django's cache?
| 720,800
|
<p>I'm using site wide caching with <a href="http://en.wikipedia.org/wiki/Memcached">memcached</a> as the backend. I would like to invalidate pages in the cache when the underlying database object changes. </p>
<p>If the page name changes then I would invalidate the whole cache (as it affects navigation on every page. Clumsy but sufficient for my needs.</p>
<p>If just the page content changes then I'd like to invalidate the cache of just that page.</p>
<p>Is there an easy way to do this? </p>
| 8
|
2009-04-06T09:36:35Z
| 1,995,155
|
<p>tghw's solution does not actually work, because the cache key is NOT the absolute path. The key is calculated from the absolute path and the HTTP headers. See <a href="http://stackoverflow.com/questions/1995126/invalidating-a-path-from-the-django-cache-recursively">this question</a> for an example.</p>
| 4
|
2010-01-03T14:39:44Z
|
[
"python",
"django",
"caching",
"memcached"
] |
HTTP Authentication in Python
| 720,867
|
<p>Whats is the python urllib equivallent of </p>
<pre><code>curl -u username:password status="abcd" http://example.com/update.json
</code></pre>
<p>I did this:</p>
<pre><code>handle = urllib2.Request(url)
authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password))
handle.add_header("Authorization", authheader)
</code></pre>
<p>Is there a better / simpler way?</p>
| 15
|
2009-04-06T10:03:12Z
| 720,880
|
<p>The trick is to create a password manager, and then tell urllib about it. Usually, you won't care about the realm of the authentication, just the host/url part. For example, the following:</p>
<pre><code>password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)
</code></pre>
<p>Will set the user name and password to every URL starting with <code>top_level_url</code>. Other options are to specify a host name or more complete URL here.</p>
<p>A good document describing this and more is at <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6">http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6</a>.</p>
| 20
|
2009-04-06T10:09:33Z
|
[
"authentication",
"curl",
"http-headers",
"python"
] |
HTTP Authentication in Python
| 720,867
|
<p>Whats is the python urllib equivallent of </p>
<pre><code>curl -u username:password status="abcd" http://example.com/update.json
</code></pre>
<p>I did this:</p>
<pre><code>handle = urllib2.Request(url)
authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password))
handle.add_header("Authorization", authheader)
</code></pre>
<p>Is there a better / simpler way?</p>
| 15
|
2009-04-06T10:03:12Z
| 720,881
|
<p>Yes, have a look at the <a href="http://docs.python.org/library/urllib2.html#httpbasicauthhandler-objects">urllib2.HTTP*AuthHandlers</a>.</p>
<p>Example from the documentation:</p>
<pre><code>import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://mahler:8092/site-updates.py',
user='klem',
passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')
</code></pre>
| 6
|
2009-04-06T10:11:21Z
|
[
"authentication",
"curl",
"http-headers",
"python"
] |
String inside a string
| 720,927
|
<pre><code>BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
</code></pre>
<p>I get this <code>'<a href="http://foobar.com?foo=bar" rel="nofollow">http://foobar.com?foo=bar</a>'</code> # It ignores the inside string.</p>
<p>But i wanted something like this <code>'<a href="http://foobar.com?foo=" rel="nofollow">http://foobar.com?foo=</a>'bar''</code></p>
<p>Thanks for the answer.</p>
<p>Can you help me out with almost the same problem:</p>
<pre><code>lst = ['foo', 'bar', 'foo bar']
[str(l) for l in lst if ' ' in l]
</code></pre>
<p>I get <code>['foo bar']</code> but i wanted it like <code>[''foo bar'']</code></p>
<p>Thanks in advance.</p>
| 1
|
2009-04-06T10:43:45Z
| 720,929
|
<p>Change your <code>BASE_URL</code> to either</p>
<pre><code>BASE_URL = "http://foobar.com?foo='%s'"
</code></pre>
<p>or</p>
<pre><code>BASE_URL = 'http://foobar.com?foo=\'%s\''
</code></pre>
| 7
|
2009-04-06T10:45:41Z
|
[
"python",
"string"
] |
String inside a string
| 720,927
|
<pre><code>BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
</code></pre>
<p>I get this <code>'<a href="http://foobar.com?foo=bar" rel="nofollow">http://foobar.com?foo=bar</a>'</code> # It ignores the inside string.</p>
<p>But i wanted something like this <code>'<a href="http://foobar.com?foo=" rel="nofollow">http://foobar.com?foo=</a>'bar''</code></p>
<p>Thanks for the answer.</p>
<p>Can you help me out with almost the same problem:</p>
<pre><code>lst = ['foo', 'bar', 'foo bar']
[str(l) for l in lst if ' ' in l]
</code></pre>
<p>I get <code>['foo bar']</code> but i wanted it like <code>[''foo bar'']</code></p>
<p>Thanks in advance.</p>
| 1
|
2009-04-06T10:43:45Z
| 720,942
|
<p>If you're working with URL parameters, it's probably safer to use urllib.urlencode:</p>
<pre><code>import urllib
BASE_URL = 'http://foobar.com/?%s'
print BASE_URL % urllib.urlencode({
'foo': 'bar',
})
</code></pre>
<p>Regarding the quotes: Why do you explicitly want them? Normally your HTTP-wrapper would handle all that for you.</p>
<p>Regarding your 2nd question: If you absolutely also want to have the quotes in there, you still have to either escape them when appending the contained string, or (probably the safer way of doing it) would be using repr(...)</p>
<pre><code>lst = ['foo', 'bar', 'foo bar']
lst2 = []
for l in lst:
if ' ' in l:
lst2.append(repr(l))
</code></pre>
| 6
|
2009-04-06T10:50:45Z
|
[
"python",
"string"
] |
String inside a string
| 720,927
|
<pre><code>BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
</code></pre>
<p>I get this <code>'<a href="http://foobar.com?foo=bar" rel="nofollow">http://foobar.com?foo=bar</a>'</code> # It ignores the inside string.</p>
<p>But i wanted something like this <code>'<a href="http://foobar.com?foo=" rel="nofollow">http://foobar.com?foo=</a>'bar''</code></p>
<p>Thanks for the answer.</p>
<p>Can you help me out with almost the same problem:</p>
<pre><code>lst = ['foo', 'bar', 'foo bar']
[str(l) for l in lst if ' ' in l]
</code></pre>
<p>I get <code>['foo bar']</code> but i wanted it like <code>[''foo bar'']</code></p>
<p>Thanks in advance.</p>
| 1
|
2009-04-06T10:43:45Z
| 721,054
|
<p>It seems, you are a bit confused about how <em>string literals</em> work.</p>
<p>When you say <code>s = 'this is a string'</code>, you are assigning a string to a variable. What string? Well, a string literal that you hardcoded in your program.</p>
<p>Python uses the apostrophes to indicate start and end of a string literal - with anything <em>inside</em> being the contents of the string.</p>
<p>This is probably one of the first hard problems for beginners in programming: There is a difference between what you write in your programs source code and what actually happens at runtime. You might want to work through a couple of tutorials (I hear "Dive into Python" is pretty good).</p>
| 3
|
2009-04-06T11:27:47Z
|
[
"python",
"string"
] |
String inside a string
| 720,927
|
<pre><code>BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
</code></pre>
<p>I get this <code>'<a href="http://foobar.com?foo=bar" rel="nofollow">http://foobar.com?foo=bar</a>'</code> # It ignores the inside string.</p>
<p>But i wanted something like this <code>'<a href="http://foobar.com?foo=" rel="nofollow">http://foobar.com?foo=</a>'bar''</code></p>
<p>Thanks for the answer.</p>
<p>Can you help me out with almost the same problem:</p>
<pre><code>lst = ['foo', 'bar', 'foo bar']
[str(l) for l in lst if ' ' in l]
</code></pre>
<p>I get <code>['foo bar']</code> but i wanted it like <code>[''foo bar'']</code></p>
<p>Thanks in advance.</p>
| 1
|
2009-04-06T10:43:45Z
| 724,698
|
<p>If you want single quotes to appear in URL you can use</p>
<pre><code>BASE_URL = 'http://foobar.com?foo=%s'
variable = "'bar'"
final_url = BASE_URL % (variable)
</code></pre>
<p>But this variant is quite insecure, if variable is coming from somewhere (like user input).</p>
| 1
|
2009-04-07T08:52:28Z
|
[
"python",
"string"
] |
Django templates stripping spaces?
| 721,035
|
<p>I'm having trouble with Django templates and CharField models.</p>
<p>So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug <em>Somename_Somesurname</em> and gets displayed as expected on the template. </p>
<p>However, if I create an object, <em>Somename Somesurname</em> (notice the second space), slug <em>Somename__Somesurname</em> is created, and although on the Django console I see this as <code><Object: Somename Somesurname></code>, on the template it is displayed as <em>Somename Somesurname</em>. </p>
<p>So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?</p>
| 13
|
2009-04-06T11:22:15Z
| 721,082
|
<p>Django sees the object internally as having two spaces (judging by the two underscores and two spaces in the <code>repr</code> output). The fact that it only shows up with one space in the template is just how HTML works. Notice how, in the question you just asked, most of the places where you entered two spaces, only one is showing up?</p>
<p>From the <a href="http://www.w3.org/TR/html401/struct/text.html">HTML4 Spec</a>:</p>
<blockquote>
<p>In particular, user agents should collapse input white space sequences when producing output inter-word space.</p>
</blockquote>
<p>As S.Lott suggested, you can verify that my guess is correct by adding debug logging, or using the Firebug plugin for Firefox or something similar, to see exactly what's getting sent to the browser. Then you'll know for sure on which end the problem lies.</p>
<p>If multiple spaces are really important to you, you'll need to use the <code>&nbsp;</code> entity, though I don't know offhand how you'd get Django to encode the output of that specific object using them.</p>
| 10
|
2009-04-06T11:45:05Z
|
[
"python",
"django",
"django-templates"
] |
Django templates stripping spaces?
| 721,035
|
<p>I'm having trouble with Django templates and CharField models.</p>
<p>So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug <em>Somename_Somesurname</em> and gets displayed as expected on the template. </p>
<p>However, if I create an object, <em>Somename Somesurname</em> (notice the second space), slug <em>Somename__Somesurname</em> is created, and although on the Django console I see this as <code><Object: Somename Somesurname></code>, on the template it is displayed as <em>Somename Somesurname</em>. </p>
<p>So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?</p>
| 13
|
2009-04-06T11:22:15Z
| 721,249
|
<p><a href="http://docs.djangobrasil.org/ref/templates/builtins.html#slugify" rel="nofollow">Slugify</a> removes all leading spaces, you'll need to rewrite this as a custom template tag to get the behaviour you're after.
The original filter code looks like this</p>
<pre><code>def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return mark_safe(re.sub('[-\s]+', '-', value))
</code></pre>
<p>which changes "some string" into "some-string" killing the extra whitespace.
You could change it like so:</p>
<pre><code>def new_slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens, does not remove leading whitespace.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return mark_safe(re.sub('[-\s]', '-', value))
</code></pre>
<p>Which will result in the following behaviour:
"Some String here" to "some--string-here"</p>
<p>You still might have problems as mentioned before with how html treats extra whitespace, you'd have to write another, deslugify filter.</p>
| 0
|
2009-04-06T12:41:11Z
|
[
"python",
"django",
"django-templates"
] |
Django templates stripping spaces?
| 721,035
|
<p>I'm having trouble with Django templates and CharField models.</p>
<p>So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug <em>Somename_Somesurname</em> and gets displayed as expected on the template. </p>
<p>However, if I create an object, <em>Somename Somesurname</em> (notice the second space), slug <em>Somename__Somesurname</em> is created, and although on the Django console I see this as <code><Object: Somename Somesurname></code>, on the template it is displayed as <em>Somename Somesurname</em>. </p>
<p>So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?</p>
| 13
|
2009-04-06T11:22:15Z
| 722,266
|
<p>Let me preface this by saying <a href="#721082">@DNS's answer</a> is correct as to why the spaces are not showing.</p>
<p>With that in mind, this template filter will replace any spaces in the string with <code>&nbsp;</code></p>
<p>Usage:</p>
<pre><code>{{ "hey there world"|spacify }}
</code></pre>
<p>Output would be <code>hey&nbsp;there&nbsp;&nbsp;world</code></p>
<p>Here is the code:</p>
<pre><code>from django.template import Library
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re
register = Library()
@stringfilter
def spacify(value, autoescape=None):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(re.sub('\s', '&'+'nbsp;', esc(value)))
spacify.needs_autoescape = True
register.filter(spacify)
</code></pre>
<p>For notes on how template filters work and how to install them, <a href="http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#code-layout">check out the docs</a>.</p>
| 29
|
2009-04-06T16:46:38Z
|
[
"python",
"django",
"django-templates"
] |
Django templates stripping spaces?
| 721,035
|
<p>I'm having trouble with Django templates and CharField models.</p>
<p>So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug <em>Somename_Somesurname</em> and gets displayed as expected on the template. </p>
<p>However, if I create an object, <em>Somename Somesurname</em> (notice the second space), slug <em>Somename__Somesurname</em> is created, and although on the Django console I see this as <code><Object: Somename Somesurname></code>, on the template it is displayed as <em>Somename Somesurname</em>. </p>
<p>So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?</p>
| 13
|
2009-04-06T11:22:15Z
| 10,258,813
|
<p>There is a built-in template tag <strong>spaceless</strong></p>
<pre><code>{% spaceless %}
<p>
<a href="foo/">Foo</a>
</p>
{% endspaceless %}
</code></pre>
<p>Which results:</p>
<pre><code><p><a href="foo/">Foo</a></p>
</code></pre>
<p>Read more in django <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#spaceless">documentation</a>.</p>
| 5
|
2012-04-21T12:16:28Z
|
[
"python",
"django",
"django-templates"
] |
Django templates stripping spaces?
| 721,035
|
<p>I'm having trouble with Django templates and CharField models.</p>
<p>So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug <em>Somename_Somesurname</em> and gets displayed as expected on the template. </p>
<p>However, if I create an object, <em>Somename Somesurname</em> (notice the second space), slug <em>Somename__Somesurname</em> is created, and although on the Django console I see this as <code><Object: Somename Somesurname></code>, on the template it is displayed as <em>Somename Somesurname</em>. </p>
<p>So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?</p>
| 13
|
2009-04-06T11:22:15Z
| 13,642,196
|
<p>This tag keeps spaces and newlines. I copied Django's own tag linebreaksbr and then added a line to replace the spaces with nbsp. It does not replace single spaces so text source is still readable. I wrote this because I couldn't get the spacify tag (other answer) to work with linebreaksbr. </p>
<pre><code>from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe, SafeData
from django.utils.text import normalize_newlines
from django.utils.html import escape
@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def keep_spacing(value, autoescape=None):
autoescape = autoescape and not isinstance(value, SafeData)
value = normalize_newlines(value)
if autoescape:
value = escape(value)
value = mark_safe(value.replace(' ', ' &nbsp;'))
return mark_safe(value.replace('\n', '<br />'))
</code></pre>
| 0
|
2012-11-30T09:21:57Z
|
[
"python",
"django",
"django-templates"
] |
Django templates stripping spaces?
| 721,035
|
<p>I'm having trouble with Django templates and CharField models.</p>
<p>So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug <em>Somename_Somesurname</em> and gets displayed as expected on the template. </p>
<p>However, if I create an object, <em>Somename Somesurname</em> (notice the second space), slug <em>Somename__Somesurname</em> is created, and although on the Django console I see this as <code><Object: Somename Somesurname></code>, on the template it is displayed as <em>Somename Somesurname</em>. </p>
<p>So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?</p>
| 13
|
2009-04-06T11:22:15Z
| 18,688,638
|
<p><code>'\s'</code> might be ok in the use case described above, but be careful, this replaces other whitespaces like <code>'\t'</code> or <code>'\n'</code> as well! If this is not what you want, just use <code>" "</code> instead.</p>
| 0
|
2013-09-08T21:04:24Z
|
[
"python",
"django",
"django-templates"
] |
What's a good two-way encryption library implemented in Python?
| 721,436
|
<p>The authentication system for an application we're using right now uses a two-way hash that's basically little more than a glorified caesar cypher. Without going into too much detail about what's going on with it, I'd like to replace it with a more secure encryption algorithm (and it needs to be done server-side). Unfortunately, it needs to be two-way and the algorithms in hashlib are all one-way.</p>
<p>What are some good encryption libraries that will include algorithms for this kind of thing?</p>
| 4
|
2009-04-06T13:27:18Z
| 721,444
|
<p>If it's two-way, it's not really a "hash". It's encryption (and from the sounds of things this is really more of a 'salt' or 'cypher', <em>not</em> real encryption.) A hash is one-way <em>by definition</em>. So rather than something like MD5 or SHA1 you need to look for something more like PGP.</p>
<p>Secondly, can you explain the reasoning behind the 2-way requirement? That's not generally considered good practice for authentication systems any more.</p>
| 7
|
2009-04-06T13:30:05Z
|
[
"python",
"encryption"
] |
What's a good two-way encryption library implemented in Python?
| 721,436
|
<p>The authentication system for an application we're using right now uses a two-way hash that's basically little more than a glorified caesar cypher. Without going into too much detail about what's going on with it, I'd like to replace it with a more secure encryption algorithm (and it needs to be done server-side). Unfortunately, it needs to be two-way and the algorithms in hashlib are all one-way.</p>
<p>What are some good encryption libraries that will include algorithms for this kind of thing?</p>
| 4
|
2009-04-06T13:27:18Z
| 721,457
|
<p>I assume you want an encryption algorithm, not a hash. The <a href="https://pypi.python.org/pypi/pycrypto" rel="nofollow">PyCrypto</a> library offers a pretty wide range of options. It's in the middle of moving over to a <a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">new maintainer</a>, so the docs are a little disorganized, but <a href="http://www.dlitz.net/software/pycrypto/doc/#crypto-cipher-encryption-algorithms" rel="nofollow">this</a> is roughly where you want to start looking. I usually use AES for stuff like this.</p>
| 19
|
2009-04-06T13:32:06Z
|
[
"python",
"encryption"
] |
What's a good two-way encryption library implemented in Python?
| 721,436
|
<p>The authentication system for an application we're using right now uses a two-way hash that's basically little more than a glorified caesar cypher. Without going into too much detail about what's going on with it, I'd like to replace it with a more secure encryption algorithm (and it needs to be done server-side). Unfortunately, it needs to be two-way and the algorithms in hashlib are all one-way.</p>
<p>What are some good encryption libraries that will include algorithms for this kind of thing?</p>
| 4
|
2009-04-06T13:27:18Z
| 721,458
|
<p><a href="http://www.dlitz.net/software/pycrypto/" rel="nofollow">PyCrypto</a> supports AES, DES, IDEA, RSA, ElGamal, etc.</p>
<p>I've found the documentation <a href="http://www.dlitz.net/software/pycrypto/doc/" rel="nofollow">here</a>.</p>
| 4
|
2009-04-06T13:32:16Z
|
[
"python",
"encryption"
] |
Monitoring internet activity
| 722,046
|
<p>I'm looking into writing a small app (in Python) that monitors internet activity. The same idea as <a href="http://www.metal-machine.de/readerror/index.php?page=10" rel="nofollow">NetMeter</a> except with a little more customisation (I need to be able to set off-peak time ranges).</p>
<p>Anyway, I've been having a little trouble researching these questions:</p>
<ul>
<li>Does Python have an API to monitor this?</li>
<li>As far as data collecting goes I'll probably be recording values in bytes/min with the timestamp - is there something more sensible I'm missing here?</li>
</ul>
| 2
|
2009-04-06T15:45:44Z
| 722,072
|
<p>The <a href="http://sourceforge.net/projects/pylibpcap/" rel="nofollow">pylibpcap</a> project may actually give you what you want out of the box, or at least a leg up on implementing one yourself. It's a set of python bindings, as the name suggests, to the libpcap packet capture library.</p>
| 4
|
2009-04-06T15:52:28Z
|
[
"python",
"monitoring",
"bandwidth"
] |
How can I get the width of a wx.ListCtrl and its column name?
| 722,298
|
<p>I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it myself (Please correct me if there's a built in way of doing this!!!)</p>
<p>How can I find out how wide the titles and elements of my list will be rendered?</p>
| 1
|
2009-04-06T16:54:59Z
| 722,878
|
<p>Yes, you would have to make this yourself for wx.ListCtrl and I'm not sure it would be easy (or elegant) to do right.</p>
<p>Consider using a wx.Grid, here is a small example to get you going:</p>
<pre><code>import wx, wx.grid
class GridData(wx.grid.PyGridTableBase):
_cols = "This is a long column name,b,c".split(",")
_data = [
"1 2 3".split(),
"4,5,And here is a long cell value".split(","),
"7 8 9".split()
]
def GetColLabelValue(self, col):
return self._cols[col]
def GetNumberRows(self):
return len(self._data)
def GetNumberCols(self):
return len(self._cols)
def GetValue(self, row, col):
return self._data[row][col]
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
grid = wx.grid.Grid(self)
grid.SetTable(GridData())
grid.EnableEditing(False)
grid.SetSelectionMode(wx.grid.Grid.SelectRows)
grid.SetRowLabelSize(0)
grid.AutoSizeColumns()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
</code></pre>
| 1
|
2009-04-06T19:43:54Z
|
[
"python",
"wxpython",
"wxwidgets",
"width",
"listctrl"
] |
How can I get the width of a wx.ListCtrl and its column name?
| 722,298
|
<p>I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it myself (Please correct me if there's a built in way of doing this!!!)</p>
<p>How can I find out how wide the titles and elements of my list will be rendered?</p>
| 1
|
2009-04-06T16:54:59Z
| 723,585
|
<p>If you'd like to save yourself a lot of headache related to wx.ListCtrl you should switch over to using <a href="http://objectlistview.sourceforge.net/python/" rel="nofollow">ObjectListView</a> (has a nice cookbook and forum for code examples). It's very nice and I tend to use it for anything more than a very basic ListCtrl, because it is extremely powerful and flexible and easy to code up. Here's <a href="http://wiki.wxpython.org/ObjectListView" rel="nofollow">the wxPyWiki page</a> related to it (including example code). The developer is also on the wxPython mailing list so you can email with questions.</p>
| 3
|
2009-04-06T23:03:42Z
|
[
"python",
"wxpython",
"wxwidgets",
"width",
"listctrl"
] |
How can I get the width of a wx.ListCtrl and its column name?
| 722,298
|
<p>I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it myself (Please correct me if there's a built in way of doing this!!!)</p>
<p>How can I find out how wide the titles and elements of my list will be rendered?</p>
| 1
|
2009-04-06T16:54:59Z
| 4,856,472
|
<p>This works for me</p>
<pre><code>import wx
class Frame(wx.Frame):
def __init__(self, *args, **kw):
wx.Frame.__init__(self, *args, **kw)
self.list = wx.ListCtrl(self, style=wx.LC_REPORT)
items = ['A', 'b', 'something really REALLY long']
self.list.InsertColumn(0, "AA")
for item in items:
self.list.InsertStringItem(0, item)
self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
app = wx.App(False)
frm = Frame(None, title="ListCtrl test")
frm.Show()
app.MainLoop()
</code></pre>
| 1
|
2011-01-31T21:43:01Z
|
[
"python",
"wxpython",
"wxwidgets",
"width",
"listctrl"
] |
How can I get the width of a wx.ListCtrl and its column name?
| 722,298
|
<p>I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it myself (Please correct me if there's a built in way of doing this!!!)</p>
<p>How can I find out how wide the titles and elements of my list will be rendered?</p>
| 1
|
2009-04-06T16:54:59Z
| 5,705,303
|
<p>In Addition to jakepars answer: this should check, whether the header is bigger, or the item which takes the most space in the column. Not to elegant but working...</p>
<pre><code>import wx
class Frame(wx.Frame):
def __init__(self, *args, **kw):
wx.Frame.__init__(self, *args, **kw)
self.list = wx.ListCtrl(self, style=wx.LC_REPORT)
items = ['A', 'b', 'something really REALLY long']
self.list.InsertColumn(0, "AAAAAAAAAAAAAAAAAAAAAAAA")
for item in items:
self.list.InsertStringItem(0, item)
self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
a = self.list.GetColumnWidth(0)
print "a " + str(a)
self.list.SetColumnWidth(0,wx.LIST_AUTOSIZE_USEHEADER)
b = self.list.GetColumnWidth(0)
print "b " + str(b)
if a>b:
print "a is bigger"
self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
app = wx.App(False)
frm = Frame(None, title="ListCtrl test")
frm.Show()
app.MainLoop()
</code></pre>
| 4
|
2011-04-18T15:34:10Z
|
[
"python",
"wxpython",
"wxwidgets",
"width",
"listctrl"
] |
Django GROUP BY strftime date format
| 722,325
|
<p>I would like to do a SUM on rows in a database and group by date.</p>
<p>I am trying to run this SQL query using Django aggregates and annotations:</p>
<pre><code>select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data)
from my_model
group by the_date;
</code></pre>
<p>I tried the following:</p>
<pre><code>data = My_Model.objects.values("strftime('%m/%d/%Y',
time_stamp)").annotate(Sum("numbers_data")).order_by()
</code></pre>
<p>but it seems like you can only use column names in the values() function; it doesn't like the use of strftime().</p>
<p>How should I go about this?</p>
| 14
|
2009-04-06T17:04:07Z
| 722,352
|
<p>Any reason not to just do this in the database, by running the following query against the database:</p>
<pre><code>select date, sum(numbers_data)
from my_model
group by date;
</code></pre>
<p>If your answer is, the date is a datetime with non-zero hours, minutes, seconds, or milliseconds, my answer is to use a date function to truncate the datetime, but I can't tell you exactly what that is without knowing what RBDMS you're using.</p>
| 1
|
2009-04-06T17:12:10Z
|
[
"python",
"django",
"orm",
"django-models",
"django-aggregation"
] |
Django GROUP BY strftime date format
| 722,325
|
<p>I would like to do a SUM on rows in a database and group by date.</p>
<p>I am trying to run this SQL query using Django aggregates and annotations:</p>
<pre><code>select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data)
from my_model
group by the_date;
</code></pre>
<p>I tried the following:</p>
<pre><code>data = My_Model.objects.values("strftime('%m/%d/%Y',
time_stamp)").annotate(Sum("numbers_data")).order_by()
</code></pre>
<p>but it seems like you can only use column names in the values() function; it doesn't like the use of strftime().</p>
<p>How should I go about this?</p>
| 14
|
2009-04-06T17:04:07Z
| 722,880
|
<p>This works for me:</p>
<pre><code>select_data = {"d": """strftime('%%m/%%d/%%Y', time_stamp)"""}
data = My_Model.objects.extra(select=select_data).values('d').annotate(Sum("numbers_data")).order_by()
</code></pre>
<p>Took a bit to figure out I had to escape the % signs.</p>
| 14
|
2009-04-06T19:45:11Z
|
[
"python",
"django",
"orm",
"django-models",
"django-aggregation"
] |
Django GROUP BY strftime date format
| 722,325
|
<p>I would like to do a SUM on rows in a database and group by date.</p>
<p>I am trying to run this SQL query using Django aggregates and annotations:</p>
<pre><code>select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data)
from my_model
group by the_date;
</code></pre>
<p>I tried the following:</p>
<pre><code>data = My_Model.objects.values("strftime('%m/%d/%Y',
time_stamp)").annotate(Sum("numbers_data")).order_by()
</code></pre>
<p>but it seems like you can only use column names in the values() function; it doesn't like the use of strftime().</p>
<p>How should I go about this?</p>
| 14
|
2009-04-06T17:04:07Z
| 36,063,115
|
<p>I'm not sure about strftime, my solution below is using sql postgres trunc...</p>
<pre><code>select_data = {"date": "date_trunc('day', creationtime)"}
ttl = ReportWebclick.objects.using('cms')\
.extra(select=select_data)\
.filter(**filters)\
.values('date', 'tone_name', 'singer', 'parthner', 'price', 'period')\
.annotate(loadcount=Sum('loadcount'), buycount=Sum('buycount'), cancelcount=Sum('cancelcount'))\
.order_by('date', 'parthner')
</code></pre>
<p>-- equal to sql query execution:</p>
<pre>
select date_trunc('month', creationtime) as date, tone_name, sum(loadcount), sum(buycount), sum(cancelcount)
from webclickstat
group by tone_name, date;
</pre>
| 1
|
2016-03-17T14:13:30Z
|
[
"python",
"django",
"orm",
"django-models",
"django-aggregation"
] |
Django GROUP BY strftime date format
| 722,325
|
<p>I would like to do a SUM on rows in a database and group by date.</p>
<p>I am trying to run this SQL query using Django aggregates and annotations:</p>
<pre><code>select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data)
from my_model
group by the_date;
</code></pre>
<p>I tried the following:</p>
<pre><code>data = My_Model.objects.values("strftime('%m/%d/%Y',
time_stamp)").annotate(Sum("numbers_data")).order_by()
</code></pre>
<p>but it seems like you can only use column names in the values() function; it doesn't like the use of strftime().</p>
<p>How should I go about this?</p>
| 14
|
2009-04-06T17:04:07Z
| 38,285,830
|
<p>As of v1.8, you can use <a href="https://docs.djangoproject.com/en/1.8/ref/models/expressions/#func-expressions" rel="nofollow">Func() expressions</a>.</p>
<p>For example, if you happen to be targeting AWS Redshift's date and time functions:</p>
<pre><code>from django.db.models import F, Func, Value
def TimezoneConvertedDateF(field_name, tz_name):
tz_fn = Func(Value(tz_name), F(field_name), function='CONVERT_TIMEZONE')
dt_fn = Func(tz_fn, function='TRUNC')
return dt_fn
</code></pre>
<p>Then you can use it like this:</p>
<pre><code>SomeDbModel.objects \
.annotate(the_date=TimezoneConvertedDateF('some_timestamp_col_name',
'America/New_York')) \
.filter(the_date=...)
</code></pre>
<p>or like this:</p>
<pre><code>SomeDbModel.objects \
.annotate(the_date=TimezoneConvertedDateF('some_timestamp_col_name',
'America/New_York')) \
.values('the_date') \
.annotate(...)
</code></pre>
| 1
|
2016-07-09T19:57:13Z
|
[
"python",
"django",
"orm",
"django-models",
"django-aggregation"
] |
Why doesn't the handle_read method get called with asyncore?
| 722,605
|
<p>I am trying to proto-type send/recv via a packet socket using the asyncore dispatcher (code below). Although my handle_write method gets called promptly, the handle_read method doesn't seem to get invoked. The loop() does call the readable method every so often, but I am not able to receive anything. I know there are packets received on eth0 because a simple tcpdump shows incoming packets. Am I missing something? </p>
<pre><code>
#!/usr/bin/python
import asyncore, socket, IN, struct
class packet_socket(asyncore.dispatcher):
def __init__(self):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_PACKET, socket.SOCK_RAW)
self.buffer = '0180C20034350012545900040060078910'
self.socket.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len("eth0")+1,), "eth0"))
def handle_close(self):
self.close()
def handle_connect(self):
pass
def handle_read(self):
print "handle_read() called"
data,addr=self.recvfrom(1024)
print data
print addr
def readable(self):
print "Checking read flag"
return True
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
print "Writing buffer data to the socket"
sent = self.sendto(self.buffer,("eth0",0xFFFF))
self.buffer = self.buffer[sent:]
c = packet_socket()
asyncore.loop()
</code></pre>
<p>Thanks in advance.</p>
| 1
|
2009-04-06T18:25:01Z
| 723,053
|
<p>I finally got this to work with some help from a co-worker. This has to do with passing the protocol argument to the <code>create_socket()</code> method. Unfortunately <code>create_socket()</code> of the dispatcher doesn't take a third argument - so I had to modify my <code>packet_socket()</code> constructor to take a pre-created socket with protocol as <code>ETH_P_ALL</code> (or whatever protocol type you desire to receive) as an argument. Edited code below:</p>
<pre><code>
#!/usr/bin/python
import asyncore, socket, IN, struct
proto=3
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
s.bind(("eth0",proto))
class packet_socket(asyncore.dispatcher):
def __init__(self,sock):
asyncore.dispatcher.__init__(self,sock)
#self.create_socket(socket.AF_PACKET, socket.SOCK_RAW,socket.htons(3))
self.buffer = '0180C20034350012545900040060078910'
self.socket.setsockopt(socket.SOL_SOCKET,IN.SO_BINDTODEVICE,struct.pack("%ds" % (len("eth0")+1,), "eth0"))
def handle_close(self):
self.close()
def handle_connect(self):
pass
def handle_read(self):
print "handle_read() called"
data,addr=self.recvfrom(1024)
print data
print addr
def readable(self):
print "Checking read flag"
return True
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
print "Writing buffer data to the socket"
sent = self.sendto(self.buffer,("eth0",0xFFFF))
self.buffer = self.buffer[sent:]
c = packet_socket(s)
asyncore.loop()
</code></pre>
<p>Thanks,</p>
| 1
|
2009-04-06T20:22:06Z
|
[
"python",
"sockets",
"packet"
] |
Python class inclusion wrong behaviour
| 722,640
|
<p>I have into my main.py</p>
<pre><code>from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
</code></pre>
<p>and the controllor.py is:</p>
<pre><code>class controller:
def div(self, x, y):
return x // y
</code></pre>
<p>when I run my main I got the error:</p>
<pre><code>Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'
</code></pre>
<p>WHat is wrong?</p>
| 0
|
2009-04-06T18:37:35Z
| 722,650
|
<p>You should create an instance of controller, like this:</p>
<pre><code>ctrl = controller()
</code></pre>
<p>Note the brackets after controller.</p>
| 2
|
2009-04-06T18:40:47Z
|
[
"python"
] |
Python class inclusion wrong behaviour
| 722,640
|
<p>I have into my main.py</p>
<pre><code>from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
</code></pre>
<p>and the controllor.py is:</p>
<pre><code>class controller:
def div(self, x, y):
return x // y
</code></pre>
<p>when I run my main I got the error:</p>
<pre><code>Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'
</code></pre>
<p>WHat is wrong?</p>
| 0
|
2009-04-06T18:37:35Z
| 722,653
|
<blockquote>
<p>ctrl = controller</p>
</blockquote>
<p>âcontrollerâ is a module, representing your whole âcontroller.pyâ file. In Python, unlike in Java, there can be any number of symbols defined inside a module, so there isn't a 1:1 relationship between the imported module and the class defined in it.</p>
<p>So the script complains because the âcontrollerâ module does not have a âdivâ function; âdivâ is defined as a method of the âcontrollerâ class <em>inside</em> the âcontrollerâ module. If you want an instance of the controller() class you need to say:</p>
<pre><code>ctrl= controller.controller()
</code></pre>
<p>(Note also the () to instantiate the object, or you'll be getting the class itself rather than an instance. If you do really want to define a static method in the class so you can call it without an instance, you can do this using the âstaticmethodâ decorator and omitting âselfâ.)</p>
<p>It's usually best to name your classes with an initial capital to avoid confusion:</p>
<pre><code>class Controller(object):
...
ctrl= controller.Controller()
</code></pre>
| 3
|
2009-04-06T18:41:45Z
|
[
"python"
] |
Python class inclusion wrong behaviour
| 722,640
|
<p>I have into my main.py</p>
<pre><code>from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
</code></pre>
<p>and the controllor.py is:</p>
<pre><code>class controller:
def div(self, x, y):
return x // y
</code></pre>
<p>when I run my main I got the error:</p>
<pre><code>Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'
</code></pre>
<p>WHat is wrong?</p>
| 0
|
2009-04-06T18:37:35Z
| 722,696
|
<p>This is very confusing as shown.</p>
<p>When you say</p>
<pre><code>from modules import controller
</code></pre>
<p>You're making the claim that you have a module with a filename of <code>modules.py</code>.</p>
<p>OR</p>
<p>You're making the claim that you have a package named <code>modules</code>. This directory has an <code>__init__.py</code> file and a module with a filename of <code>controller.py</code></p>
<p>You should clarify this to be precise. It looks like you have mis-named your files and modules in the the example code posted here.</p>
<p>When you say</p>
<pre><code>from modules import controller
</code></pre>
<p>That creates a <em>module</em> (not a class) named <code>controller</code>.</p>
<p>When you say</p>
<pre><code>ctrl = controller
</code></pre>
<p>That creates another name for the <code>controller</code> <em>module</em>, <code>ctrl</code>.</p>
<p>At no time to you reference the class (<code>controller.controller</code>). At no time did you create an instance of the class (<code>controller.controller()</code>).</p>
| 4
|
2009-04-06T18:55:02Z
|
[
"python"
] |
Python class inclusion wrong behaviour
| 722,640
|
<p>I have into my main.py</p>
<pre><code>from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
</code></pre>
<p>and the controllor.py is:</p>
<pre><code>class controller:
def div(self, x, y):
return x // y
</code></pre>
<p>when I run my main I got the error:</p>
<pre><code>Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.div(5,2))
AttributeError: 'module' object has no attribute 'div'
</code></pre>
<p>WHat is wrong?</p>
| 0
|
2009-04-06T18:37:35Z
| 724,665
|
<p>When you execute following code</p>
<pre><code>from modules import controller
ctrl = controller
</code></pre>
<p><strong>ctrl</strong> variable becomes a pointer to <strong>controller</strong> class.
To create an instance of <strong>controller</strong> class you need to add parenthesis:</p>
<pre><code>from modules import controller
ctrl = controller()
</code></pre>
| 1
|
2009-04-07T08:36:36Z
|
[
"python"
] |
Best way to turn word list into frequency dict
| 722,697
|
<p>What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?</p>
<p>In other words:</p>
<pre><code>['a', 'b', 'b', 'a', 'b', 'c']
-->
{'a': 2, 'b': 3, 'c': 1}
</code></pre>
<p>(I've had to do something like the above so many times, is there anything in the standard lib that does it for you?)</p>
<p>EDIT:</p>
<p>Jacob Gabrielson points out there is <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup&pathrev=68559#Counter" rel="nofollow">something coming in the standard lib</a> for the 2.7/3.1 branch</p>
| 4
|
2009-04-06T18:55:11Z
| 722,702
|
<p>Kind of</p>
<pre><code>from collections import defaultdict
fq= defaultdict( int )
for w in words:
fq[w] += 1
</code></pre>
<p>That usually works nicely.</p>
| 11
|
2009-04-06T18:56:16Z
|
[
"python"
] |
Best way to turn word list into frequency dict
| 722,697
|
<p>What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?</p>
<p>In other words:</p>
<pre><code>['a', 'b', 'b', 'a', 'b', 'c']
-->
{'a': 2, 'b': 3, 'c': 1}
</code></pre>
<p>(I've had to do something like the above so many times, is there anything in the standard lib that does it for you?)</p>
<p>EDIT:</p>
<p>Jacob Gabrielson points out there is <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup&pathrev=68559#Counter" rel="nofollow">something coming in the standard lib</a> for the 2.7/3.1 branch</p>
| 4
|
2009-04-06T18:55:11Z
| 722,755
|
<p>I have to share an interesting but kind of ridiculous way of doing it that I just came up with:</p>
<pre><code>>>> class myfreq(dict):
... def __init__(self, arr):
... for k in arr:
... self[k] = 1
... def __setitem__(self, k, v):
... dict.__setitem__(self, k, self.get(k, 0) + v)
...
>>> myfreq(['a', 'b', 'b', 'a', 'b', 'c'])
{'a': 2, 'c': 1, 'b': 3}
</code></pre>
| 0
|
2009-04-06T19:11:35Z
|
[
"python"
] |
Best way to turn word list into frequency dict
| 722,697
|
<p>What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?</p>
<p>In other words:</p>
<pre><code>['a', 'b', 'b', 'a', 'b', 'c']
-->
{'a': 2, 'b': 3, 'c': 1}
</code></pre>
<p>(I've had to do something like the above so many times, is there anything in the standard lib that does it for you?)</p>
<p>EDIT:</p>
<p>Jacob Gabrielson points out there is <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup&pathrev=68559#Counter" rel="nofollow">something coming in the standard lib</a> for the 2.7/3.1 branch</p>
| 4
|
2009-04-06T18:55:11Z
| 722,767
|
<p>This is an abomination, but:</p>
<pre><code>from itertools import groupby
dict((k, len(list(xs))) for k, xs in groupby(sorted(items)))
</code></pre>
<p>I can't think of a reason one would choose this method over S.Lott's, but if someone's going to point it out, it might as well be me. :)</p>
| 2
|
2009-04-06T19:15:59Z
|
[
"python"
] |
Best way to turn word list into frequency dict
| 722,697
|
<p>What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?</p>
<p>In other words:</p>
<pre><code>['a', 'b', 'b', 'a', 'b', 'c']
-->
{'a': 2, 'b': 3, 'c': 1}
</code></pre>
<p>(I've had to do something like the above so many times, is there anything in the standard lib that does it for you?)</p>
<p>EDIT:</p>
<p>Jacob Gabrielson points out there is <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup&pathrev=68559#Counter" rel="nofollow">something coming in the standard lib</a> for the 2.7/3.1 branch</p>
| 4
|
2009-04-06T18:55:11Z
| 722,806
|
<p>I find that the easiest to understand (while might not be the most efficient) way is to do:</p>
<pre><code>{i:words.count(i) for i in set(words)}
</code></pre>
| 18
|
2009-04-06T19:28:51Z
|
[
"python"
] |
Best way to turn word list into frequency dict
| 722,697
|
<p>What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?</p>
<p>In other words:</p>
<pre><code>['a', 'b', 'b', 'a', 'b', 'c']
-->
{'a': 2, 'b': 3, 'c': 1}
</code></pre>
<p>(I've had to do something like the above so many times, is there anything in the standard lib that does it for you?)</p>
<p>EDIT:</p>
<p>Jacob Gabrielson points out there is <a href="http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup&pathrev=68559#Counter" rel="nofollow">something coming in the standard lib</a> for the 2.7/3.1 branch</p>
| 4
|
2009-04-06T18:55:11Z
| 727,509
|
<p>Just a note that, starting with Python 2.7/3.1, this functionality will be built in to the <code>collections</code> module, see <a href="http://bugs.python.org/issue1696199">this bug</a> for more information. Here's the example from the <a href="http://docs.python.org/dev/whatsnew/2.7.html">release notes</a>:</p>
<pre><code>>>> from collections import Counter
>>> c=Counter()
>>> for letter in 'here is a sample of english text':
... c[letter] += 1
...
>>> c
Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
'p': 1, 'r': 1, 'x': 1})
>>> c['e']
5
>>> c['z']
0
</code></pre>
| 6
|
2009-04-07T20:42:20Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.