content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
case-insensitive alphabetical sorting of nested lists
i'm trying to sort this nested list by inner's list first element:
ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
print i
}
by default python considers A > a, hence the output i get is:
['A', 11]... | case-insensitive alphabetical sorting of nested lists | i'm trying to sort this nested list by inner's list first element:
ak = [ ['a',1],['E',2],['C',13],['A',11],['b',9] ]
ak.sort(cmp=lambda x, y: cmp(x[0], y[0]))
for i in ak: {
print i
}
by default python considers A > a, hence the output i get is:
['A', 11] ['C', 13] ['E', 2] ['a', 1] ['b', 9]
i've tried convertin... | [
"Try:\nak.sort(key=lambda x:x[0].lower())\n\nI would recommend that you avoid using cmp as this has been deprecated in Python 2.6, and removed in 3.0. I know you're using 2.4, but the reason cmp has fallen into disfavour is that it is a very slow way to sort.\nI'm not sure why your effort with lower failed, though.... | [
9,
3
] | [] | [] | [
"python"
] | stackoverflow_0000710262_python.txt |
Q:
Python 3.0 Windows/COM
How to access a COM object from a python file using python 3.0.
And, yes, I know that not a lot of people are using Python 3.0. Switching back to 2.6 is a huge hassle for me, so I don't want to unless I absolutely have to.
I appreciate your time, and any assistance!
A:
Install pywin32 ... | Python 3.0 Windows/COM | How to access a COM object from a python file using python 3.0.
And, yes, I know that not a lot of people are using Python 3.0. Switching back to 2.6 is a huge hassle for me, so I don't want to unless I absolutely have to.
I appreciate your time, and any assistance!
| [
"Install pywin32 and then create the object using it's progid:\nimport win32com.client\nobject = win32com.client.Dispatch(\"Outlook.Application\")\n\nSee also the Python and COM tutorial.\nEDIT: Hmm... looks like they may not have a python 3.0 version yet. \n"
] | [
6
] | [] | [] | [
"com",
"python",
"python_3.x"
] | stackoverflow_0000710278_com_python_python_3.x.txt |
Q:
How do I parse XML from a Google App Engine app?
How do I parse XML from a Google App Engine app? Any examples?
A:
Since the question was asked, Google has whitelisted pyexpat, which includes minidom, so you can use the following code without having to upload any libraries:
from xml.dom import minidom
dom = min... | How do I parse XML from a Google App Engine app? | How do I parse XML from a Google App Engine app? Any examples?
| [
"Since the question was asked, Google has whitelisted pyexpat, which includes minidom, so you can use the following code without having to upload any libraries:\nfrom xml.dom import minidom\n\ndom = minidom.parseString('<eg>example text</eg>')\n\nMore information:\nhttp://docs.python.org/library/xml.dom.minidom.htm... | [
20,
8,
4
] | [] | [] | [
"google_app_engine",
"parsing",
"python",
"xml"
] | stackoverflow_0000410954_google_app_engine_parsing_python_xml.txt |
Q:
Why do languages like Java use hierarchical package names, while Python does not?
I haven't done enterprise work in Java, but I often see the reverse-domain-name package naming convention. For example, for a Stack Overflow Java package you'd put your code underneath package com.stackoverflow.
I just ran across a P... | Why do languages like Java use hierarchical package names, while Python does not? | I haven't done enterprise work in Java, but I often see the reverse-domain-name package naming convention. For example, for a Stack Overflow Java package you'd put your code underneath package com.stackoverflow.
I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments ... | [
"Python doesn't do this because you end up with a problem -- who owns the \"com\" package that almost everything else is a subpackage of? Python's method of establishing package hierarchy (through the filesystem hierarchy) does not play well with this convention at all. Java can get away with it because package h... | [
18,
14,
12,
12,
11,
6,
2,
0
] | [] | [] | [
"java",
"package",
"python"
] | stackoverflow_0000709036_java_package_python.txt |
Q:
How to tell the difference between an iterator and an iterable?
In Python the interface of an iterable is a subset of the iterator interface. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable __it... | How to tell the difference between an iterator and an iterable? | In Python the interface of an iterable is a subset of the iterator interface. This has the advantage that in many cases they can be treated in the same way. However, there is an important semantic difference between the two, since for an iterable __iter__ returns a new iterator object and not just self. How can I test ... | [
"'iterator' if obj is iter(obj) else 'iterable'\n\n",
"\nHowever, there is an important semantic difference between the two...\n\nNot really semantic or important. They're both iterable -- they both work with a for statement.\n\nThe difference is for example important when one wants to loop multiple times.\n\nWh... | [
12,
3,
2,
0
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0000709084_iterator_python.txt |
Q:
generating plural forms into a .pot file
I'm internationalizing a python program and cant get plural forms into the .pot file. I have marked string that require plural translations with a _pl() eg.
self.write_info(_pl("%(num)d track checked", "%(num)d tracks checked",
song_obj.song_count) % {... | generating plural forms into a .pot file | I'm internationalizing a python program and cant get plural forms into the .pot file. I have marked string that require plural translations with a _pl() eg.
self.write_info(_pl("%(num)d track checked", "%(num)d tracks checked",
song_obj.song_count) % {"num" : song_obj.song_count})
Then I'm running... | [
"I haven't used this with Python, and can't test at the moment, but try --keyword=_pl:1,2 instead.\nFrom the GNU gettext docs:\n\n--keyword[=keywordspec]’\n Additional keyword to be looked for (without keywordspec means not to use default keywords).\nIf keywordspec is a C identifier id, xgettext looks for stri... | [
3
] | [] | [] | [
"internationalization",
"python",
"xgettext"
] | stackoverflow_0000711637_internationalization_python_xgettext.txt |
Q:
Is there a good python module that does HTML encoding/escaping in C?
There is cgi.escape but that appears to be implemented in pure python. It seems like most frameworks like Django also just run some regular expressions. This is something we do a lot, so it would be good to have it be as fast as possible.
Maybe... | Is there a good python module that does HTML encoding/escaping in C? | There is cgi.escape but that appears to be implemented in pure python. It seems like most frameworks like Django also just run some regular expressions. This is something we do a lot, so it would be good to have it be as fast as possible.
Maybe C implementations wouldn't be much faster than a series of regexes for th... | [
"See lxml, which is based on libxml2. While it's primarily a XML library, HTML support is available.\n"
] | [
0
] | [] | [] | [
"escaping",
"python",
"python_module"
] | stackoverflow_0000712113_escaping_python_python_module.txt |
Q:
Backslashes being added into my cookie in Python
I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real... | Backslashes being added into my cookie in Python | I am working with Python's SimpleCookie and I ran into this problem and I am not sure if it is something with my syntax or what. Also, this is classwork for my Python class so it is meant to teach about Python so this is far from the way I would do this in the real world.
Anyway, so basically I am keeping informatio... | [
"As explained by others, the backslashes are escaping double quote characters you insert into the cookie value. The (hidden) mechanism in action here is the SimpleCookie class. The BaseCookie.output() method returns a string representation suitable to be sent as HTTP headers. It will insert escape characters (backs... | [
3,
2,
2,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0000709937_python.txt |
Q:
How to work around needing to update a dictionary
I need to delete a k/v pair from a dictionary in a loop. After getting RuntimeError: dictionary changed size during iteration I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. Howev... | How to work around needing to update a dictionary | I need to delete a k/v pair from a dictionary in a loop. After getting RuntimeError: dictionary changed size during iteration I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. However, as many of you will probably know-I get the same er... | [
"Without code, I'm assuming you're writing something like:\nfor key in dict:\n if check_condition(dict[key]):\n del dict[key]\n\nIf so, you can write\nfor key in list(dict.keys()):\n if key in dict and check_condition(dict[key]):\n del dict[key]\n\nlist(dict.keys()) returns a copy of the keys, no... | [
6,
4,
1
] | [] | [] | [
"dictionary",
"python",
"runtime_error"
] | stackoverflow_0000712225_dictionary_python_runtime_error.txt |
Q:
Is it possible to get a timezone in Python given a UTC timestamp and a UTC offset?
I have data that is the UTC offset and the UTC time. Given that, is it possible in Python to get the user's local timezone (mainly to figure if it is DST etc. probably using pytz), similar to the function in PHP timezone_name_from_a... | Is it possible to get a timezone in Python given a UTC timestamp and a UTC offset? | I have data that is the UTC offset and the UTC time. Given that, is it possible in Python to get the user's local timezone (mainly to figure if it is DST etc. probably using pytz), similar to the function in PHP timezone_name_from_abbr?
For example:
If my epoch time is 1238720309,
I can get the UTC time as:
>>> d = dat... | [
"Since, in general, there is more than one possible time zone for a given time zone offset, the general answer is \"No, not without more information\". The more information is typically the location to which the time applies - which country, or state, or city.\n",
"No. Time zones are too complicated and there a... | [
5,
1,
0
] | [] | [] | [
"dst",
"python",
"pytz",
"timezone",
"utc"
] | stackoverflow_0000712322_dst_python_pytz_timezone_utc.txt |
Q:
How to deliver instance of object to instance of SocketServer.BaseRequestHandler?
This is problem.
My primary work is : deliver "s" object to "handle" method in TestRequestHandler class.
My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object... | How to deliver instance of object to instance of SocketServer.BaseRequestHandler? | This is problem.
My primary work is : deliver "s" object to "handle" method in TestRequestHandler class.
My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object to TestRequestHandler? Some suggestions?
import threading
import SocketServer
from soc... | [
"If I understand correctly, I think you perhaps are misunderstanding how the module works. You are already specifying an address of 'localhost:6666' for the server to bind on. \nWhen you start the server via your call to serve_forever(), this is going to cause the server to start listening to a socket on localhos... | [
2,
1,
1
] | [] | [] | [
"python",
"python_2.7",
"sockets",
"socketserver",
"tcp"
] | stackoverflow_0000711002_python_python_2.7_sockets_socketserver_tcp.txt |
Q:
How to disable v1 tag in a Web service request with SoapPy?
I'm trying to use SOAPpy to write a web service client. However after defining WSDL object, a call to a web-service method is wrapped in a
<v1> .. actual parameters .. </v1>
How can I disable this v1 tag?
A:
You can give the name of tag by providing ... | How to disable v1 tag in a Web service request with SoapPy? | I'm trying to use SOAPpy to write a web service client. However after defining WSDL object, a call to a web-service method is wrapped in a
<v1> .. actual parameters .. </v1>
How can I disable this v1 tag?
| [
"You can give the name of tag by providing name in the parameter call list, i.e:\nserver.GetList(GetListRequest = { \"order\" : \"asc\" })\n\nthen v1 is replaced by GetListRequest as I originally wanted.\n"
] | [
0
] | [] | [] | [
"python",
"soappy",
"web_services"
] | stackoverflow_0000713522_python_soappy_web_services.txt |
Q:
How do I schedule a process' termination?
I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?
A:
This is in Perl, but you should be able to transla... | How do I schedule a process' termination? | I need to run a process, wait a few hours, kill it, and start it again. Is there an easy way that I can accomplish this with Python or Bash? I can run it in the background but how do I identify it to use kill on it?
| [
"This is in Perl, but you should be able to translate it to Python.\n#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\n#set times to 0 for infinite times\nmy ($times, $wait, $program, @args) = @ARGV;\n\n$times = -1 unless $times;\nwhile ($times--) {\n $times = -1 if $times < 0; #catch -2 and turn it back into -1\... | [
3,
3,
2,
0,
0,
0,
0
] | [] | [] | [
"bash",
"kill",
"process",
"python",
"unix"
] | stackoverflow_0000704203_bash_kill_process_python_unix.txt |
Q:
Preserving the Java-type of an object when passing it from Java to Jython
I wonder if it possible to not have jython automagicaly transform java objects to python types when you put them in a Java ArrayList.
Example copied from a jython-console:
>>> b = java.lang.Boolean("True");
>>> type(b)
<type 'javainstance'>
... | Preserving the Java-type of an object when passing it from Java to Jython | I wonder if it possible to not have jython automagicaly transform java objects to python types when you put them in a Java ArrayList.
Example copied from a jython-console:
>>> b = java.lang.Boolean("True");
>>> type(b)
<type 'javainstance'>
>>> isinstance(b, java.lang.Boolean);
1
So far, everything is fine but if I pu... | [
"You appear to be using an old version of Jython. In current Jython versions, the Python bool type corresponds to a Java Boolean.\nJython is not transforming the Java type to a Python type on the way into the ArrayList - on the contrary, it will transform a primitive Python type to a primitive or wrapper Java type... | [
1
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0000713675_java_jython_python.txt |
Q:
questions re: current state of GUI programming with Python
I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what s... | questions re: current state of GUI programming with Python | I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I ... | [
"seems your complains are about wxPython, not about Python itself. try pyQt (or is it qtPython?)\nbut, both wxPython and pyQt are just Python bindings to a C / C++ (respectively) library, it's just as (conceptually) low level as the originals.\nbut, Qt is far superior to wx\n",
"PyQt is a binding to Qt SDK from ... | [
11,
4,
3,
3,
2,
2,
0,
0,
0
] | [] | [] | [
"python",
"user_interface"
] | stackoverflow_0000707491_python_user_interface.txt |
Q:
Why Jython behaves inconsistently when tested with PyStone?
I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start t... | Why Jython behaves inconsistently when tested with PyStone? | I've been playing recently with Jython and decided to do some quick and dirty benchmarking with pystone. In order to have a reference, I first tested cPython 2.6, with an increasing numbers of loops (I thought this may be relevant as Jython should start to profit from the JIT only after some time).
(richard garibaldi):... | [
"This might be a bug in jython 2.5b1. You should consider reporting it back to the jython team. I have just run the pystone benchmark on my MacBook with the current stable release of jython (2.2.1) and I get slow but consistent results:\nmo$ ~/Coding/Jython/jython2.2.1/jython pystone.py 50000\nPystone(1.1) time for... | [
2,
2,
2,
1,
1
] | [] | [] | [
"benchmarking",
"java",
"jython",
"performance",
"python"
] | stackoverflow_0000597483_benchmarking_java_jython_performance_python.txt |
Q:
calling execfile() in custom namespace executes code in '__builtin__' namespace
When I call execfile without passing the globals or locals arguments it creates objects in the current namespace, but if I call execfile and specify a dict for globals (and/or locals), it creates objects in the __builtin__ namespace.
... | calling execfile() in custom namespace executes code in '__builtin__' namespace | When I call execfile without passing the globals or locals arguments it creates objects in the current namespace, but if I call execfile and specify a dict for globals (and/or locals), it creates objects in the __builtin__ namespace.
Take the following example:
# exec.py
def myfunc():
print 'myfunc created in %s n... | [
"First off, __name__ is not a namespace - its a reference to the name of the module it belongs to, ie: somemod.py -> somemod.__name__ == 'somemod'\nThe exception to this being if you run a module as an executable from the commandline, then the __name__ is '__main__'.\nin your example there is a lucky coincidence th... | [
4,
1,
1
] | [] | [] | [
"namespaces",
"python"
] | stackoverflow_0000711066_namespaces_python.txt |
Q:
Turning ctypes data into python string as quickly as possible
I'm trying to write a video application in PyQt4 and I've used Python ctypes to hook into an old legacy video decoder library. The library gives me 32-bit ARGB data and I need to turn that into a QImage. I've got it working as follows:
# Copy the rgb i... | Turning ctypes data into python string as quickly as possible | I'm trying to write a video application in PyQt4 and I've used Python ctypes to hook into an old legacy video decoder library. The library gives me 32-bit ARGB data and I need to turn that into a QImage. I've got it working as follows:
# Copy the rgb image data from the pointer into the buffer
memmove(self.rgb_buffer,... | [
"The ctypes.c_char_Array_829400 instance has the property .raw which returns a string possibly containing NUL bytes, and the property .value which returns the string up to the first NUL byte if it contains one or more.\nHowever, you can also use ctypes the access the string at self.rgb_buffer_ptr, like this:\nctype... | [
6
] | [] | [] | [
"ctypes",
"pyqt4",
"python"
] | stackoverflow_0000714367_ctypes_pyqt4_python.txt |
Q:
WeakValueDictionary for holding any type
Is there any way to work around the limitations of WeakValueDictionary to allow it to hold weak references to built-in types like dict or list? Can something be done at the C level in an extension module? I really need a weakref container that can hold (nearly) any type o... | WeakValueDictionary for holding any type | Is there any way to work around the limitations of WeakValueDictionary to allow it to hold weak references to built-in types like dict or list? Can something be done at the C level in an extension module? I really need a weakref container that can hold (nearly) any type of object.
| [
"According to the Python documentation you can create weak references to subclasses of dict and list... it's not a perfect solution, but if you're able to create a custom subclass of dict and use that instead of a native dict, it should be good enough. (I've never actually done this myself)\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0000715125_python.txt |
Q:
Best way to encode tuples with json
In python I have a dictionary that maps tuples to a list of tuples. e.g.
{(1,2): [(2,3),(1,7)]}
I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.
Is the best way to handle ... | Best way to encode tuples with json | In python I have a dictionary that maps tuples to a list of tuples. e.g.
{(1,2): [(2,3),(1,7)]}
I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.
Is the best way to handle this is encode it as "1,2" and then parse... | [
"You might consider saying\n{\"[1,2]\": [(2,3),(1,7)]}\n\nand then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in JSON.parse method (I'm using jQuery.each to iterate here but you could use anything):\nvar myjson = JSON.p... | [
28,
10,
3,
2,
1
] | [] | [] | [
"json",
"python"
] | stackoverflow_0000715550_json_python.txt |
Q:
Python SAX parser says XML file is not well-formed
I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema... | Python SAX parser says XML file is not well-formed | I stripped some tags that I thought were unnecessary from an XML file. Now when I try to parse it, my SAX parser throws an error and says my file is not well-formed. However, I know every start tag has an end tag. The file's opening tag has a link to an XML schema. Could this be causing the trouble? If so, then how do ... | [
"I would suggest putting those tags back in and making sure it still works. Then, if you want to take them out, do it one at a time until it breaks.\nHowever, I question the wisdom of taking them out. If it's your XML file, you should understand it better. If it's a third-party XML file, you really shouldn't be fid... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"sax",
"xml"
] | stackoverflow_0000708531_python_sax_xml.txt |
Q:
Launching a .py python script from within a cgi script
I'm trying to launch a .py script from within a cgi script while running a local cgi server.
The cgi script simply receives some data from Google Earth and passes it to the .py script which is currently being called using execfile('script.py') placed at the en... | Launching a .py python script from within a cgi script | I'm trying to launch a .py script from within a cgi script while running a local cgi server.
The cgi script simply receives some data from Google Earth and passes it to the .py script which is currently being called using execfile('script.py') placed at the end of the cgi script.
The script runs to completion, however ... | [
"You say you're launching a python script from a CGI script, but you don't specify what language the CGI script is written in. Because CGI is simply an interface, it's not clear what language the CGI script is written in. I'm going to assume python, since that makes the most sense. \nWhat would work best would b... | [
1,
0
] | [] | [] | [
"cgi",
"python",
"scripting"
] | stackoverflow_0000715791_cgi_python_scripting.txt |
Q:
How can I print entity numbers in my xml document instead of entity names using python's lxml?
I'm using lxml and python to generate xml documents (just using etree.tostring(root) ) but at the moment the resulting xml displays html entities as with named entities ( < ; ) rather than their numeric values ( < ;... | How can I print entity numbers in my xml document instead of entity names using python's lxml? | I'm using lxml and python to generate xml documents (just using etree.tostring(root) ) but at the moment the resulting xml displays html entities as with named entities ( < ; ) rather than their numeric values ( < ; ). How exactly do I go about changing this so that the result uses the numeric values instead of t... | [
"Ultimately, it looks like the python code will call xmlNodeDumpOutput in the libxml2 library.\nUnfortunately, it doesn't look like there is any way to configure this to control how such entities are represented. Looking at entities.c in xmlEncodeEntitiesReentrant, the < > and & characters are hardcoded to always ... | [
2
] | [] | [] | [
"lxml",
"python",
"xml"
] | stackoverflow_0000715304_lxml_python_xml.txt |
Q:
Barchart sizing of text & barwidth with matplotlib - python
I'm creating a bar chart with matplotlib-0.91 (for the first time) but the y axis labels are being cut off. If I increase the width of the figure enough they eventually show up completely but then the output is not the correct size.
Any way to deal with ... | Barchart sizing of text & barwidth with matplotlib - python | I'm creating a bar chart with matplotlib-0.91 (for the first time) but the y axis labels are being cut off. If I increase the width of the figure enough they eventually show up completely but then the output is not the correct size.
Any way to deal with this?
| [
"I think I ran into a similar problem.\nSee if this helps adjusting the label's font size:\nimport matplotlib.pyplot as plt\nimport matplotlib.font_manager as fm\n\nfontsize2use = 10\n\nfig = plt.figure(figsize=(10,5))\nplt.xticks(fontsize=fontsize2use) \nplt.yticks(fontsize=fontsize2use) \nfontprop = fm.FontPr... | [
4,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0000712082_matplotlib_python.txt |
Q:
Populating form field based on query/slug factor
I've seen some similar questions, but nothing that quite pointed me in the direction I was hoping for. I have a situation where I have a standard django form built off of a model. This form has a drop down box where you select an item you want to post a comment on. ... | Populating form field based on query/slug factor | I've seen some similar questions, but nothing that quite pointed me in the direction I was hoping for. I have a situation where I have a standard django form built off of a model. This form has a drop down box where you select an item you want to post a comment on. Now I'd like people to be able to browse by items, and... | [
"If I'm reading your question right, this is a fairly common use-case and well support by django forms. You can use the same form for both scenarios you describe.\nLet's say the item to be commented has the primary key 5. You would build a link for the user to click with a URL that looks like this:\n<a href=\"/comm... | [
1
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0000715889_django_forms_python.txt |
Q:
OptionParser - supporting any option at the end of the command line
I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around ssh [hostname] [command]).
I want to execute it as such:
./floep [command]
However, I need to pass certain command lin... | OptionParser - supporting any option at the end of the command line | I'm writing a small program that's supposed to execute a command on a remote server (let's say a reasonably dumb wrapper around ssh [hostname] [command]).
I want to execute it as such:
./floep [command]
However, I need to pass certain command lines from time to time:
./floep -v [command]
so I decided to use optparse.O... | [
"Try using disable_interspersed_args()\n#!/usr/bin/env python\nfrom optparse import OptionParser\n\nparser = OptionParser()\nparser.disable_interspersed_args()\nparser.add_option(\"-v\", action=\"store_true\", dest=\"verbose\")\n(options, args) = parser.parse_args()\n\nprint \"Options: %s args: %s\" % (options, arg... | [
13,
1,
1
] | [
"You can use a bash script like this:\n#!/bin/bash\nwhile [ \"-\" == \"${1:0:1}\" ] ; do\n if [ \"-v\" == \"${1}\" ] ; then\n # do something\n echo \"-v\"\n elif [ \"-s\" == \"${1}\" ] ; then\n # do something\n echo \"-s\"\n fi\n shift\ndone\n${@}\n\nThe ${@} gives you the rest of the command line t... | [
-1
] | [
"optparse",
"python"
] | stackoverflow_0000716006_optparse_python.txt |
Q:
How to integrate BIRT with Python
Has anyone ever tried that?
A:
What kind of integration are you talking about?
If you want to call some BIRT API the I gues it could be done from Jython as Jython can call any Java API.
If you don't need to call the BIRT API then you can just get the birt reports with http reque... | How to integrate BIRT with Python | Has anyone ever tried that?
| [
"What kind of integration are you talking about?\nIf you want to call some BIRT API the I gues it could be done from Jython as Jython can call any Java API.\nIf you don't need to call the BIRT API then you can just get the birt reports with http requests from the BIRT report server (a tomcat application).\n"
] | [
1
] | [] | [] | [
"birt",
"java",
"python",
"reporting"
] | stackoverflow_0000697594_birt_java_python_reporting.txt |
Q:
My first python program: can you tell me what I'm doing wrong?
I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.
I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.
Th... | My first python program: can you tell me what I'm doing wrong? | I hope this question is considered appropriate for stackoverflow. If not, I'll remove the question right away.
I've just wrote my very first python program. The idea is that you can issue a command, and it's gets sent to several servers in parallel.
This is just for personal educational purposes. The program works! I r... | [
"Usually is preferred that what follows after the end of sentence : is in a separate line (also don't add a space before it)\nif options.verbose:\n print \"\"\n\ninstead of\nif options.verbose : print \"\"\n\nYou don't need to check the len of a list if you are going to iterate over it\nif len(threadlist) > 0 : \n... | [
10,
7,
5,
3
] | [] | [] | [
"python"
] | stackoverflow_0000716278_python.txt |
Q:
Google Data API authentication
I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs
First step (AuthSubRequest) which is getting the single-use token works ... | Google Data API authentication | I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs
First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionTo... | [
"According to the 2.0 documentation here there is a python example set...\n\nRunning the sample code\nA full working sample client, containing all the sample code shown in this document, is available in the Python client library distribution, under the directory samples/contacts/contacts_example.py.\nThe sample cli... | [
4,
1,
1
] | [] | [] | [
"django",
"gdata",
"gdata_api",
"google_api",
"python"
] | stackoverflow_0000695703_django_gdata_gdata_api_google_api_python.txt |
Q:
Why is my PyObjc Cocoa view class forgetting its fields?
I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a vie... | Why is my PyObjc Cocoa view class forgetting its fields? | I was trying to hack up a tool to visualize shaders for my game and I figured I would try using python and cocoa. I have ran into a brick wall of sorts though. Maybe its my somewhat poor understand of objective c but I can not seem to get this code for a view I was trying to write working:
from objc import YES, NO, IBA... | [
"Depending on what's happening elsewhere in your app, your instance might actually be getting copied. \nIn this case, implement the copyWithZone method to ensure that the new copy gets the renderer as well. (Caveat, while I am a Python developer, and an Objective-C cocoa developer, I haven't used PyObjC myself, so ... | [
3,
2
] | [] | [] | [
"macos",
"pyobjc",
"python",
"xcode"
] | stackoverflow_0000716386_macos_pyobjc_python_xcode.txt |
Q:
Does the Python library httplib2 cache URIs with GET strings?
In the following example what is cached correctly? Is there a Vary-Header I have to set server-side for the GET string?
import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://test.com/list/")
resp, content = h.request("http://test... | Does the Python library httplib2 cache URIs with GET strings? | In the following example what is cached correctly? Is there a Vary-Header I have to set server-side for the GET string?
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/lis... | [
"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.\nFor the chapter and verse from the __init__.py file for httplib2, if you would like proof, have a look at call to the cache on around line 1000:\ncachekey = defrag_uri\n... | [
4
] | [] | [] | [
"caching",
"httplib2",
"python"
] | stackoverflow_0000717700_caching_httplib2_python.txt |
Q:
Self-repairing Python threads
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... | Self-repairing Python threads | 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 pro... | [
"Just use a try: ... except: ... block in the run 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 whe... | [
8,
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0000717831_multithreading_python.txt |
Q:
Locating (file/line) the invocation of a constructor in python
I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore wh... | Locating (file/line) the invocation of a constructor in python | I'm implementing a event system: Various pieces of code will post events to a central place where they will be distributed to all listeners. The main problem with this approach: When an exception happens during event processing, I can't tell anymore who posted the event.
So my question is: Is there an efficient way to ... | [
"import sys\ndef get_caller(ext=False):\n \"\"\" Get the caller of the caller of this function. If the optional ext parameter is given, returns the line's text as well. \"\"\"\n f=sys._getframe(2)\n s=(f.f_code.co_filename, f.f_lineno)\n del f\n if ext:\n import linecache\n s=(s[0], s[1... | [
1,
1,
1,
0
] | [] | [] | [
"event_handling",
"exception",
"python",
"stack_trace"
] | stackoverflow_0000716795_event_handling_exception_python_stack_trace.txt |
Q:
Unable to put Python code to Joomla
I have a Python code from Google app engine.
I need to implement it to Joomla.
How can you implement Python code to Joomla?
[edit after the 1st answer]
It is enough for me that I can put the code to a module position.
A:
Joomla is PHP based whereas Google App Engine is Python ... | Unable to put Python code to Joomla | I have a Python code from Google app engine.
I need to implement it to Joomla.
How can you implement Python code to Joomla?
[edit after the 1st answer]
It is enough for me that I can put the code to a module position.
| [
"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. \nThere's no straight python to php conversion though.\nEDIT: but if you really want... | [
2
] | [] | [] | [
"joomla",
"python"
] | stackoverflow_0000718498_joomla_python.txt |
Q:
How to execute an arbitrary shell script and pass multiple variables via Python?
I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages... | How to execute an arbitrary shell script and pass multiple variables via Python? | I am building an application plugin in Python which allows users to arbitrarily extend the application with simple scripts (working under Mac OS X). Executing Python scripts is easy, but some users are more comfortable with languages like Ruby.
From what I've read, I can easily execute Ruby scripts (or other arbitrary... | [
"See http://docs.python.org/library/subprocess.html#using-the-subprocess-module\n\nargs should be a string, or a sequence\n of program arguments. The program to\n execute is normally the first item in\n the args sequence or the string if a\n string is given, but can be explicitly\n set by using the executable ... | [
4,
1,
0
] | [] | [] | [
"environment_variables",
"macos",
"python",
"ruby",
"shell"
] | stackoverflow_0000714360_environment_variables_macos_python_ruby_shell.txt |
Q:
How do I print outputs from calls to subprocess.Popen(...) in a loop?
I wrote a script to run a command-line program with different input arguments and grab a certain line from the output. I have the following running in a loop:
p1 = subprocess.Popen(["program", args], stderr=subprocess.STDOUT, stdout=subprocess.P... | How do I print outputs from calls to subprocess.Popen(...) in a loop? | I wrote a script to run a command-line program with different input arguments and grab a certain line from the output. I have the following running in a loop:
p1 = subprocess.Popen(["program", args], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=False)
p2 = subprocess.Popen(["grep", phrase], stdin=p1.stdout, ... | [
"Here's a quick hack that worked for me on Linux. It might work for you, depending on your requirements. It uses tee as a filter that, if you pass print_all to your script, will duplicate an extra copy to /dev/tty (hey, I said it was a hack):\n#!/usr/bin/env python\n\nimport subprocess\nimport sys\n\nphrase = \"b... | [
2,
1
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0000714879_python_subprocess.txt |
Q:
Changing the title of a Tab in wx.Notebook
I'm experimenting with wxPython,
I have a tabbed interface (notebook) and each tab is basically a file list view (yes, I'm trying to make a file manager)
The file list inherits from wx.ListCtrl, and the tabbed interface inherits from wx.Notebook
I'm just starting .. and I... | Changing the title of a Tab in wx.Notebook | I'm experimenting with wxPython,
I have a tabbed interface (notebook) and each tab is basically a file list view (yes, I'm trying to make a file manager)
The file list inherits from wx.ListCtrl, and the tabbed interface inherits from wx.Notebook
I'm just starting .. and I had it so double clicking on a folder will cd i... | [
"I don't know wxPython, but I assume it wraps all the methods of the C++ classes.\nThere is wxNotebook::GetSelection() which returns wxNOT_FOUND or the index of the selected page, which can then be used to call wxNotebook::SetPageText().\nOr use wxNotebook::GetPage() with this index to check whether it is equal to ... | [
2,
0
] | [
"As .GetPage returns a wx.Window, I think tab.Label = title should work.\n"
] | [
-1
] | [
"python",
"tabbed_interface",
"wxpython",
"wxwidgets"
] | stackoverflow_0000718546_python_tabbed_interface_wxpython_wxwidgets.txt |
Q:
Btrieve without Pervasive?
Is there any library available to query Btrieve databases without buying something from Pervasive? I'm looking to code in C# or Python.
A:
As far as I know that is not possible. It is not an open source database, so writing drivers for it is really hard.
A:
If you download one of the... | Btrieve without Pervasive? | Is there any library available to query Btrieve databases without buying something from Pervasive? I'm looking to code in C# or Python.
| [
"As far as I know that is not possible. It is not an open source database, so writing drivers for it is really hard.\n",
"If you download one of the trial versions, you can get/install the odbc client and connect that way.\nIn our version of pervasive (older version) on the server where the database is installed,... | [
2,
2,
0
] | [] | [] | [
"btrieve",
"c#",
"python"
] | stackoverflow_0000080215_btrieve_c#_python.txt |
Q:
can pylons + authkit ignore particular responses with 401 status?
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 ... | can pylons + authkit ignore particular responses with 401 status? | 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 a... | [
"It looks like the authkit.setup.intercept option is designed to do precisely this.\n"
] | [
1
] | [] | [] | [
"authkit",
"http",
"pylons",
"python"
] | stackoverflow_0000717776_authkit_http_pylons_python.txt |
Q:
How to recover a broken python "cPickle" dump?
I am using rss2email for converting a number of RSS feeds into mail for easier consumption. That is, I was using it because it broke in a horrible way today: On every run, it only gives me this backtrace:
Traceback (most recent call last):
File "/usr/share/rss2email... | How to recover a broken python "cPickle" dump? | I am using rss2email for converting a number of RSS feeds into mail for easier consumption. That is, I was using it because it broke in a horrible way today: On every run, it only gives me this backtrace:
Traceback (most recent call last):
File "/usr/share/rss2email/rss2email.py", line 740, in <module>
elif actio... | [
"How I solved my problem\nA Perl port of pickle.py\nFollowing J.F. Sebastian's comment about how simple the pickle\nformat is, I went out to port parts of pickle.py to Perl. A couple\nof quick regular expressions would have been a faster way to access my\ndata, but I felt that the hack value and an opportunity to l... | [
6,
3,
2,
2
] | [] | [] | [
"pickle",
"python",
"rss"
] | stackoverflow_0000664444_pickle_python_rss.txt |
Q:
Significant figures in the decimal module
So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:
from ... | Significant figures in the decimal module | So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly:
from decimal import Decimal
>>> Decimal('1.0') + Dec... | [
"Changing the decimal working precision to 2 digits is not a good idea, unless you absolutely only are going to perform a single operation.\nYou should always perform calculations at higher precision than the level of significance, and only round the final result. If you perform a long sequence of calculations and ... | [
8,
3,
1,
0,
0
] | [
"If I undertand Decimal correctly, the \"precision\" is the number of digits after the decimal point in decimal notation.\nYou seem to want something else: the number of significant digits. That is one more than the number of digits after the decimal point in scientific notation.\nI would be interested in learning ... | [
-1
] | [
"decimal",
"floating_point",
"physics",
"python",
"significance"
] | stackoverflow_0000144218_decimal_floating_point_physics_python_significance.txt |
Q:
Python 3: formatting zip module arguments correctly (newb)
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.
#!c:\python30
#... | Python 3: formatting zip module arguments correctly (newb) | 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.
#!c:\python30
# Filename: backup_ver5.py
import os
import time
import zipfile
... | [
"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.\n",
"To answer your other question: the double backslashes are there because they are escaped.\n"
] | [
3,
1
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0000719503_python_zip.txt |
Q:
App Engine - problem trying to set a Model property value
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.
Here's my code:
def setVenueIntroText(text):
venue_obj = db.GqlQuery("SELECT * FROM Venue").get()
venue_obj.intro_text = text # Works ... | App Engine - problem trying to set a Model property value | 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.
Here's my 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 ... | [
"I think this should work:\ndef setVenueIntroText(text):\n query = db.GqlQuery(\"SELECT * FROM Venue\")\n for result in query:\n result.intro_text = text\n db.put(result)\n\n",
"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 s... | [
1,
1
] | [] | [] | [
"bigtable",
"google_app_engine",
"python"
] | stackoverflow_0000718553_bigtable_google_app_engine_python.txt |
Q:
How can you make a vote-up-down button like in Stackoverflow?
Problems
how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease
how to save the action af an user to an variable NumberOfVotesOfQuestionID
I am not sure whether I should use database or not for the varia... | How can you make a vote-up-down button like in Stackoverflow? | Problems
how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease
how to save the action af an user to an variable NumberOfVotesOfQuestionID
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 nu... | [
"This is a dirty/untested theoretical implementation using jQuery/Django.\nWe'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.\nThe template\n<div id=\"answer_595\" class=\"answer\">\n <img src=\"vote_up.png\" class... | [
60,
8,
3,
0
] | [] | [] | [
"ajax",
"html",
"javascript",
"python"
] | stackoverflow_0000719194_ajax_html_javascript_python.txt |
Q:
How do I set Session name with Cherrypy?
In PHP I would do it like this:
session_name("special_session_name");
So how do I do it with Cherrypy?
Just need to find exact equivalent for it.
PHP manual page:
http://fi2.php.net/session_name
A:
Reading the docs and the source most probably you have to set "tools.ses... | How do I set Session name with Cherrypy? | In PHP I would do it like this:
session_name("special_session_name");
So how do I do it with Cherrypy?
Just need to find exact equivalent for it.
PHP manual page:
http://fi2.php.net/session_name
| [
"Reading the docs and the source most probably you have to set \"tools.sessions.name\" in your config file:\ncherrypy.config.update({'tools.sessions.name': \"special_session_name\"})\n\n"
] | [
3
] | [] | [] | [
"cherrypy",
"php",
"python",
"session"
] | stackoverflow_0000719710_cherrypy_php_python_session.txt |
Q:
How can domain aliases be set up using Django?
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... | How can domain aliases be set up using Django? | 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?
| [
"This is done at the web server level. Django doesn't care about the domain on the incoming request.\nIf you are using Apache just put multiple ServerAlias directives inside your virtual host like this:\n<VirtualHost *:80>\n ServerName www.mydomain.com\n ServerAlias mydomain.com\n ServerAlias forum.mydoma... | [
4
] | [] | [] | [
"cross_domain",
"django",
"dns",
"python"
] | stackoverflow_0000719771_cross_domain_django_dns_python.txt |
Q:
Reversible version of compile() in Python
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,
a = comp("2 * (3 + x)", "", "eval")
eval(a, dict(x=3)) # ... | Reversible version of compile() in Python | 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,
a = comp("2 * (3 + x)", "", "eval")
eval(a, dict(x=3)) # => 12
decomp(a) # => "2 * (3 + x)"
The returne... | [
"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.\nimport ... | [
6,
4
] | [] | [] | [
"metaprogramming",
"python"
] | stackoverflow_0000718769_metaprogramming_python.txt |
Q:
Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL
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.
There are 648 rows in the database: 27 weeks of series for 24 teams. The prob... | Help Me Figure Out A Random Scheduling Algorithm using Python and PostgreSQL | 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.
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 advanc... | [
"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.\nYou could keep your current table, but replace e... | [
2,
1,
1
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0000719886_postgresql_python.txt |
Q:
How do I apply Django model Meta options to models that I did not write?
I want to apply the "ordering" 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... | How do I apply Django model Meta options to models that I did not write? | I want to apply the "ordering" 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?
| [
"This is how the Django manual recommends you do it:\n\nYou 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 regul... | [
9,
6,
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000720083_django_python.txt |
Q:
What's the easiest way/best tutorials to get familiar with SQLAlchemy?
What are best resources/tutorials for starting up with SQLAlchemy?
Maybe some simple step by step stuff like creating a simple table and using it and going up from there.
A:
Personally, I'd buy this book and cram it into the noggin over the c... | What's the easiest way/best tutorials to get familiar with SQLAlchemy? | What are best resources/tutorials for starting up with SQLAlchemy?
Maybe some simple step by step stuff like creating a simple table and using it and going up from there.
| [
"Personally, I'd buy this book and cram it into the noggin over the course of a week or so.\nI've tried tackling SQLAlchemy on the job without learning the details first. I had a hard time with it, because I found the online documentation to be sparse and cryptic (\"read the source for more info...\"). SA also prov... | [
5,
3,
1
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0000195771_python_sqlalchemy.txt |
Q:
How do i use Django session to read/set cookies?
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!
sessionID = request.session["userid"]
The program does not pass this point!
Any ideas?
A:
First, Django already creates a user object ... | How do i use Django session to read/set cookies? | 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!
sessionID = request.session["userid"]
The program does not pass this point!
Any ideas?
| [
"First, Django already creates a user object for you so you don't need to store it in the session. Just access it as:\nrequest.user\n\nFor example, to get the username you would use:\nrequest.user.username\n\nNext, if you want to store information in the session you don't need to worry about it at the cookie level... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000720329_django_python.txt |
Q:
Function definition in Python
I am new to Python. I was trying to define and run a simple function in a class.
Can anybody please tell me what's wrong in my code:
class A :
def m1(name,age,address) :
print('Name -->',name)
print('Age -->',age)
print('Address -->',address)
>>> a = A()
>... | Function definition in Python | I am new to Python. I was trying to define and run a simple function in a class.
Can anybody please tell me what's wrong in my 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 (... | [
"Instance methods take instance as first argument:\nclass A :\n def m1(self, name,age,address) :\n print('Name -->',name)\n print('Age -->',age)\n print('Address -->',address)\n\nYou can also use @staticmethod decorator to create static function:\nclass A :\n @staticmethod\n def m1(nam... | [
18,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0000720621_python.txt |
Q:
HTTP Authentication in Python
Whats is the python urllib equivallent of
curl -u username:password status="abcd" http://example.com/update.json
I did this:
handle = urllib2.Request(url)
authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password))
handle.add_header("Authorization", authheader)
I... | HTTP Authentication in Python | Whats is the python urllib equivallent of
curl -u username:password status="abcd" http://example.com/update.json
I did this:
handle = urllib2.Request(url)
authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password))
handle.add_header("Authorization", authheader)
Is there a better / simpler way?
| [
"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:\npassword_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()\ntop_level_url = \"http://example.com/\"\npassword_mgr.add_passwor... | [
20,
6
] | [] | [] | [
"authentication",
"curl",
"http_headers",
"python"
] | stackoverflow_0000720867_authentication_curl_http_headers_python.txt |
Q:
What's a good two-way encryption library implemented in Python?
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 s... | What's a good two-way encryption library implemented in Python? | 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). Un... | [
"I assume you want an encryption algorithm, not a hash. The PyCrypto library offers a pretty wide range of options. It's in the middle of moving over to a new maintainer, so the docs are a little disorganized, but this is roughly where you want to start looking. I usually use AES for stuff like this.\n",
"If i... | [
21,
8,
6
] | [] | [] | [
"encryption",
"python"
] | stackoverflow_0000721436_encryption_python.txt |
Q:
Monitoring internet activity
I'm looking into writing a small app (in Python) that monitors internet activity. The same idea as NetMeter except with a little more customisation (I need to be able to set off-peak time ranges).
Anyway, I've been having a little trouble researching these questions:
Does Python have ... | Monitoring internet activity | I'm looking into writing a small app (in Python) that monitors internet activity. The same idea as NetMeter except with a little more customisation (I need to be able to set off-peak time ranges).
Anyway, I've been having a little trouble researching these questions:
Does Python have an API to monitor this?
As far as ... | [
"The pylibpcap 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.\n"
] | [
4
] | [] | [] | [
"bandwidth",
"monitoring",
"python"
] | stackoverflow_0000722046_bandwidth_monitoring_python.txt |
Q:
pythonic way to compare compound classes?
I have a class that acts as an item in a tree:
class CItem( list ):
pass
I have two trees, each with CItem as root, each tree item has some dict members (like item._test = 1). Now i need to compare this trees. I can suggest to overload a comparison operator for CItem:
c... | pythonic way to compare compound classes? | I have a class that acts as an item in a tree:
class CItem( list ):
pass
I have two trees, each with CItem as root, each tree item has some dict members (like item._test = 1). Now i need to compare this trees. I can suggest to overload a comparison operator for CItem:
class CItem( list ):
def __eq__( self, other )... | [
"My feeling would be something like\nclass CItem(list):\n def __eq__(self, other):\n return list.__eq__(self, other) and self.__dict__ == other.__dict__\n\nbut it's basically the same code you have, just expressed in shorter notation. I can't think of any more substantial changes to make offhand.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0000722741_python.txt |
Q:
Env Variables in Python (v3.0) on Windows
I'm using Python 3.0.
How to expand an environment variable given the %var_name% syntax?
Any help is much appreciated! Thanks!
A:
It's in a slightly unexpected place: os.path.expandvars(). Admittedly it is quite often used for processing paths:
>>> import os.path
>>> ... | Env Variables in Python (v3.0) on Windows | I'm using Python 3.0.
How to expand an environment variable given the %var_name% syntax?
Any help is much appreciated! Thanks!
| [
"It's in a slightly unexpected place: os.path.expandvars(). Admittedly it is quite often used for processing paths:\n>>> import os.path\n>>> os.path.expandvars('%APPDATA%\\\\MyApp')\n'C:\\\\Documents and Settings\\\\Administrator\\\\Application Data\\\\MyApp'\n\nbut it's a shell function really.\n",
"I'm guessing... | [
3,
2
] | [] | [] | [
"python",
"scripting",
"shell",
"windows"
] | stackoverflow_0000722739_python_scripting_shell_windows.txt |
Q:
Why doesn't the handle_read method get called with asyncore?
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 s... | Why doesn't the handle_read method get called with asyncore? | 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 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 create_socket() method. Unfortunately create_socket() of the dispatcher doesn't take a third argument - so I had to modify my packet_socket() constructor to take a pre-created socket with protocol ... | [
1
] | [] | [] | [
"packet",
"python",
"sockets"
] | stackoverflow_0000722605_packet_python_sockets.txt |
Q:
Data Modelling Advice for Blog Tagging system on Google App Engine
Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitf... | Data Modelling Advice for Blog Tagging system on Google App Engine | Am wondering if anyone might provide some conceptual advice on an efficient way to build a data model to accomplish the simple system described below. Am somewhat new to thinking in a non-relational manner and want to try avoiding any obvious pitfalls. It's my understanding that a basic principal is that "storage is ... | [
"Thanks to both of you for your suggestions. I've implemented (first iteration) as follows. Not sure if it's the best approach, but it's working.\nClass A = Articles. Has a StringListProperty which can be queried on it's list elements\nClass B = Tags. One entity per tag, also keeps a running count of the total ... | [
7,
2,
1,
1
] | [] | [] | [
"data_modeling",
"google_app_engine",
"python"
] | stackoverflow_0000304117_data_modeling_google_app_engine_python.txt |
Q:
Google AppEngine: Date Range not returning correct results
Im trying to search for some values within a date range for a specific type, but content for dates that exist in the database are not being returned by the query.
Here is an extract of the python code:
deltaDays = timedelta(days= 20)
endDate = datetime.dat... | Google AppEngine: Date Range not returning correct results | Im trying to search for some values within a date range for a specific type, but content for dates that exist in the database are not being returned by the query.
Here is an extract of the python code:
deltaDays = timedelta(days= 20)
endDate = datetime.date.today()
startDate = endDate - deltaDays
result = db.GqlQuery(... | [
"nothing looks wrong to me. are you sure that the missing dates also have mytype == type?\ni have observed some funny behaviour with indexes in the past. I recommend writing a handler to iterate through all of your records and just put() them back in the database. maybe something with the bulk uploader isn't wor... | [
1
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0000722728_google_app_engine_gql_python.txt |
Q:
Store last created model's row in memory
I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB.
In general, all changes are stored in DB as history, but I w... | Store last created model's row in memory | I am working on ajax-game. The abstract: 2+ gamers(browsers) change a variable which is saved to DB through json. All gamers are synchronized by javascript-timer+json - periodically reading that variable from DB.
In general, all changes are stored in DB as history, but I want the recent change duplicated in memory.
S... | [
"You can use the cache system:\nhttp://docs.djangoproject.com/en/dev/topics/cache/#topics-cache\n",
"Unfortunately I don't believe you can do this unless you only have one instance of Python running, in which case you can use a global variable. With most web implementations you have a threaded server so this wou... | [
0,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000602030_django_python.txt |
Q:
Inserting object with ManyToMany in Django
I have a blog-like application with stories and categories:
class Category(models.Model):
...
class Story(models.Model):
categories = models.ManyToManyField(Category)
...
Now I know that when you save a new instance of a model with a many-to-many field, probl... | Inserting object with ManyToMany in Django | I have a blog-like application with stories and categories:
class Category(models.Model):
...
class Story(models.Model):
categories = models.ManyToManyField(Category)
...
Now I know that when you save a new instance of a model with a many-to-many field, problems come up because the object is not yet in the... | [
"\"As far as I can fathom, any insert of an object with a many-to-many field will require two database hits,...\"\nSo what?\nMicromanaging each individual database access generally isn't worth all the thinking. Do the simplest, most obvious thing so that Django can optimize cache for you. \nYour application perf... | [
3,
2
] | [] | [] | [
"django",
"many_to_many",
"python"
] | stackoverflow_0000723293_django_many_to_many_python.txt |
Q:
Controlling a Windows Console App w/ stdin pipe
I am trying to control a console application (JTAG app from Segger) from Python using the subprocess module. The application behaves correctly for stdout, but stdin doesn't seem to be read. If enable the shell, I can type into the input and control the application,... | Controlling a Windows Console App w/ stdin pipe | I am trying to control a console application (JTAG app from Segger) from Python using the subprocess module. The application behaves correctly for stdout, but stdin doesn't seem to be read. If enable the shell, I can type into the input and control the application, but I need to do this programmatically. The same co... | [
"As shoosh says, I'd try to verify that the application really is looking for keyboard input. If it is, you can try Win32 message passing, or sending it keyboard input via automation.\nFor the message passing route, you could use the EnumWindows function via ctypes to find the window you're after, then using PostMe... | [
3,
2
] | [] | [] | [
"command_line",
"jtag",
"python",
"subprocess",
"windows"
] | stackoverflow_0000723424_command_line_jtag_python_subprocess_windows.txt |
Q:
Is there any good Python tutorial/guide to use XML-RPC with Last.fm API?
I'm new to XML-RPC and I would like to know if there is any good tutorial to use XML-RPC with the Last.fm API.
Is it possible to call the API methods using the xmlrpclib module like in the following example?
import xmlrpclib
myserver = xmlrpc... | Is there any good Python tutorial/guide to use XML-RPC with Last.fm API? | I'm new to XML-RPC and I would like to know if there is any good tutorial to use XML-RPC with the Last.fm API.
Is it possible to call the API methods using the xmlrpclib module like in the following example?
import xmlrpclib
myserver = xmlrpclib.ServerProxy('http://ws.audioscrobbler.com/2.0/')
| [
"Your code looks just fine.\nYou might not know this, but most XML-RPC endpoints (such as Last.fm's) support XML-RPC introspection. For instance, if you want to find out what methods it exposes, do this: \nimport xmlrpclib\nsvc = xmlrpclib.ServerProxy('http://ws.audioscrobbler.com/2.0/')\nprint svc.system.listMetho... | [
7,
1,
1,
0,
0
] | [] | [] | [
"python",
"web_services",
"xml_rpc"
] | stackoverflow_0000646578_python_web_services_xml_rpc.txt |
Q:
Python class inclusion wrong behaviour
I have into my main.py
from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
and the controllor.py is:
class controller:
def div(self, x, y):
return x // y
when I run my main I got the error:
Traceback (most recent call last):
File ... | Python class inclusion wrong behaviour | I have into my main.py
from modules import controller
ctrl = controller
help(ctrl)
print(ctrl.div(5,2))
and the controllor.py is:
class controller:
def div(self, x, y):
return x // y
when I run my main I got the error:
Traceback (most recent call last):
File "...\main.py", line 8, in ?
print(ctrl.d... | [
"This is very confusing as shown.\nWhen you say\nfrom modules import controller\n\nYou're making the claim that you have a module with a filename of modules.py.\nOR\nYou're making the claim that you have a package named modules. This directory has an __init__.py file and a module with a filename of controller.py\n... | [
4,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000722640_python.txt |
Q:
String inside a string
BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
I get this 'http://foobar.com?foo=bar' # It ignores the inside string.
But i wanted something like this 'http://foobar.com?foo='bar''
Thanks for the answer.
Can you help me out with almost the same pr... | String inside a string | BASE_URL = 'http://foobar.com?foo=%s'
variable = 'bar'
final_url = BASE_URL % (variable)
I get this 'http://foobar.com?foo=bar' # It ignores the inside string.
But i wanted something like this 'http://foobar.com?foo='bar''
Thanks for the answer.
Can you help me out with almost the same problem:
lst = ['foo', 'bar', ... | [
"Change your BASE_URL to either\nBASE_URL = \"http://foobar.com?foo='%s'\"\n\nor\nBASE_URL = 'http://foobar.com?foo=\\'%s\\''\n\n",
"If you're working with URL parameters, it's probably safer to use urllib.urlencode:\nimport urllib\n\nBASE_URL = 'http://foobar.com/?%s'\nprint BASE_URL % urllib.urlencode({\n 'fo... | [
7,
7,
3,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0000720927_python_string.txt |
Q:
ctypes bindings for Subversion in windows
Is there a binary installer or a faq for the new ctypes bindings for Subversion 1.6 in Windows (32 and 64bit)?
What library would you use to make an easy to deploy (both win32 and x64) svn client in python for svn version >= 1.5?
A:
You have the pysvn module which will a... | ctypes bindings for Subversion in windows | Is there a binary installer or a faq for the new ctypes bindings for Subversion 1.6 in Windows (32 and 64bit)?
What library would you use to make an easy to deploy (both win32 and x64) svn client in python for svn version >= 1.5?
| [
"You have the pysvn module which will allow you to do that:\nBinary installer based on subversion 1.5.5\n"
] | [
1
] | [] | [] | [
"ctypes",
"python",
"svn",
"windows"
] | stackoverflow_0000724580_ctypes_python_svn_windows.txt |
Q:
How to handle unicode of an unknown encoding in Django?
I want to save some text to the database using the Django ORM wrappers. The problem is, this text is generated by scraping external websites and many times it seems they are listed with the wrong encoding. I would like to store the raw bytes so I can improve ... | How to handle unicode of an unknown encoding in Django? | I want to save some text to the database using the Django ORM wrappers. The problem is, this text is generated by scraping external websites and many times it seems they are listed with the wrong encoding. I would like to store the raw bytes so I can improve my encoding detection as time goes on without redoing the scr... | [
"You can store data, encoded into base64, for example. Or try to analize HTTP headers from browser, may be it is simplier to get proper encoding from there.\n",
"Create a File with the data. Use a Django models.FileField to hold a reference to the file.\nNo it does not involve a ton of I/O. If your file is smal... | [
1,
1
] | [] | [] | [
"django",
"python",
"unicode"
] | stackoverflow_0000724212_django_python_unicode.txt |
Q:
What's the best way to propagate information from my wx.Process back to my main thread?
I'm trying to subclass wx.Process such that I have a customized process launcher that fires events back to the main thread with data collected from the stdout stream. Is this a good way of doing things?
class BuildProcess(wx.P... | What's the best way to propagate information from my wx.Process back to my main thread? | I'm trying to subclass wx.Process such that I have a customized process launcher that fires events back to the main thread with data collected from the stdout stream. Is this a good way of doing things?
class BuildProcess(wx.Process):
def __init__(self, cmd, notify=None):
wx.Process.__init__(self, notify)
... | [
"The objective is not to call methods of another process, the objective is to redirect the stdout of another process back to the parent process via \"update\" events fired periodically as the process executes. \nOne solution is to use wx.Timer to periodically poll the output stream of the process, so that we don't ... | [
1,
0
] | [] | [] | [
"events",
"multithreading",
"process",
"python",
"wxpython"
] | stackoverflow_0000723984_events_multithreading_process_python_wxpython.txt |
Q:
Programming Design Help - How to Structure a Sudoku Solver program?
I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objec... | Programming Design Help - How to Structure a Sudoku Solver program? | I'm trying to create a sudoku solver program in Java (maybe Python).
I'm just wondering how I should go about structuring this...
Do I create a class and make each box a object of that class (9x9=81 objects)? If yes, how do I control all the objects - in other words, how do I make them all call a certain method in the ... | [
"Don't over-engineer it. It's a 2-D array or maybe a Board class that represents a 2-D array at best. Have functions that calculate a given row/column and functions that let you access each square. Additional methods can be used validate that each sub-3x3 and row/column don't violate the required constraints.\n"... | [
12,
2,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"data_structures",
"python",
"sudoku"
] | stackoverflow_0000431996_data_structures_python_sudoku.txt |
Q:
String manipulation in Python
I am converting some code from another language to python. That code reads a rather large file into a string and then manipulates it by array indexing like:
str[i] = 'e'
This does not work directly in python due to the strings being immutable. What is the preferred way of doing this ... | String manipulation in Python | I am converting some code from another language to python. That code reads a rather large file into a string and then manipulates it by array indexing like:
str[i] = 'e'
This does not work directly in python due to the strings being immutable. What is the preferred way of doing this in python ?
I have seen the string.... | [
"Assuming you're not using a variable-length text encoding such as UTF-8, you can use array.array:\n>>> import array\n>>> a = array.array('c', 'foo')\n>>> a[1] = 'e'\n>>> a\narray('c', 'feo')\n>>> a.tostring()\n'feo'\n\nBut since you're dealing with the contents of a file, mmap should be more efficient:\n>>> f = op... | [
12,
9,
1,
0
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0000725364_python_replace_string.txt |
Q:
Dynamic use of a class method defined in a Cython extension module
I would like to use the C implementation of a class method (generated from Cython) if it is present, or use its Python equivalent if the C extension is not present. I first tried this:
class A(object):
try:
import c_ext
method =... | Dynamic use of a class method defined in a Cython extension module | I would like to use the C implementation of a class method (generated from Cython) if it is present, or use its Python equivalent if the C extension is not present. I first tried this:
class A(object):
try:
import c_ext
method = c_ext.optimized_method
except ImportError:
def method(self)... | [
"Ok I just found the answer...\nThe problem comes from the way Cython wraps the functions it exports: every method is unbound regardless from where it is referenced.\nThe solution is to explicitly declare a bound method:\nclass A(object):\n def method(self):\n return \"foo\"\n\ntry:\n import c_ext\n ... | [
4
] | [] | [] | [
"cython",
"methods",
"python"
] | stackoverflow_0000725777_cython_methods_python.txt |
Q:
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
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.
However, I rarely hear the same a... | If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby? | 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.
However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language.
Why th... | [
"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.\nPhilosophically, it's s... | [
21,
16,
16,
13,
3,
3,
2,
1
] | [] | [] | [
"language_features",
"monkeypatching",
"python",
"ruby"
] | stackoverflow_0000717506_language_features_monkeypatching_python_ruby.txt |
Q:
Finding all *rendered* images in a HTML file
I need a way to find only rendered IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).
I'm using Python on AppEngine.
Any ideas?
Thanks,
Ivan
A:
The s... | Finding all *rendered* images in a HTML file | I need a way to find only rendered IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).
I'm using Python on AppEngine.
Any ideas?
Thanks,
Ivan
| [
"The source code for rendered img tag are something like this:\n<img src=\"img.jpg\"></img>\n\nIf the img tag is displayed as text(not rendered), the html code would be like this:\n <img src="styles/BWLogo.jpg"></img>\n\n< is \"<\" character, > is \">\" character\nTo match rendered img t... | [
2,
2,
2,
0
] | [] | [] | [
"html",
"parsing",
"python",
"regex"
] | stackoverflow_0000725756_html_parsing_python_regex.txt |
Q:
Transferring Python modules
Basically for this case, I am using the _winreg module in Python v2.6 but the python package I have to use is v2.5. When I try to use:
_winreg.ExpandEnvironmentStrings
it complains about not having this attribute in this module. I have successfully transferred other modules like comtyp... | Transferring Python modules | Basically for this case, I am using the _winreg module in Python v2.6 but the python package I have to use is v2.5. When I try to use:
_winreg.ExpandEnvironmentStrings
it complains about not having this attribute in this module. I have successfully transferred other modules like comtypes from site-packages folder.
But... | [
"It's a compiled C extension, not pure Python, so you generally can't simply copy the DLL/so file across from one installation to another: the Python binary interface changes on 0.1 version number updates (but not 0.0.1 updates). In any case, _winreg seems to be statically build into Python.exe on the current offic... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0000727791_python.txt |
Q:
Is there a way to overload += in python?
I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:
(1) if __add__ mutates self, then
z = x + y
will mutate x when I don't really want x to be mutated there.
(2) if __add__ returns a new object, then
tmp... | Is there a way to overload += in python? | I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:
(1) if __add__ mutates self, then
z = x + y
will mutate x when I don't really want x to be mutated there.
(2) if __add__ returns a new object, then
tmp = z
z += x
z += y
tmp += w
return z
will ret... | [
"Yes. Just override the object's __iadd__ method, which takes the same parameters as add. You can find more information here.\n"
] | [
102
] | [] | [] | [
"operator_overloading",
"python"
] | stackoverflow_0000728361_operator_overloading_python.txt |
Q:
Python/urllib suddenly stops working properly
I'm writing a little tool to monitor class openings at my school.
I wrote a python script that will fetch the current availablity of classes from each department every few minutes.
The script was functioning properly until the uni's site started returning this:
SIS Ser... | Python/urllib suddenly stops working properly | I'm writing a little tool to monitor class openings at my school.
I wrote a python script that will fetch the current availablity of classes from each department every few minutes.
The script was functioning properly until the uni's site started returning this:
SIS Server is not available at this time
Uni must have b... | [
"This post doesn't attempt to fix your code, but suggest a debugging tool.\nOnce upon a time I was coding a program to fill out online forms for me. To learn exactly how my browser was handling the POSTs, and cookies, and whatnot, I installed WireShark ( http://www.wireshark.org/ ), a network sniffer. This applic... | [
2,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0000728193_python_urllib.txt |
Q:
Example of how to use msilib to create a .msi file from a python module
Can anyone give me an example of how to use python's msilib standard library module to create a msi file from a custom python module?
For example, let's say I have a custom module called cool.py with the following code
class Cool(object):
... | Example of how to use msilib to create a .msi file from a python module | Can anyone give me an example of how to use python's msilib standard library module to create a msi file from a custom python module?
For example, let's say I have a custom module called cool.py with the following code
class Cool(object):
def print_cool(self):
print "cool"
and I want to create an msi file ... | [
"You need to write a distutils setup script for your module, then you can do\npython setup.py bdist_msi\n\nand an msi-installer will be created for your module.\nSee also http://docs.python.org/distutils/apiref.html#module-distutils.command.bdist_msi\n",
"I think there is a misunderstanding: think of MS CAB Files... | [
5,
0
] | [] | [] | [
"python",
"windows",
"windows_installer"
] | stackoverflow_0000728589_python_windows_windows_installer.txt |
Q:
Python's eval() and globals()
I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval().
But it seems to not work in my case. Here's the simpified example (I tried tw... | Python's eval() and globals() | I'm trying to execute a number of functions using eval(), and I need to create some kind of environment for them to run. It is said in documentation that you can pass globals as a second parameter to eval().
But it seems to not work in my case. Here's the simpified example (I tried two approaches, declaring variable gl... | [
"test_variable should be global in test.py. You're getting a name error because you're trying to declare a variable global that doesn't yet exist.\nSo your my_test.py file should be like this:\ntest_variable = None\n\ndef my_func():\n print test_variable\n\nAnd running this from the command prompt:\n>>> import ... | [
10,
4
] | [] | [] | [
"eval",
"python"
] | stackoverflow_0000729248_eval_python.txt |
Q:
Identifying a map in groovy
While porting over a code fragment from python I've stumbled over a trivial problem:
if isinstance(v['content'], dict):
What would be the most elegant way to port this over to groovy?
A:
You can use instanceof (see map-specific example here), like this:
if (v['content'] instanceof ja... | Identifying a map in groovy | While porting over a code fragment from python I've stumbled over a trivial problem:
if isinstance(v['content'], dict):
What would be the most elegant way to port this over to groovy?
| [
"You can use instanceof (see map-specific example here), like this:\nif (v['content'] instanceof java.util.map)\n\n"
] | [
5
] | [] | [] | [
"groovy",
"python"
] | stackoverflow_0000729354_groovy_python.txt |
Q:
How to I get scons to invoke an external script?
I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clea... | How to I get scons to invoke an external script? | I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clear to me what I need to do.
What I wish to achieve is e... | [
"Something along these lines should do -\nenv.Command ('document.tex', '', 'python table_generator.py')\nenv.PDF ('document.pdf', 'document.tex')\n\nIt declares that 'document.tex' is generated by calling the Python script, and requests a PDF document to be created from this generatd 'document.tex' file.\nNote that... | [
16,
3
] | [] | [] | [
"latex",
"python",
"scons",
"tex"
] | stackoverflow_0000729759_latex_python_scons_tex.txt |
Q:
Seting up Python on IIS 5.1
I have this test python file
import os
print 'Content-type: text/html'
print
print '<HTML><HEAD><TITLE>Python Sample CGI</TITLE></HEAD>'
print '<BODY>'
print "<H1>This is A Sample Python CGI Script</H1>"
print '<br>'
if os.environ.has_key('REMOTE_HOST'):
print "<p>You have access... | Seting up Python on IIS 5.1 | I have this test python file
import os
print 'Content-type: text/html'
print
print '<HTML><HEAD><TITLE>Python Sample CGI</TITLE></HEAD>'
print '<BODY>'
print "<H1>This is A Sample Python CGI Script</H1>"
print '<br>'
if os.environ.has_key('REMOTE_HOST'):
print "<p>You have accessed this site from IP: "+os.enviro... | [
"C:\\Python30\\python.exe -u \"%\" \"%\"\n\nClose, but it should be \"%s\". I use:\n\"C:\\Python30\\python.exe\" -u \"%s\" \n\n(The second %s is for command-line <isindex> queries, which will never happen in this century.)\n"
] | [
2
] | [] | [] | [
"cgi",
"iis",
"iis_5",
"python"
] | stackoverflow_0000730105_cgi_iis_iis_5_python.txt |
Q:
wxPython: Making a fixed-height panel
I have a wx.Frame, in which I have a vertical BoxSizer with two items, a TextCtrl and a custom widget. I want the custom widget to have a fixed pixel height, while the TextCtrl will expand normally to fill the window. What should I do?
A:
Got it.
When creating the widget, us... | wxPython: Making a fixed-height panel | I have a wx.Frame, in which I have a vertical BoxSizer with two items, a TextCtrl and a custom widget. I want the custom widget to have a fixed pixel height, while the TextCtrl will expand normally to fill the window. What should I do?
| [
"Got it.\nWhen creating the widget, use a size of (-1,100), where \"100\" is the height you want. Apparently the \"-1\" is a sort of \"None\" in this context.\nWhen adding the widget to the sizer, use a proportion of 0, like this:\nself.sizer.Add(self.timeline,0,wx.EXPAND)\n"
] | [
6
] | [] | [] | [
"layout",
"python",
"widget",
"wxpython"
] | stackoverflow_0000730394_layout_python_widget_wxpython.txt |
Q:
Python "round robin"
Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:
pairs = [a,b,c,d,e,f]
I have a function that takes two ordered pairs and find the distance between them:
def distance(a,b):
from math import sqrt as sqrt
... | Python "round robin" | Given multiple (x,y) ordered pairs, I want to compare distances between each one of them.
So pretend I have a list of ordered pairs:
pairs = [a,b,c,d,e,f]
I have a function that takes two ordered pairs and find the distance between them:
def distance(a,b):
from math import sqrt as sqrt
from math import pow as ... | [
"in python 2.6, you can use itertools.permutations\nimport itertools\nperms = itertools.permutations(pairs, 2)\ndistances = (distance(*p) for p in perms)\n\nor\nimport itertools\ncombs = itertools.combinations(pairs, 2)\ndistances = (distance(*c) for c in combs)\n\n",
"try:\n\n from itertools import combinatio... | [
17,
10,
6,
4,
3
] | [] | [] | [
"iteration",
"python",
"round_robin"
] | stackoverflow_0000728543_iteration_python_round_robin.txt |
Q:
Pygame Invalid Syntax I just can't figure out
I've been following a tutorial "McGugan - Beginning Game Development with Python and Pygame (Apress, 2007)" and in the code at around chapter five involving object movement I keep getting invalid syntax alerts on '-' being used in the code. It isn't up to date but I wo... | Pygame Invalid Syntax I just can't figure out | I've been following a tutorial "McGugan - Beginning Game Development with Python and Pygame (Apress, 2007)" and in the code at around chapter five involving object movement I keep getting invalid syntax alerts on '-' being used in the code. It isn't up to date but I would've thought a subtract wouldn't be changed in an... | [
"In this line:\ndestination = Vector2(*event.pos) – Vector2(*sprite.get_size())/2.\n\nYou somehow typed the character \"–\" (EN DASH) instead of \"-\" (HYPHEN-MINUS).\nUse \"-\" (HYPHEN-MINUS) instead, like this:\ndestination = Vector2(*event.pos) - Vector2(*sprite.get_size())/2.\n\n",
"I can't be sure without a ... | [
5,
0,
0
] | [] | [] | [
"pygame",
"python",
"syntax"
] | stackoverflow_0000731057_pygame_python_syntax.txt |
Q:
Python script - SCP on windows
How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host... | Python script - SCP on windows | How is it possible to do secure copy using python (windows native install - ActivePython). Unfortunately pexpect module is for unix only and we don't want cygwin locally. I wrote a script that based on pscp.exe win tool - but always stops at first execution becuse of fingerprint host id. and haven't found option to swi... | [
"paramiko is pretty slick. See this question for some more details.\n",
"I strongly recommend that you use keys rather than passwords. If you use ssh keys properly, you do not need to use expect, as the scp command won't ask for any user input. If you have command line ssh installed, you can make a key like th... | [
2,
2,
1,
1,
0
] | [] | [] | [
"copy",
"python",
"windows"
] | stackoverflow_0000729130_copy_python_windows.txt |
Q:
Is there a way to get all the directories but not files in a directory in Python?
This link is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?
A:
There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:
def listfiles(... | Is there a way to get all the directories but not files in a directory in Python? | This link is using a custom method, but I just wanna see if there is a single method to do it in Python 2.6?
| [
"There isn't a built-in function to only list files, but it's easy enough to define in a couple of lines:\ndef listfiles(directory):\n return [f for f in os.listdir(directory) \n if os.path.isdir(os.path.join(directory, f))]\n\nEDIT: fixed, thanks Stephan202\n",
"If a_directory is the directory yo... | [
5,
3,
1,
0
] | [] | [] | [
"directory",
"python"
] | stackoverflow_0000731534_directory_python.txt |
Q:
What's easiest way to get Python script output on the web?
I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seco... | What's easiest way to get Python script output on the web? | I have a python script that runs continuously. It outputs 2 lines of info every 30 seconds. I'd like to be able to view this output on the web. In particular, I'd like the site to auto-update (add the new output at the top of the page/site every 30 seconds without having to refresh the page).
I understand I can do t... | [
"This question appears to have two things in it.\n\nPresentation on the web. This is easy to do in Python -- use Django or TurboGears or any Python-based web framework.\nRefresh of the web page to show new data. This can be done two ways.\n\nSome fancy Javascript to refresh.\nSome fancy HTML to refresh the page. ... | [
5,
3,
2,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0000731470_javascript_python.txt |
Q:
Showing data in a GUI where the data comes from an outside source
I'm kind of lost on how to approach this problem, I'd like to write a GUI ideally using Tkinter with python, but I initially started with Qt and found that the problem extends either with all GUI frameworks or my limited understanding.
The data in t... | Showing data in a GUI where the data comes from an outside source | I'm kind of lost on how to approach this problem, I'd like to write a GUI ideally using Tkinter with python, but I initially started with Qt and found that the problem extends either with all GUI frameworks or my limited understanding.
The data in this case is coming from a named pipe, and I'd like to display whatever ... | [
"When I did something like this I used a separate thread listening on the pipe. The thread had a pointer/handle back to the GUI so it could send the data to be displayed.\nI suppose you could do it in the GUI's update/event loop, but you'd have to make sure it's doing non-blocking reads on the pipe. I did it in a s... | [
0,
0,
0
] | [] | [] | [
"named_pipes",
"python",
"user_interface"
] | stackoverflow_0000731759_named_pipes_python_user_interface.txt |
Q:
How to convert html entities into symbols?
I have made some adaptations to the script from this answer. and I am having problems with unicode. Some of the questions end up being written poorly.
Some answers and responses end up looking like:
Yeah.. I know.. I’m a simpleton.. So what’s a Singleton? (2)
... | How to convert html entities into symbols? | I have made some adaptations to the script from this answer. and I am having problems with unicode. Some of the questions end up being written poorly.
Some answers and responses end up looking like:
Yeah.. I know.. I’m a simpleton.. So what’s a Singleton? (2)
How can I make the ’ to be translated to t... | [
"You should be able to convert HTMl/XML entities into Unicode characters. Check out this answer in SO:\nDecoding HTML Entities With Python\nBasically you want something like this:\nfrom BeautifulSoup import BeautifulStoneSoup\n\nsoup = BeautifulStoneSoup(urllib2.urlopen(URL),\n convertEntit... | [
1,
0
] | [] | [] | [
"beautifulsoup",
"html_entities",
"python",
"unicode"
] | stackoverflow_0000728296_beautifulsoup_html_entities_python_unicode.txt |
Q:
HTML Rich Textbox
I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?
It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.
Thanks!
... | HTML Rich Textbox | I'm writing a web-app using Python and Pylons. I need a textbox that is rich (ie, provides the ability to bold/underline/add bullets..etc...). Does anyone know a library or widget I can use?
It doesn't have to be Python/Pylons specific, as it can be a Javascript implementation as well.
Thanks!
| [
"There are several very mature javascript implementations that are server-framework agnostic:\n\nhttp://www.fckeditor.net/\nTinyMCE\nWMD (used by SO)\n\nThe wikipedia article on Free HTML editors has a good overview, though note that not all are for application embedding.\n",
"ExtJS's HtmlEditor was the best I fo... | [
5,
2,
1
] | [] | [] | [
"http",
"javascript",
"pylons",
"python",
"widget"
] | stackoverflow_0000732429_http_javascript_pylons_python_widget.txt |
Q:
Resetting the main GUI window
I just want the equivalent of closing and reopening my main program. I want to invoke it when a "new"-like option from a drop-down menu is clicked on. Something like calling root.destroy() and then re-initiating the mainloop.
How can I get this done?
A:
There are at least three ways... | Resetting the main GUI window | I just want the equivalent of closing and reopening my main program. I want to invoke it when a "new"-like option from a drop-down menu is clicked on. Something like calling root.destroy() and then re-initiating the mainloop.
How can I get this done?
| [
"There are at least three ways you can solve this. \nMethod one: the head fake. When you create your app, don't put all the widgets in the root window. Instead, hide the root window and create a new toplevel that represents your application. When you restart it's just a matter of destroying that new toplevel and re... | [
4,
2,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0000731887_python_tkinter.txt |
Q:
Django Model: Returning username from currently logged in user
I'm working on a Django app for hosting media (specifically audio and images). I have image galleries and photos separate in my model, and have them linked with a ForeignKey (not sure if that's correct, but still learning). What I need is for the Album... | Django Model: Returning username from currently logged in user | I'm working on a Django app for hosting media (specifically audio and images). I have image galleries and photos separate in my model, and have them linked with a ForeignKey (not sure if that's correct, but still learning). What I need is for the Album class's __unicode__ to return the album owner's username.
class Alb... | [
"There should be no problem accessing the user (even as a foreign key) from a model. I just finished testing it out myself, and there doesn't appear to be any significant difference.\ndef __unicode__(self):\n return self.user.username\n\nOn a side note, you should also just be able to return self.artist, since ... | [
1
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0000732405_django_django_admin_django_models_python.txt |
Q:
Function overloading in Python: Missing
As function overloading says:
Function overloading is absent in Python.
As far as I feel this a big handicap since its also an object-oriented (OO) language. Initially I found that unable to differentiate between the argument types was difficult, but the dynamic nature of Py... | Function overloading in Python: Missing | As function overloading says:
Function overloading is absent in Python.
As far as I feel this a big handicap since its also an object-oriented (OO) language. Initially I found that unable to differentiate between the argument types was difficult, but the dynamic nature of Python made it easy (e.g. list, tuples, strings... | [
"Now, unless you're trying to write C++ code using Python syntax, what would you need overloading for?\nI think it's exactly opposite. Overloading is only necessary to make strongly-typed languages act more like Python. In Python you have keyword argument, and you have *args and **kwargs.\nSee for example: What is ... | [
35,
32,
21,
6,
6
] | [] | [] | [
"missing_features",
"overloading",
"python"
] | stackoverflow_0000733264_missing_features_overloading_python.txt |
Q:
Access list of tuples
I have a list that contains several tuples, like:
[('a_key', 'a value'), ('another_key', 'another value')]
where the first tuple-values act as dictionary-keys.
I'm now searching for a python-like way to access the key/value-pairs, like:
"mylist.a_key" or "mylist['a_key']"
without iterating o... | Access list of tuples | I have a list that contains several tuples, like:
[('a_key', 'a value'), ('another_key', 'another value')]
where the first tuple-values act as dictionary-keys.
I'm now searching for a python-like way to access the key/value-pairs, like:
"mylist.a_key" or "mylist['a_key']"
without iterating over the list. any ideas?
| [
"You can't do it without any iteration. You will either need iteration to convert it into a dict, at which point key access will become possible sans iteration, or you will need to iterate over it for each key access. Converting to a dict seems the better idea-- in the long run it is more efficient, but more import... | [
14,
3
] | [] | [] | [
"python"
] | stackoverflow_0000733574_python.txt |
Q:
How do I make this progress bar close when it is done
I commonly write Python scipts to do conversion tasks for me and whenever I write one that takes a while I use this little progress bar to check on it
import sys
import time
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
barra = QtGui.QProgressBar()... | How do I make this progress bar close when it is done | I commonly write Python scipts to do conversion tasks for me and whenever I write one that takes a while I use this little progress bar to check on it
import sys
import time
from PyQt4 import QtGui
app = QtGui.QApplication(sys.argv)
barra = QtGui.QProgressBar()
barra.show()
barra.setMinimum(0)
barra.setMaximum(10)
for ... | [
"Well, because you set your Maximum to 10, your progress bar shouldn't reach 100% because \nfor a in range(10):\n time.sleep(1)\n barra.setValue(a)\n\nwill only iterate up to 9.\nProgress bars don't close automatically. You will have to call \nbarra.hide()\n\nafter your loop.\nAs for the paint problem, it's likel... | [
5
] | [] | [] | [
"progress_bar",
"pyqt",
"python"
] | stackoverflow_0000732829_progress_bar_pyqt_python.txt |
Q:
Type checking of arguments Python
Sometimes checking of arguments in Python is necessary. e.g. I have a function which accepts either the address of other node in the network as the raw string address or class Node which encapsulates the other node's information.
I use type() function as in:
if type(n) == type... | Type checking of arguments Python | Sometimes checking of arguments in Python is necessary. e.g. I have a function which accepts either the address of other node in the network as the raw string address or class Node which encapsulates the other node's information.
I use type() function as in:
if type(n) == type(Node):
do this
elif type(n... | [
"Use isinstance(). Sample:\nif isinstance(n, unicode):\n # do this\nelif isinstance(n, Node):\n # do that\n...\n\n",
">>> isinstance('a', str)\nTrue\n>>> isinstance(n, Node)\nTrue\n\n",
"Sounds like you're after a \"generic function\" - one which behaves differently based on the arguments given. It's a b... | [
120,
17,
7,
6,
4
] | [] | [] | [
"python",
"typechecking"
] | stackoverflow_0000734368_python_typechecking.txt |
Q:
How do I run another script in Python without waiting for it to finish?
I am creating a little dashboard for a user that will allow him to run specific jobs. I am using Django so I want him to be able to click a link to start the job and then return the page back to him with a message that the job is running. Th... | How do I run another script in Python without waiting for it to finish? | I am creating a little dashboard for a user that will allow him to run specific jobs. I am using Django so I want him to be able to click a link to start the job and then return the page back to him with a message that the job is running. The results of the job will be emailed to him later.
I believe I am supposed to... | [
"p = subprocess.Popen([sys.executable, '/path/to/script.py'], \n stdout=subprocess.PIPE, \n stderr=subprocess.STDOUT)\n\nThat will start the subprocess in background. Your script will keep running normally.\nRead the documentation here.\n",
"Ru... | [
66,
6,
2,
1
] | [] | [] | [
"background",
"django",
"process",
"python",
"subprocess"
] | stackoverflow_0000546017_background_django_process_python_subprocess.txt |
Q:
Propagating application settings
Probably a very common question, but couldn't find suitable answer yet..
I have a (Python w/ C++ modules) application that makes heavy use of an SQLite database and its path gets supplied by user on application start-up.
Every time some part of application needs access to databas... | Propagating application settings | Probably a very common question, but couldn't find suitable answer yet..
I have a (Python w/ C++ modules) application that makes heavy use of an SQLite database and its path gets supplied by user on application start-up.
Every time some part of application needs access to database, I plan to acquire a new session and... | [
"Yes, there are others. Your option 3 though is very Pythonic. \nUse a standard Python module to encapsulate options (this is the way web frameworks like Django do it)\nUse a factory to emit properly configured sessions.\nSince SQLite already has a \"connection\", why not use that? What does your DatabaseSession... | [
2
] | [] | [] | [
"global",
"python",
"settings",
"singleton"
] | stackoverflow_0000735337_global_python_settings_singleton.txt |
Q:
Looping through chars, generating words and checking if domain exists
Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?
What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exi... | Looping through chars, generating words and checking if domain exists | Is there any way to generate words based on characters and checking if a domain exists with this word (ping)?
What I want to do is to generate words based on some characters, example "abcdefgh", and then ping generatedword.com to check if it exists.
| [
"You don't want to use the ping command, but you can use Python's socket.gethostbyname() function to determine whether a host exists.\ndef is_valid_host(hostname):\n try:\n addr = socket.gethostbyname(hostname)\n except socket.gaierror, ex:\n return False\n return True\n\nhosts = ['abc', 'yah... | [
7,
3,
0
] | [] | [] | [
"ping",
"python"
] | stackoverflow_0000735743_ping_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.