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:
How to avoid a recursive loop with __setattr__ and a property setter?
This causes an infinite recursive loop when setattr is called, when trying to set the value for some_prop, which is a property with a setter:
class TypeSystem(object):
def __setattr__(self, key, value):
if the_special_case is True:
... | How to avoid a recursive loop with __setattr__ and a property setter? | This causes an infinite recursive loop when setattr is called, when trying to set the value for some_prop, which is a property with a setter:
class TypeSystem(object):
def __setattr__(self, key, value):
if the_special_case is True:
# do something
else:
super(TypeSystem,self)... | [
"This has nothing to do with __setattr__ or your TypeSystem. Your problem is \n@some_prop.setter\ndef some_prop(self,value):\n self.some_prop = value\n\nThat is clearly an infinite loop - you're trying to set the property in the property's setter.\nYou have the same problem in the getter:\nsome_prop = self.some_... | [
10
] | [] | [] | [
"python"
] | stackoverflow_0007452382_python.txt |
Q:
Using request.FILES in GAE ModelForm
I have a django form using djangoforms.ModelForm. One of the required fields I have is a FileField. I've been trying to figure out how to pass the uploaded file to the form.
I've been trying to use something like:
def post(self):
form = StudentForm(data=self.request.POST, f... | Using request.FILES in GAE ModelForm | I have a django form using djangoforms.ModelForm. One of the required fields I have is a FileField. I've been trying to figure out how to pass the uploaded file to the form.
I've been trying to use something like:
def post(self):
form = StudentForm(data=self.request.POST, files=self.request.FILES)
However, I get t... | [
"If we adapt the answer to the other question you mentioned, that would look like this (not tested):\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\nupload = self.request.params['field_name']\ndjango_files_dict = {'field_name': SimpleUploadedFile(upload.filename,\n ... | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007452232_google_app_engine_python.txt |
Q:
XMPP HTML Message sends to Pidgin but fails to send to Jitsi
Anyone know why a Message formatted in this way would send properly via XMPP to users running Pidgin but fail to send at all to users running Jitsi? There is no error message to accompany the failure.
<message to="fancy.pants@thesrv0001">
<html xmlns... | XMPP HTML Message sends to Pidgin but fails to send to Jitsi | Anyone know why a Message formatted in this way would send properly via XMPP to users running Pidgin but fail to send at all to users running Jitsi? There is no error message to accompany the failure.
<message to="fancy.pants@thesrv0001">
<html xmlns="http://jabber.org/protocol/xhtml-im">
<body xmlns="http://ww... | [
"Not all clients implement XEP-0071 (XHTML-IM), so it recommends both trying to figure out if the other side speaks XHTML (see section 10), and also mandates the use of a normal body element:\n<message>\n <body>hi!</body>\n <html xmlns='http://jabber.org/protocol/xhtml-im'>\n <body xmlns='http://www.w3.org/199... | [
1
] | [] | [] | [
"html",
"pidgin",
"python",
"xmpp"
] | stackoverflow_0007451791_html_pidgin_python_xmpp.txt |
Q:
Linux eventfd's initial value and use in a pollable Lock
Question
eventfd() is a new system call available in Linux since 2.6.22. The call signature is
int eventfd(unsigned int initval, int flags);
I am making use of this call in constructing a new light saberLock class that's usable in a polling loop.
The Python... | Linux eventfd's initial value and use in a pollable Lock | Question
eventfd() is a new system call available in Linux since 2.6.22. The call signature is
int eventfd(unsigned int initval, int flags);
I am making use of this call in constructing a new light saberLock class that's usable in a polling loop.
The Python Lock object starts in an unblocked state. My use of eventfd r... | [
"If I understand you correctly, you want to have the state of this beast to alternate between 0 and UINT64_MAX-1?\nThe type of the initial value is probably just there for historical reasons. Once that such an interface is used it sticks and it is difficult to change it afterwards.\nIf you need the value to be init... | [
1
] | [] | [] | [
"c",
"linux",
"locking",
"polling",
"python"
] | stackoverflow_0007453063_c_linux_locking_polling_python.txt |
Q:
Python: CTypes memory leak with Structure
Does Python ctypes have a known memory leak? I am working on a Python script having code like the below snippet, using ctypes, that for some reason is causing a memory leak. The "while True" in this example is to test for the leak caused by calling the function. It is b... | Python: CTypes memory leak with Structure | Does Python ctypes have a known memory leak? I am working on a Python script having code like the below snippet, using ctypes, that for some reason is causing a memory leak. The "while True" in this example is to test for the leak caused by calling the function. It is being run on Windows with Python 2.5.4:
import c... | [
"That's not a memory leak, that just means the garbage collector hasn't run yet. And even if the garbage collector does run, odds are good that there's some kind of memory pooling going on.\nProcessExplorer isn't a good debugging tool, especially for memory.\n",
"The script in and by itself doesn't leak. Running... | [
2,
1
] | [] | [] | [
"ctypes",
"memory_leaks",
"python"
] | stackoverflow_0007452625_ctypes_memory_leaks_python.txt |
Q:
Get colors of current gtk style
I use PyGTK and I want to get colors of a widget (for example bg color), I run such a code:
gdkColorToRgb = lambda gc: (gc.red//257, gc.green//257, gc.blue//257)
widget = gtk.HBox() ## for example
style = widget.get_style()
for i in range(5):
print i, gdkColorToRgb(style.bg[i])
... | Get colors of current gtk style | I use PyGTK and I want to get colors of a widget (for example bg color), I run such a code:
gdkColorToRgb = lambda gc: (gc.red//257, gc.green//257, gc.blue//257)
widget = gtk.HBox() ## for example
style = widget.get_style()
for i in range(5):
print i, gdkColorToRgb(style.bg[i])
But it does not give colors of my cu... | [
"I just stumbled upon the same issue, saw your question and found a solution: You have to wait until the widget is realized, e.g. like this:\ndef print_style(widget):\n style = widget.get_style()\n for i in range(5):\n print i, gdkColorToRgb(style.bg[i])\ngdkColorToRgb = lambda gc: (gc.red//257, gc.gre... | [
5
] | [] | [] | [
"colors",
"gtk2",
"pygtk",
"python",
"themes"
] | stackoverflow_0006715464_colors_gtk2_pygtk_python_themes.txt |
Q:
Python Pass List to CGI
In Python CGI, is it possible pass "Python list" as hidden text input field ?
How can I retrieve values using cgi form later ?
Thanks for help.
def testinput2(answer):
#answer=['a','b','a','a','a']#according to abc1 statefile
fin = file("2.map", "r")
for line in fin.rea... | Python Pass List to CGI | In Python CGI, is it possible pass "Python list" as hidden text input field ?
How can I retrieve values using cgi form later ?
Thanks for help.
def testinput2(answer):
#answer=['a','b','a','a','a']#according to abc1 statefile
fin = file("2.map", "r")
for line in fin.readlines():
fun.app... | [
"No, HTML elements only support one value per an input element and know nothing of Python lists.\nIf you want to save a list of values in html, you should create list of hidden HTML inputs, each with the same name attribute.\nYou can later get the list of values with form.getvalue(key), where the key is the value o... | [
1
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0007453496_cgi_python.txt |
Q:
How to read .dcm in Xcode using python?
I'm trying to create an app for viewing and analyzing DICOM slices. I have done this app in MATLAB, but MATLAB does not have enough tools to build a really nice GUI and 3D picture is bad. So, I was trying to use ITK and VTK to build an app in Xcode for a long period of time ... | How to read .dcm in Xcode using python? | I'm trying to create an app for viewing and analyzing DICOM slices. I have done this app in MATLAB, but MATLAB does not have enough tools to build a really nice GUI and 3D picture is bad. So, I was trying to use ITK and VTK to build an app in Xcode for a long period of time but without any success. One day I found xcod... | [
"Congratulations on choosing Python for working with DICOM; the SciPy/numpy/matplotlib clan is much better at dealing with huge amounts of volume data than MATLAB (or at least GNU Octave) in my experience.\nTrivia load and display code using GDCM's python bindings, a ConvertNumpy.py from GDCM's examples and matplot... | [
1
] | [] | [] | [
"cocoa",
"dicom",
"matlab",
"python",
"xcode"
] | stackoverflow_0007143638_cocoa_dicom_matlab_python_xcode.txt |
Q:
How can I capture packets from a PPP interface with pypcap?
It's dpkt.ethernet.Ethernet(pkt) for an ethernet interface, what is it for the ppp0 interface?
A:
You're mixing up dpkt, a library for parsing and creating packets, with pypcap, a Python wrapper for libpcap.
To specify an interface to listen on, use pca... | How can I capture packets from a PPP interface with pypcap? | It's dpkt.ethernet.Ethernet(pkt) for an ethernet interface, what is it for the ppp0 interface?
| [
"You're mixing up dpkt, a library for parsing and creating packets, with pypcap, a Python wrapper for libpcap.\nTo specify an interface to listen on, use pcap.pcap(name='ppp0').\nTo deserialize PPP packets, use dpkt.ppp.PPP(pkt).\n"
] | [
4
] | [] | [] | [
"packet_capture",
"pcap",
"ppp",
"python"
] | stackoverflow_0007453840_packet_capture_pcap_ppp_python.txt |
Q:
Why do my Django inlines show multiple forms for single model?
I'm attempting to combine the admin form for the User and my UserProfile model. I found out how to do it here, which works. I have this now:
#DJANGOPROJECT/generic/admin.py
class UserProfileInline(admin.TabularInline):
model = UserProfile
class Us... | Why do my Django inlines show multiple forms for single model? | I'm attempting to combine the admin form for the User and my UserProfile model. I found out how to do it here, which works. I have this now:
#DJANGOPROJECT/generic/admin.py
class UserProfileInline(admin.TabularInline):
model = UserProfile
class UserAdmin(admin.ModelAdmin):
inlines = [UserProfileInline]
admin.... | [
"https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin\n\nInlineModelAdmin.extra This controls the number of extra forms the\n formset will display in addition to the initial forms. See the\n formsets documentation for more information.\nNew in Django 1.2: Please, see the ... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_authentication",
"mysql",
"python"
] | stackoverflow_0007453807_django_django_admin_django_authentication_mysql_python.txt |
Q:
Working with multiple filesystem types: Python won't escape properly?
In short, I'm trying to use distutils.dir_util.copy_tree() to copy data from an ext3 fs to a USB thumbdrive formatted using FAT32. The filenames tend to be long and contain interesting characters - which python strips/escapes fine for ext3. Howe... | Working with multiple filesystem types: Python won't escape properly? | In short, I'm trying to use distutils.dir_util.copy_tree() to copy data from an ext3 fs to a USB thumbdrive formatted using FAT32. The filenames tend to be long and contain interesting characters - which python strips/escapes fine for ext3. However, upon using copy_tree(), the list of illegal characters suddenly grows ... | [
"Python (or any other use-space application) cannot possibly determine the filesystem type in the first place. That might work (albeit be very slow) for simple setups, but inevitably fails in the presence of changing hard and soft links and various filesystems - what do you do when FAT is mounted over FUSE or Union... | [
2,
1
] | [] | [] | [
"fat32",
"linux",
"python"
] | stackoverflow_0007453844_fat32_linux_python.txt |
Q:
Adding to a linked list
Can someone please tell me why my add function is not working:
(it only adds the first {'a', 3} but not the rest)
thankyou
class Frequency(object):
"""
Stores a letter:frequency pair.
>>> f = Frequency('c', 2)
>>> f.letter
'c'
>>> f.frequency
2
>>> f
{c:... | Adding to a linked list | Can someone please tell me why my add function is not working:
(it only adds the first {'a', 3} but not the rest)
thankyou
class Frequency(object):
"""
Stores a letter:frequency pair.
>>> f = Frequency('c', 2)
>>> f.letter
'c'
>>> f.frequency
2
>>> f
{c: 2}
"""
def __init__(... | [
"The problem is that after the first loop current is always None, therefore the second loop body is never executed even in case found is False.\n",
"it seems to me that there is another issue.\nwhen found is false and current.frequency > frequency, you should set current.next.next to the previous next,\nsomething... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007453939_python.txt |
Q:
I need a neat data structure suggestion to store a very large dataset (to train Naive Bayes in Python)
I am going to implement Naive Bayes classifier with Python and classify e-mails as Spam or Not spam. I have a very sparse and long dataset with many entries. Each entry is like the following:
1 9:3 94:1 109:1 163... | I need a neat data structure suggestion to store a very large dataset (to train Naive Bayes in Python) | I am going to implement Naive Bayes classifier with Python and classify e-mails as Spam or Not spam. I have a very sparse and long dataset with many entries. Each entry is like the following:
1 9:3 94:1 109:1 163:1 405:1 406:1 415:2 416:1 435:3 436:3 437:4 ...
Where 1 is label (spam, not spam), and each pair correspond... | [
"If you assume you didn't care about multiple occurrences of each word in an email, then all you really need to know is (that is, your features are booleans):\nFor each feature, what is the count of positive associations and negative associations?\nYou can do this online very easily in one pass, keeping track of ju... | [
0,
0,
0,
0
] | [] | [] | [
"data_structures",
"machine_learning",
"python",
"spam_prevention"
] | stackoverflow_0007452917_data_structures_machine_learning_python_spam_prevention.txt |
Q:
Plotting Histogram: How can I do it from scratch using data stored in a database?
I have some data stored in a database like this:
TableName: faults
Table:
+------------+--------------+
| fault_type | total |
+------------+--------------+
| 1 | 1 |
| 2 | 3 |
| 3 ... | Plotting Histogram: How can I do it from scratch using data stored in a database? | I have some data stored in a database like this:
TableName: faults
Table:
+------------+--------------+
| fault_type | total |
+------------+--------------+
| 1 | 1 |
| 2 | 3 |
| 3 | 8 |
| 4 | 2 |
.............................
H... | [
"The solution below assumes that you have MySQL, Python and GNUPlot. The specific details can be fine tuned if necessary. Posting it so that it could be a baseline for other peers.\nStep #1: Decide the type of graph.\nIf it is a frequency plot of some kind, then a simple SQL query should do the trick:\nselect total... | [
2,
0
] | [] | [] | [
"gnuplot",
"graph",
"histogram",
"mysql",
"python"
] | stackoverflow_0001767565_gnuplot_graph_histogram_mysql_python.txt |
Q:
Is there a Python equivalent to the grave accent in bash scripting?
I don't like using a lot of IF statements. Here is what I am playing around with right now, in the world of having to use a lot of IF statements to get it done:
First, some variables...
pick_level = 1
lockpicking_level1_maxxp = 40
lockpicking_leve... | Is there a Python equivalent to the grave accent in bash scripting? | I don't like using a lot of IF statements. Here is what I am playing around with right now, in the world of having to use a lot of IF statements to get it done:
First, some variables...
pick_level = 1
lockpicking_level1_maxxp = 40
lockpicking_level2_maxxp = 70
lockpicking_level3_maxxp = 100
Now we get to picking a loc... | [
"Don't repeat yourself. Use data structures instead of individual objects as much as possible:\nlockpicking_maxxp = {\n 1: 40,\n 2: 70,\n 3: 100\n}\n\nx = random.randint(1, 100)\nif x > lockpicking_maxxp[pick_level] / 2:\n print 'You failed to pick the lock'\n ...\n\nOf course, you probably have othe... | [
4,
2,
2
] | [] | [] | [
"bash",
"dynamic",
"python",
"replace",
"variables"
] | stackoverflow_0007454523_bash_dynamic_python_replace_variables.txt |
Q:
Python Substituiting a float only giving whole number
I'm reading into a csv file an extracting a piece of data with the line:
x = float(node[1])
when I print(x), I get the correct value or the exact value found in the cell. e.g 153.018848
But when I try to pass x as variable in the following:
print('<node vers... | Python Substituiting a float only giving whole number | I'm reading into a csv file an extracting a piece of data with the line:
x = float(node[1])
when I print(x), I get the correct value or the exact value found in the cell. e.g 153.018848
But when I try to pass x as variable in the following:
print('<node version="0" lon="%d">' %(x))
the output will be <node version... | [
"You've overlooked the fact that %d is for integers. Try %f instead.\n",
"You want to replace your %d with %f, problem solved ;)\nSee: http://docs.python.org/release/2.5.2/lib/typesseq-strings.html\nFor bonus points, are you aware you can put together long format strings that are still readable using dictionaries... | [
3,
1,
1
] | [] | [] | [
"arguments",
"floating_point",
"python",
"variables"
] | stackoverflow_0007454787_arguments_floating_point_python_variables.txt |
Q:
Best way to retrieve data attributes in Python?
I have a question that is puzzling me recently about which is the best way to retrieve attributes from outside.
Let say I have a class:
class Thing:
def __init__(self, whatever):
self.whatever = whatever
x = Thing('foo')
Now I know that if I want to ret... | Best way to retrieve data attributes in Python? | I have a question that is puzzling me recently about which is the best way to retrieve attributes from outside.
Let say I have a class:
class Thing:
def __init__(self, whatever):
self.whatever = whatever
x = Thing('foo')
Now I know that if I want to retrieve whatever attribute I can do this:
x.whatever
I... | [
"Defining explicit getters and setters is a bad practice in Python. Instead, use properties:\nclass Thing(object): # New-style class\n def __init__(self, whatever):\n self._whatever = whatever\n\n @property\n def whatever(self):\n return self._whatever # Insert complicated calculation here\n\... | [
14,
8,
0
] | [] | [] | [
"coding_style",
"python"
] | stackoverflow_0007454879_coding_style_python.txt |
Q:
How to stop a multi-threaded Python script from outside
I have a Python program that uses multiple daemon threads. I want to stop the program from outside, preferably from another Python script.
I've tried with kill <pid> from shell, just for a test, but it doesn't work with multi-threaded scripts.
One way would b... | How to stop a multi-threaded Python script from outside | I have a Python program that uses multiple daemon threads. I want to stop the program from outside, preferably from another Python script.
I've tried with kill <pid> from shell, just for a test, but it doesn't work with multi-threaded scripts.
One way would be to make the program check some file every n-seconds as a fl... | [
"Use the poison pill technique. Upon receipt of a pill (a special message) your program must handle it and die.. The way you're doing it its ok, but for something more elegant, you should implement a kind of communication between your \"killing script\" and your main program. For a start, have a look in the standar... | [
2,
0,
0
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0007453203_multithreading_python.txt |
Q:
Parsing a website with a javascript call using Python
Since I counldn't find an API function in common wikimedia to get alicense of an image, the only thing left to do it to fetch the webpage and parse it myself.
For each image, there is a nice popup in wikimedia that lists the "Attribution" field which I need.
F... | Parsing a website with a javascript call using Python | Since I counldn't find an API function in common wikimedia to get alicense of an image, the only thing left to do it to fetch the webpage and parse it myself.
For each image, there is a nice popup in wikimedia that lists the "Attribution" field which I need.
For example, in the page http://commons.wikimedia.org/wiki/F... | [
"using unutbu's answer, I converted it to use Selenium WebDriver (rather than the older Selenium-RC).\nimport codecs\nimport lxml.html as lh\nfrom selenium import webdriver\n\nbrowser = webdriver.Firefox()\nbrowser.get('http://commons.wikimedia.org/wiki/File%3aBrad_Pitt_Cannes_2011.jpg')\ncontent = browser.page_sou... | [
4,
1,
1
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0007453970_parsing_python.txt |
Q:
Django Unicode- When I Use unicode functions?
I'm From Iran And I Use Persian Character. When should I use 'u', 'decode()', 'encode' and unicode()?
A:
1) You use decode() and unicode() to decode the input string from its representation (for example iso-8859-2 or utf-8) and get the unicode object.
2) You use a u ... | Django Unicode- When I Use unicode functions? | I'm From Iran And I Use Persian Character. When should I use 'u', 'decode()', 'encode' and unicode()?
| [
"1) You use decode() and unicode() to decode the input string from its representation (for example iso-8859-2 or utf-8) and get the unicode object.\n2) You use a u to indicate that the string is to be treated as unicode (in fact the result object is unicode type):\n>>> foo = u'łódź'\n>>> foo.__class__\n<type 'unico... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007452524_django_python.txt |
Q:
Django Forgot Password function changing default email
I created a Forgot Password functionality for my website using the password_reset function that is built in Django
it sends an email like so:
You're receiving this e-mail because you requested a password reset for your user account at example.com.
Please go t... | Django Forgot Password function changing default email | I created a Forgot Password functionality for my website using the password_reset function that is built in Django
it sends an email like so:
You're receiving this e-mail because you requested a password reset for your user account at example.com.
Please go to the following page and choose a new password:
http://exam... | [
"The default template for that email is django/contrib/admin/templates/registration/password_reset_email.html. You can override it by providing your own template templates/registration/password_reset_email.html in your top app directory as usual.\n",
"For those who get the error:\nCaught NoReverseMatch while rend... | [
6,
0
] | [] | [] | [
"django",
"email",
"passwords",
"python",
"reset"
] | stackoverflow_0006939596_django_email_passwords_python_reset.txt |
Q:
Special characters in output are like �
I have some .txt files which included Turkish characters. I prepared a HTML code and wanna include texts which are in my txt files. The processes are successful but the html files which are made by python have character problems(special characters seems like this: �)
I have ... | Special characters in output are like � | I have some .txt files which included Turkish characters. I prepared a HTML code and wanna include texts which are in my txt files. The processes are successful but the html files which are made by python have character problems(special characters seems like this: �)
I have tried add u before strings in python code but... | [
"When you serve the content to a web browser, you need to tell it what encoding the file is in. Ideally, you should send a Content-type: HTTP header in the response with something like text/plain; charset=utf-8, where \"utf-8\" is replaced by whatever encoding you're actually using if it's not utf-8.\nYour browser ... | [
1,
0,
0
] | [] | [] | [
"character",
"encoding",
"python"
] | stackoverflow_0007455371_character_encoding_python.txt |
Q:
Installing with pip breaks on python setup.py egg_info
I'm trying to install my own program via Pip and the PyPI with the usual command pip install tvrenamr however I'm getting the error below:
Downloading/unpacking tvrenamr
Running setup.py egg_info for package tvrenamr
Usage: tvr [options] <file/folder>
... | Installing with pip breaks on python setup.py egg_info | I'm trying to install my own program via Pip and the PyPI with the usual command pip install tvrenamr however I'm getting the error below:
Downloading/unpacking tvrenamr
Running setup.py egg_info for package tvrenamr
Usage: tvr [options] <file/folder>
-c: error: no such option: --egg-base
Complete output... | [
"Unfortunately this was a case of setup tools masking an error in the setup.py that was being caused by a bad version string in tvrenamr/__init__.py.\nI picked up on the error after installing manually with python setup.py install into a clean virtualenv so something in my environment must have been affecting thing... | [
0
] | [] | [] | [
"pip",
"python",
"setuptools"
] | stackoverflow_0007233285_pip_python_setuptools.txt |
Q:
How do I speed up (or break up) this MySQL query?
I'm building a video recommendation site (think pandora for music videos) in python and MySQL. I have three tables in my db:
video - a table of of the videos. Data doesn't change. Columns are:
CREATE TABLE `video` (
id int(11) NOT NULL AUTO_INCREMENT,
we... | How do I speed up (or break up) this MySQL query? | I'm building a video recommendation site (think pandora for music videos) in python and MySQL. I have three tables in my db:
video - a table of of the videos. Data doesn't change. Columns are:
CREATE TABLE `video` (
id int(11) NOT NULL AUTO_INCREMENT,
website_id smallint(3) unsigned DEFAULT '0',
rating_g... | [
"\nChange the field type of the *rating_global* to a numeric type (either float or integer), no need for it to be varchar. Personally I would change all rating fields to integer, I find no need for them to be float.\nDrop the KEY on id, PRIMARY KEY is already indexed.\nvideo.id,rating_global,website_id\nWatch the i... | [
1
] | [] | [] | [
"mysql",
"numpy",
"python"
] | stackoverflow_0007411028_mysql_numpy_python.txt |
Q:
simple string question - the Single quotation marks and Double quotation marks inside the string just make the string into several parts
I need to use a long string for testing regular expression. However, the test string is always altered by the inside quotation marks, which leads to the whole string seperetaed i... | simple string question - the Single quotation marks and Double quotation marks inside the string just make the string into several parts | I need to use a long string for testing regular expression. However, the test string is always altered by the inside quotation marks, which leads to the whole string seperetaed into several parts and some of them are not included into the string, and thus error occurred.
str1=r"row Id="7" PostTypeId="2" ParentId="4... | [
"Use a multiline string:\nstr1 = r\"\"\"row Id=\"7\" PostTypeId=\"2\" ParentId=\"4\"\n CreationDate=\"2008-07-31T22:17:57.883\"\n Score=\"49\" ViewCount=\"0\" Body=\"<p>An explicit cast to double i\"\"\"\n\nAs long as your string doesn't span multiple lines, you can also use an alternative quote... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007455568_python.txt |
Q:
Accessing python containing classes or objects
How to access the calling/outer/container python class within current class when added as a property. Consider this example...
class a():
@staticmethod
def meth():
print 'Who called me?'
class b():
my_a = a
class c():
my_a = a
b.my_a.meth()
... | Accessing python containing classes or objects | How to access the calling/outer/container python class within current class when added as a property. Consider this example...
class a():
@staticmethod
def meth():
print 'Who called me?'
class b():
my_a = a
class c():
my_a = a
b.my_a.meth()
>> Who called me?
c.my_a.meth()
>> Who called me?
... | [
"There's no good way to know how the meth() function was accessed. By the time it is called, it is simply a function. If you use @classmethod instead, you will at least get the class passed to you, but in this case, they are both the same a, so I'm not sure you'll get what you want.\nYou will likely need to do so... | [
0
] | [] | [] | [
"oop",
"python",
"static_methods"
] | stackoverflow_0007455795_oop_python_static_methods.txt |
Q:
Activating link without a browser
I have a webpage where I am a registered user. I need to log in without a browser(username,password) and click a link which adds my name to a list on the webpage. I want this process to work in the background e.g. not show up on the screen at all. I've been trying to use Python to... | Activating link without a browser | I have a webpage where I am a registered user. I need to log in without a browser(username,password) and click a link which adds my name to a list on the webpage. I want this process to work in the background e.g. not show up on the screen at all. I've been trying to use Python to do this e.g.
#!/usr/bin/env python2
#c... | [
"See http://docs.python.org/library/urllib2.html#examples for an example of http authentication. Not sure if this is what you ask for. \n",
"Look at the HTML code of the page with the button. If there is a url/link behind a button you just have to do a GET on this link, eg with urllib2.\nIf there is some javascri... | [
0,
0,
0,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0007453553_python_urllib.txt |
Q:
Executing of Python script
I found Python script for my task, but I don't know how I can execute this script on server with parameter (on my local machine I do it with command line). If this script is by address www.aaa.com/abc.py, then how can I execute it with parameters by browser or else?
A:
You'll want to ... | Executing of Python script | I found Python script for my task, but I don't know how I can execute this script on server with parameter (on my local machine I do it with command line). If this script is by address www.aaa.com/abc.py, then how can I execute it with parameters by browser or else?
| [
"You'll want to run the Python script from a CGI script.\nFirst, create a CGI script, abc.sh like this:\n#!/bin/sh\necho \"HTTP 200 OK\"\necho \"Content-type: text/plain\"\necho \"\"\n./abc.py 2>&1\n\nMake sure to chmod +x abc.sh, and stick both abc.sh and abc.py in your cgi-bin directory.\nThen you should be able ... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0007455898_python.txt |
Q:
Looping Python dictionaries in entered sequence
I am new in Python and while looping through the items of a dictionary structure I discovered that they come up in a different order than the sequence they were entered. That happens in Perl hashes too I think. Is there a simple way to get the items in the "right" or... | Looping Python dictionaries in entered sequence | I am new in Python and while looping through the items of a dictionary structure I discovered that they come up in a different order than the sequence they were entered. That happens in Perl hashes too I think. Is there a simple way to get the items in the "right" order?
| [
"Dictionaries are inherently unordered; it's what gives them (amortized) O(1) lookups for keys. \nIn more recent versions of python, there is collections.OrderedDict which does preserve insertion order. Or, you could just keep a separate list.\n"
] | [
5
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007456300_dictionary_python.txt |
Q:
How to overwrite __getattribute__() in Python
I am trying to modify __getattribute__() method for an instance, as you may already know, __getattirbute__ is read-only attribute in Python (edit: appereantly, for some objects it is, and for others it isn't). What I have in mind is, create a new object like this:
def ... | How to overwrite __getattribute__() in Python | I am trying to modify __getattribute__() method for an instance, as you may already know, __getattirbute__ is read-only attribute in Python (edit: appereantly, for some objects it is, and for others it isn't). What I have in mind is, create a new object like this:
def create_new_instace(old_instance):
class temp(ol... | [
"Actually, yes. Check difference between __getattribute__ and __getattr__ method here\nYou can assign new value to the instance's field __getattribute__ except if __setattr__ explicitly prohibits that. Try this in your python prompt:\n>>>class A(object):\n>>> pass\n>>>A().__getattribute__ = myFunc\n>>>A().__geta... | [
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007455714_python.txt |
Q:
How to return raw html in a Flask app bypassing template transformations
I have just started building my first Flask app, which currently simply returns output of inspect for my objects inside table tags. The problem is that instead of the html I expect, a template engine messes layout up creating new tags (I gues... | How to return raw html in a Flask app bypassing template transformations | I have just started building my first Flask app, which currently simply returns output of inspect for my objects inside table tags. The problem is that instead of the html I expect, a template engine messes layout up creating new tags (I guess it parses dict's curly brackets).
| [
"From your question I don't really understand, why and where this inspect is ran, but it is possible to escape output like this:\n{{ object | e }}\n\nOr you can escape things inside template by using 'foo' or {% raw %}:\n{{ '{{' }}\n\n{% raw %}\n {% %}\n{% endraw %}\n\n"
] | [
4
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0007456154_flask_python.txt |
Q:
Python Flask - login with email address, not username
I want users to login with their email address, not with a username. How easy is it to do that with Flask ? Where can I find an example ?
A:
You can use the Flask's flaskr example (exists in Flask git repo under examples) and rename the username there to emai... | Python Flask - login with email address, not username | I want users to login with their email address, not with a username. How easy is it to do that with Flask ? Where can I find an example ?
| [
"You can use the Flask's flaskr example (exists in Flask git repo under examples) and rename the username there to email.\n"
] | [
2
] | [] | [] | [
"authentication",
"email",
"flask",
"python"
] | stackoverflow_0007455843_authentication_email_flask_python.txt |
Q:
how come I have more threads than processes I asked for my pool in py3k multiprocessing under Linux?
I am trying to parallelize some work, which runs on my mac (Pyton 3.2.2 under Mac OS 10.7) but gives the following error on a Linux cluster I run it where I got 4 cores and access Python 3.2. The error messages con... | how come I have more threads than processes I asked for my pool in py3k multiprocessing under Linux? | I am trying to parallelize some work, which runs on my mac (Pyton 3.2.2 under Mac OS 10.7) but gives the following error on a Linux cluster I run it where I got 4 cores and access Python 3.2. The error messages continue until I break execution manually.
Exception in thread Thread-2:
Traceback (most recent call last):
... | [
"OK, I was \"inadvertently\" trying to cProfile the parallel run on the cluster, while I was simply having test runs offline. The code runs fine, but profiling breaks down -- as it always should for parallel scripts. It is not related to the cluster or LSF. Sorry.\n"
] | [
1
] | [] | [] | [
"linux",
"multiprocessing",
"multithreading",
"python",
"python_3.x"
] | stackoverflow_0007449099_linux_multiprocessing_multithreading_python_python_3.x.txt |
Q:
weird behaviour in twisted defer callback
Aim : To try a TCP connection to a list of server and print if the connection was successful and prompted for password or not
Problem : It seems as if a statement(to_check -= 1) in my callback(named connected) and errback(named failed) never gets executed, even though the... | weird behaviour in twisted defer callback | Aim : To try a TCP connection to a list of server and print if the connection was successful and prompted for password or not
Problem : It seems as if a statement(to_check -= 1) in my callback(named connected) and errback(named failed) never gets executed, even though the print statements in those functions are.
from ... | [
"This is a general issue with your understanding of closures in python; by default, variables are local to the innermost function in which they are assigned. -= is an implicit assignment, so to_check becomes a local variable to connected and failed. As such, the to_check in the main function is never changed. In py... | [
8
] | [] | [] | [
"callback",
"python",
"twisted"
] | stackoverflow_0007456463_callback_python_twisted.txt |
Q:
How could I check if a number is a prime number?
Possible Duplicate:
Simple Prime Generator in Python
First I will prompt user to input any number. Then my code will check whether does the number input by the user is a Prime number not.
Here is my codes:
num = int(raw_input("Input any of the number you like:"))... | How could I check if a number is a prime number? |
Possible Duplicate:
Simple Prime Generator in Python
First I will prompt user to input any number. Then my code will check whether does the number input by the user is a Prime number not.
Here is my codes:
num = int(raw_input("Input any of the number you like:"))
for x in range(2, int(num**0.5)+1):
if num % x =... | [
"import urllib\ntmpl = 'http://www.wolframalpha.com/input/?i=is+%d+a+prime+number'\ndef is_prime(n):\n return ('is a prime number' in urllib.urlopen(tmpl % (n,)).read())\n\n",
"you should stop once num % x == 0 is true (no need for further testing) and print 'it is a prime number' only if the loop completed wi... | [
5,
1,
0,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0007456519_python.txt |
Q:
True privateness in Python
PEP 8 states that (emphasis mine):
We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).
I guess it refers to defining the actual class in some other language and then exposing only the public members to t... | True privateness in Python | PEP 8 states that (emphasis mine):
We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).
I guess it refers to defining the actual class in some other language and then exposing only the public members to the interpreter. Is there some ot... | [
"No, nothing is truly private in Python.\nIf you know the method name, you can get it.\nI think you might come up with a clever hack, but it would be just that - a hack. No such functionality exists in the language.\n",
"(Note: This is not \"private\" in the sense of C++/C#/Java type private, but it's close)\nFor... | [
4,
1,
0
] | [] | [] | [
"private",
"python"
] | stackoverflow_0007456638_private_python.txt |
Q:
Grab Form Data Via Python
I'm looking to grab the form data that needs to be passed along to a specific website and submit it. Below is the html(form only) that I need to simulate. I've been working on this for a few hours, but can't seem to get anything to work. I want this to work in Google App Engine. Any h... | Grab Form Data Via Python | I'm looking to grab the form data that needs to be passed along to a specific website and submit it. Below is the html(form only) that I need to simulate. I've been working on this for a few hours, but can't seem to get anything to work. I want this to work in Google App Engine. Any help would be nice.
<form method... | [
"Is this login page for a 3rd party site? If so, there may be more to it than simply posting the form inputs.\nFor example, I just tried this with the login page on one of my own sites. A simple post request won't work in my case, and this may be the same with the login page you are accessing as well. \nFor starter... | [
2,
1
] | [] | [] | [
"cgi",
"python",
"urllib"
] | stackoverflow_0007456408_cgi_python_urllib.txt |
Q:
Calling C functions from python code. Dll not working
I wrote below dll called djj.dll it has a file called try.cpp with following code
#include<stdio.h>
int print(){
return 4;
}
Now, i build this dll and go to python idle.
I type print windll.djj.print . It gives syntax error .WHY??
A:
As Aaron Gallag... | Calling C functions from python code. Dll not working | I wrote below dll called djj.dll it has a file called try.cpp with following code
#include<stdio.h>
int print(){
return 4;
}
Now, i build this dll and go to python idle.
I type print windll.djj.print . It gives syntax error .WHY??
| [
"As Aaron Gallagher said, print is a Python keyword. Also it's unusual for a compiled DLL to use the standard Windows calling convention (i.e. windll). It's more likely to use cdecl (i.e. cdll). Here's an approach that should work:\ndjj = ctypes.cdll.LoadLibrary('djj.dll')\nmy_print = getattr(djj, 'print')\nx = my_... | [
1,
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0007456102_c_python.txt |
Q:
Porting a Python JSON API to Java (GWT)
I am trying to port this bit of Python code to Java http://www.bemasher.net/archives/1002 (scroll down to the bottom for the code)
But because everything is dynamically typed, I'm having difficulty porting this. I need to be able to use a Java implementation of Pythons json... | Porting a Python JSON API to Java (GWT) | I am trying to port this bit of Python code to Java http://www.bemasher.net/archives/1002 (scroll down to the bottom for the code)
But because everything is dynamically typed, I'm having difficulty porting this. I need to be able to use a Java implementation of Pythons json. Right now I'm using gson ( http://code.goog... | [
"It basically fetches http://www.ows.newegg.com/Stores.egg/Menus and dumps its contents to a string (response), then it parses the JSON using json.loads() and puts that into data.\nThen it will iterate through the contents of data and build a HTML list using lxml. The list itself should look like:\n<ul>\n <li><a h... | [
3,
0
] | [] | [] | [
"gson",
"gwt",
"java",
"porting",
"python"
] | stackoverflow_0007450506_gson_gwt_java_porting_python.txt |
Q:
python.exe file missing?
Okay, so about 6 months ago a guy built a program for my company using python. The program ran fine, but now all of a sudden, it doesn't work. The error message says it can't find python/python.exe. I'm just trying to figure out if this is a file that came with the python installation, or ... | python.exe file missing? | Okay, so about 6 months ago a guy built a program for my company using python. The program ran fine, but now all of a sudden, it doesn't work. The error message says it can't find python/python.exe. I'm just trying to figure out if this is a file that came with the python installation, or if this is something that was ... | [
"Python.exe is a compiler-cum-interpreter file that comes with Python Implementation Package. It runs the code written using the python language. You can't run python code until this is installed on your system. I suggest you go and download Python implementation from HERE for your OS and then try running the progr... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007457171_python.txt |
Q:
How to write mathematic formula in python
I try to write these formulas in python but with no luck
I have no errors in code but I know that calculation gives incorrect result so I guess I have something wrong in implementation of formulas.
import math
lat = 54.5917455423
lon = 17.2078876198
B = math.ra... | How to write mathematic formula in python | I try to write these formulas in python but with no luck
I have no errors in code but I know that calculation gives incorrect result so I guess I have something wrong in implementation of formulas.
import math
lat = 54.5917455423
lon = 17.2078876198
B = math.radians(lat)
L = math.radians(lon)
h = 55.889
pi ... | [
"This isn't Python:\nb/a = 1 - f\n\n",
"This formula has errors in it:\ndB = (-dX*sin(B)*cos(L) - dY*sin(L) + dZ*cos(B) \n + Da*(Rn * e**2*sin(B)*cos(B)/a+Df)*(Rm*(a/b)+Rn*ba)*sin(B)*cos(B))*vc**-1\n\nIt should be:\ndB = ( -dX*sin(B)*cos(L) - dY*sin(B)*sin(L) + dZ*cos(B)\n + Da*(Rn * e**2*sin(B)*cos(B)... | [
8,
3
] | [] | [] | [
"math",
"python"
] | stackoverflow_0007457013_math_python.txt |
Q:
Qt programming: More productive in Python or C++?
Trying to dive into Qt big time but haven't done a large project with it yet. Currently using Python, but I've been thinking -- which is really the better language to use in terms of programmer productivity?
In most comparisons between the languages, Python is the ... | Qt programming: More productive in Python or C++? | Trying to dive into Qt big time but haven't done a large project with it yet. Currently using Python, but I've been thinking -- which is really the better language to use in terms of programmer productivity?
In most comparisons between the languages, Python is the obvious answer, because you don't have to mess with mem... | [
"If one or the other, I'd actually suggest Python in spite of being a C++ enthusiast. With Python code you don't have to bother with the MOC, portability, build times, etc. Just compare the work involved in implementing a QT slot in C++ vs. PyQT or PySide, e.g. I find it to be much less of a pain to deal with widge... | [
33,
31,
11,
7,
3
] | [] | [] | [
"c++",
"pyqt",
"python",
"qt"
] | stackoverflow_0003139414_c++_pyqt_python_qt.txt |
Q:
Adding radio buttons to customised form in web2py
I'm trying to display a field as a radio button group in a customised form. I want to place each radio button on a different row in a table. The problem is when I use {{=form.custom.selection_type[0]}}, the widget is wrapped in unwanted tr and td tags. Is there ... | Adding radio buttons to customised form in web2py | I'm trying to display a field as a radio button group in a customised form. I want to place each radio button on a different row in a table. The problem is when I use {{=form.custom.selection_type[0]}}, the widget is wrapped in unwanted tr and td tags. Is there a way to add only the radio button?
My form:
{{extend '... | [
"It's not in stable yet, but in trunk, you can now specify ul or divs style rather than table style for the radio widget. I think it would be:\ndb.payment_bpay_step1.selection_type.widget = \\\n lambda f, v: SQLFORM.widgets.radio.widget(f, v, style='divs')\n\nYou can also create a custom widget, as described at ... | [
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0007456050_python_web2py.txt |
Q:
Drag window handle for Tkinter?
First of all, this is my current code, essential parts of it:
class WindowDraggable():
x = 1
y = 1
def __init__(self,label):
label.bind('<ButtonPress-1>',self.StartMove);
label.bind('<ButtonRelease-1>',self.StopMove);
label.bind('<B1-Motio... | Drag window handle for Tkinter? | First of all, this is my current code, essential parts of it:
class WindowDraggable():
x = 1
y = 1
def __init__(self,label):
label.bind('<ButtonPress-1>',self.StartMove);
label.bind('<ButtonRelease-1>',self.StopMove);
label.bind('<B1-Motion>',self.OnMotion);
def StartMov... | [
"Here's a little example:\nfrom Tkinter import *\nroot = Tk()\n\nclass WindowDraggable():\n\n def __init__(self, label):\n self.label = label\n label.bind('<ButtonPress-1>', self.StartMove)\n label.bind('<ButtonRelease-1>', self.StopMove)\n label.bind('<B1-Motion>', self.OnMotion)\n\n... | [
2
] | [] | [] | [
"drag_and_drop",
"python",
"python_2.7",
"tkinter"
] | stackoverflow_0007455573_drag_and_drop_python_python_2.7_tkinter.txt |
Q:
What would be considered the better naming style here?
I'm writing an extension for Tkinter, and conflicted on which naming style I should use for some new attributes I'm going to add.
This is the first naming style, giving all the new attributes the prefix sw_.
import Tkinter as tk
class New (tk.Button, object) ... | What would be considered the better naming style here? | I'm writing an extension for Tkinter, and conflicted on which naming style I should use for some new attributes I'm going to add.
This is the first naming style, giving all the new attributes the prefix sw_.
import Tkinter as tk
class New (tk.Button, object) :
def __init__ (self, par) :
tk.Button.__init__(... | [
"Python's style guide is the thing to follow - do the most readable, sensible thing. That said, it does suggest that you follow any project styles over the official Python styles, but to use Python styles when doing something new.\nPython already has name-spacing as a feature of the language (with imports), so pref... | [
3,
1,
0
] | [] | [] | [
"attributes",
"class",
"namespaces",
"naming_conventions",
"python"
] | stackoverflow_0007457377_attributes_class_namespaces_naming_conventions_python.txt |
Q:
Python4Delphi-powered program, how to deploy it?
My Delphi program uses Python4Delphi, and the Python script uses some standard libs. When deploying my program I don't want an entire Python installation, and it must work with python27.dll. What are the minimal set of necessary files? The document in Python4Delphi ... | Python4Delphi-powered program, how to deploy it? | My Delphi program uses Python4Delphi, and the Python script uses some standard libs. When deploying my program I don't want an entire Python installation, and it must work with python27.dll. What are the minimal set of necessary files? The document in Python4Delphi is dated and it's not clear to me...
Thanks for your h... | [
"When I did this, I made the list myself, of what I needed for my embedded python application to work. \nI remember this worked with python15.dll:\n\nPythonXX.dll should work, without any other external files other than the Visual C++ Runtime DLLs, which require a side-by-side manifest (see the p4d wiki page) to w... | [
1
] | [] | [] | [
"delphi",
"python",
"python4delphi"
] | stackoverflow_0007446637_delphi_python_python4delphi.txt |
Q:
Host to network byteorder conversion for float in Python
I have this code and I want to do host to network for the float values (t & u)
#! /usr/bin/env python
import socket
import sys, struct
x = int(sys.argv[1])
y = int(sys.argv[2])
z = socket.htons(int(sys.argv[3]))
t = float(sys.argv[4]) # I want to do (soc... | Host to network byteorder conversion for float in Python | I have this code and I want to do host to network for the float values (t & u)
#! /usr/bin/env python
import socket
import sys, struct
x = int(sys.argv[1])
y = int(sys.argv[2])
z = socket.htons(int(sys.argv[3]))
t = float(sys.argv[4]) # I want to do (socket.htonf) or something similar but only (htonl) is there
u = ... | [
"The struct module supports byte order specifiers in the format string: http://docs.python.org/library/struct.html#byte-order-size-and-alignment\n"
] | [
2
] | [] | [] | [
"endianness",
"floating_point",
"python"
] | stackoverflow_0007457954_endianness_floating_point_python.txt |
Q:
Scipy: bounds for fitting parameter(s) when using optimize.leastsq
I am using optimize.leastsq to fit data. I would like to constrain the fitting parameter(s) to a certain range. Is it possible to define bounds when using optimize.leastsq? Bounds are implemented in optimize.fmin_slsqp, but I'd prefer to use optimi... | Scipy: bounds for fitting parameter(s) when using optimize.leastsq | I am using optimize.leastsq to fit data. I would like to constrain the fitting parameter(s) to a certain range. Is it possible to define bounds when using optimize.leastsq? Bounds are implemented in optimize.fmin_slsqp, but I'd prefer to use optimize.leastsq.
| [
"I think the standard way of handling bounds is by making the function to be minimized (the residuals) very large whenever the parameters exceed the bounds.\nimport scipy.optimize as optimize\ndef residuals(p,x,y):\n if within_bounds(p):\n return y - model(p,x)\n else:\n return 1e6\n\np,cov,info... | [
6,
3,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0007409694_python_scipy.txt |
Q:
Summing Only First Values When in Dictionary When Keys Correspond To Lists (Python)
I'm working in python 2.7. I have a list of teams in the following dictionary:
NL = {'Phillies': [662, 476], 'Braves': [610, 550], 'Mets': [656, 687]}
The first value in the list is the amount of runs scored the team has, and the ... | Summing Only First Values When in Dictionary When Keys Correspond To Lists (Python) | I'm working in python 2.7. I have a list of teams in the following dictionary:
NL = {'Phillies': [662, 476], 'Braves': [610, 550], 'Mets': [656, 687]}
The first value in the list is the amount of runs scored the team has, and the second is the amount of runs that team has given up.
I'm using this code to determine the... | [
"If you want to have the running total available, or don't want to iterate over league twice, you can do:\ndef Pythag(league):\n total_runs_scored = 0\n for team, scores in league.iteritems():\n # other stuff\n total_runs_scored += scores[0]\n # other stuff\n # runs scored by all t... | [
3
] | [] | [] | [
"dictionary",
"list",
"python",
"sum"
] | stackoverflow_0007458249_dictionary_list_python_sum.txt |
Q:
Python: Spawn sudo process (in new terminal), wait until completed
Edit: my final code goes something like this:
#WARNING: all " in command need to be escaped: \\"
def spawnInNewTerminal(command):
#creates lock file
lock = open(lockPath, 'w')
lock.write("Currently performing task in separate terminal."... | Python: Spawn sudo process (in new terminal), wait until completed | Edit: my final code goes something like this:
#WARNING: all " in command need to be escaped: \\"
def spawnInNewTerminal(command):
#creates lock file
lock = open(lockPath, 'w')
lock.write("Currently performing task in separate terminal.")
lock.close()
#adds line to command to remove lock file
co... | [
"The reason is that x-terminal-emulator spawns a new process and exits, so you can't know when the executed command actually finishes. To work around that, a solution would be to modify your command to add another command that notifies you. Since apparently x-terminal-emulator only ever executes one command, we can... | [
3
] | [] | [] | [
"python",
"spawn",
"sudo",
"terminal"
] | stackoverflow_0007458326_python_spawn_sudo_terminal.txt |
Q:
Find where dependencies are coming from in Python?
When I run pip install . I get all dependencies installed, including transitive dependencies, but the problem is that there are two modules that depend on two different versions of lxml. How can I figure out who is requiring what with pip or any other tool?
A:
... | Find where dependencies are coming from in Python? | When I run pip install . I get all dependencies installed, including transitive dependencies, but the problem is that there are two modules that depend on two different versions of lxml. How can I figure out who is requiring what with pip or any other tool?
| [
"Do you have an idea of which modules depend on lxml? If so, you could simply check those modules setup.py files and check install_requires, and most package creators will include the version number as well. e.g.\n install_requires=[\n 'django-modeldict>=1.1.6',\n 'nexus>=0.1.7',\n 'django-jsonfield',\n ... | [
1
] | [] | [] | [
"dependencies",
"pip",
"python",
"setuptools"
] | stackoverflow_0007421404_dependencies_pip_python_setuptools.txt |
Q:
Cannot install MySQL-Python
for some reason I'm unable to install the MySQL-Python package in neither my virtualenv nor in my main Python install on OS X. I'm getting the following output:
Downloading/unpacking MySQL-Python
Running setup.py egg_info for package MySQL-Python
warning: no files found matc... | Cannot install MySQL-Python | for some reason I'm unable to install the MySQL-Python package in neither my virtualenv nor in my main Python install on OS X. I'm getting the following output:
Downloading/unpacking MySQL-Python
Running setup.py egg_info for package MySQL-Python
warning: no files found matching 'MANIFEST'
warning: no f... | [
"It seems you have installed MySQL 5.5.10 and Python 2.6.\nCurrent version of MySQL-python (version 1.2.3) is supported from MySQL-3.23 through 5.0.\nHowever you can try installing it via ActivePython.\nIf you install ActivePython to the default path, open terminal and run:\n/opt/ActivePython-2.6/bin/pypm install m... | [
3,
0
] | [] | [] | [
"installation",
"mysql",
"python"
] | stackoverflow_0006216009_installation_mysql_python.txt |
Q:
Best / most pythonic way to get an ordered list of unique items
I have one or more unordered sequences of (immutable, hashable) objects with possible duplicates and I want to get a sorted sequence of all those objects without duplicates.
Right now I'm using a set to quickly gather all the elements discarding dupli... | Best / most pythonic way to get an ordered list of unique items | I have one or more unordered sequences of (immutable, hashable) objects with possible duplicates and I want to get a sorted sequence of all those objects without duplicates.
Right now I'm using a set to quickly gather all the elements discarding duplicates, convert it to a list and then sort that:
result = set()
for s ... | [
"This should work:\nsorted(set(itertools.chain.from_iterable(sequences)))\n\n",
"I like your code just fine. It is straightforward and easy to understand.\nWe can shorten it just a little bit by chaining off the list():\nresult = set()\nfor s in sequences:\n result = result.union(s)\nreturn sorted(result)\n\n... | [
13,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007458689_list_python.txt |
Q:
How do I add search parameters to search page url?
I want to change the search results url from /searchhandler to /searchhandler?search_string=[search string] so that I can redirect to that search results page. How do I do this?
This is the search form in Search:
self.response.out.write("""
<form name="search_form... | How do I add search parameters to search page url? | I want to change the search results url from /searchhandler to /searchhandler?search_string=[search string] so that I can redirect to that search results page. How do I do this?
This is the search form in Search:
self.response.out.write("""
<form name="search_form" action="/searchhandler" method="post"><br />
<input ty... | [
"Is the \"tag_list\" property a list of strings? I'm gonna assume you are trying to search for tags? I would use a comma delimited list for input, instead of space delimited. \nAlso not sure what f1 is\nTry this:\nself.response.out.write(\"\"\"\n<form name=\"search_form\" action=\"/searchhandler\" method=\"GET\">... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0007456670_google_app_engine_python.txt |
Q:
a small question about python socket
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("XXXXX",23))
line = s.recv(10000)
I wonder how to show what is in the "line". I've tried print ,but what it shows is different
from what I see in python shell.
A:
Try print repr(line)... See examp... | a small question about python socket | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("XXXXX",23))
line = s.recv(10000)
I wonder how to show what is in the "line". I've tried print ,but what it shows is different
from what I see in python shell.
| [
"Try print repr(line)... See example in http://docs.python.org/library/socket.html.\n"
] | [
0
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0007458963_python_sockets.txt |
Q:
How to search for a particular string with in a regex group with in a single regex in Python?
I am trying to match the word 'noun' with in the last group of my regex.
So far I have:
tags = 'motocykl mutka 1 motorcycle bike moped 0 transportation openair noun'
print re.search('(?P<pol>\D+)(?P<d1>\d)(?P<eng>\D+)(?P... | How to search for a particular string with in a regex group with in a single regex in Python? | I am trying to match the word 'noun' with in the last group of my regex.
So far I have:
tags = 'motocykl mutka 1 motorcycle bike moped 0 transportation openair noun'
print re.search('(?P<pol>\D+)(?P<d1>\d)(?P<eng>\D+)(?P<d2>\d)(?P<end>\D+)', tags).group('end')
All I get is a string which is that last group:
transport... | [
"Not sure what your tags mean but \\D+? should match \"transportation openair\" and the [a-zA-Z] will match the last word (noun):\n^(?P<pol>\\D+)(?P<d1>\\d)(?P<eng>\\D+)(?P<d2>\\d)\\D+?(?P<end>[a-zA-Z]+)$\n",
"Your problem is that you are matching with \\D+, which will match multiple words including spaces. It m... | [
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007458669_python_regex.txt |
Q:
How to replace just one whitespace with regex in python?
for example:
T h e t e x t i s w h a t I w a n t t o r e p l a c e
I want the result like this:
The text is what I want to replace
I tried that with shell, sed,
echo 'T h e t e x t i s W h a t I w a n t r e p l a c e'|sed -r "s/... | How to replace just one whitespace with regex in python? | for example:
T h e t e x t i s w h a t I w a n t t o r e p l a c e
I want the result like this:
The text is what I want to replace
I tried that with shell, sed,
echo 'T h e t e x t i s W h a t I w a n t r e p l a c e'|sed -r "s/(([a-zA-Z])\s){1}/\2/g"|sed 's/\ / /g'
it's successfully.
bu... | [
"If you just want to convert a string that has whitespace between each chars:\n>>> import re\n>>> re.sub(r'(.) ', r'\\1', 'T h e t e x t i s w h a t I w a n t t o r e p l a c e')\n'The text is what I want to replace'\n\nOr, if you want to remove all single whitespace and replace whitespaces to just one... | [
5,
3,
1
] | [] | [] | [
"python",
"regex",
"removing_whitespace",
"replace"
] | stackoverflow_0007440175_python_regex_removing_whitespace_replace.txt |
Q:
Cast string to first element of a new list in function call
I'm looking for the Python way to take a string and pass it to a function as a list, like so:
word = 'abc'
result = crazyfunction(cast(word,[]))
so that crazyfunction will receive a list like this:
word[0] = 'abc'
instead of a string.
The goal is to cas... | Cast string to first element of a new list in function call | I'm looking for the Python way to take a string and pass it to a function as a list, like so:
word = 'abc'
result = crazyfunction(cast(word,[]))
so that crazyfunction will receive a list like this:
word[0] = 'abc'
instead of a string.
The goal is to cast in the function parameter, instead of having to do an assignmen... | [
"From your example, it looks like it would be as simple as building a list. Just call the function like this: crazyfunction(['abc'])\nEDIT: Just tested it in the console:\n>>> def printfirst(lst):\n... print lst[0]\n...\n>>> printfirst('hello')\nh\n>>> printfirst(['hello'])\nhello\n\n"
] | [
1
] | [] | [] | [
"casting",
"list",
"python",
"string"
] | stackoverflow_0007459125_casting_list_python_string.txt |
Q:
When crawling a page, how to get full URL from or attributes
I am actually using PHP but such crawling can be done by any programming languages. It will be a bit difficult to cater a lot of situations. Please help me look through the problem, and please give me some suggestion on whether I am going to the right ... | When crawling a page, how to get full URL from or attributes | I am actually using PHP but such crawling can be done by any programming languages. It will be a bit difficult to cater a lot of situations. Please help me look through the problem, and please give me some suggestion on whether I am going to the right direction.
What I know is the current url address from which I can g... | [
"Anything after the domain name can map to whatever the person configuring the domain wants.\nThere is no guarantee that a URL ending in .html refers to a real file on a filesystem somewhere, or that it will return valid HTML, or anything else.\nYou can arbitrarily decide to count def/ as a directory or part of a f... | [
3,
2
] | [] | [] | [
"php",
"python",
"web_crawler"
] | stackoverflow_0007459106_php_python_web_crawler.txt |
Q:
How could i repeatedly send messages through server socket in python?
Like the title, i would like to know how to send messages repeatedly.
Is it as simple as using a "while" function?
What I'm trying to do is, when ever a client joins. I would like to have the server end, constantly send the data to the client.... | How could i repeatedly send messages through server socket in python? | Like the title, i would like to know how to send messages repeatedly.
Is it as simple as using a "while" function?
What I'm trying to do is, when ever a client joins. I would like to have the server end, constantly send the data to the client. And if possible a way to adjust how soon i want the next message sent out.... | [
"Read about the SocketServer module, in particular the ThreadingMixIn to allow you to handle multiple clients simultaneously. It is a Python library, and the SocketServer.py source file can be read to see how it is implemented.\n",
"\nimport socket, using socket.socket If that helps any. I figured out how to rep... | [
0,
0
] | [] | [] | [
"message",
"python",
"sockets",
"udp"
] | stackoverflow_0007458893_message_python_sockets_udp.txt |
Q:
Reading Elements by attribute Condition lxml
Using lxml libarary how can I read element value if an attribute is given.
For example if "qtn" state=2 then return value required is "Doctor Checkup"
Thanks. If possible please also give me any tutorial/url for the same
<?xml version="1.0" encoding="UTF-8"?>
<elements>... | Reading Elements by attribute Condition lxml | Using lxml libarary how can I read element value if an attribute is given.
For example if "qtn" state=2 then return value required is "Doctor Checkup"
Thanks. If possible please also give me any tutorial/url for the same
<?xml version="1.0" encoding="UTF-8"?>
<elements>
<qtn state="1">I have severe chest pain
<an s... | [
"I got my answer\nfrom lxml import etree\nxml = etree.parse(open('1.xml'))\nxml.xpath(\"//qtn[@state=\"+state+\"]/text()\")\n\n"
] | [
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0007459354_lxml_python.txt |
Q:
Deleting array elements in python
All, I want to delete specific array elements of one array from the other. Here is an example. The arrays are a long list of words though.
A = ['at','in','the']
B = ['verification','at','done','on','theresa']
I would like to delete words that appear in A from B.
B = ['verificatio... | Deleting array elements in python | All, I want to delete specific array elements of one array from the other. Here is an example. The arrays are a long list of words though.
A = ['at','in','the']
B = ['verification','at','done','on','theresa']
I would like to delete words that appear in A from B.
B = ['verification','done','theresa']
Here is what I tr... | [
"Using a list comprehension to get the full answer:\n[x for x in B if x not in A]\n\nHowever, you may want to know more about replace, so ...\npython list has no replace method. If you just want to remove an element from a list, set the relevant slice to be an empty list. For example:\n>>> print B\n['verification... | [
3,
3,
1
] | [] | [] | [
"arrays",
"elements",
"python"
] | stackoverflow_0007459246_arrays_elements_python.txt |
Q:
"ImportError: DLL load failed" when trying to run Play framework for the first time
Thinking I'd jump right into this without any issues, I was surprised that I can't even get the framework to initialize. Below is the error I am getting.
C:\>play
Traceback (most recent call last):
File "C:\Play\play-1.2.1\play"... | "ImportError: DLL load failed" when trying to run Play framework for the first time | Thinking I'd jump right into this without any issues, I was surprised that I can't even get the framework to initialize. Below is the error I am getting.
C:\>play
Traceback (most recent call last):
File "C:\Play\play-1.2.1\play", line 13, in <module>
from play.application import PlayApplication
File "C:\Play\p... | [
"C:\\csvn\\Python25\\lib\\socket.py ? Looks like you're using a preinstalled Python 2.5 instead of the bundled Python 2.6... Do you have Python-related environment settings?\n",
"you could have just set PYTHON_HOME environment variable to point to play's python\n"
] | [
1,
0
] | [] | [] | [
"playframework",
"python"
] | stackoverflow_0006521828_playframework_python.txt |
Q:
Subtracting by Dictionary Values from Iterated Total in For Loop Python
Working in Python 2.7.
I have a dictionary with team names as the keys and the values are contained in lists. The first value is the amount of runs the team scored, the second is runs allowed:
NL = {'Phillies': [662, 476], 'Braves': [610, 550]... | Subtracting by Dictionary Values from Iterated Total in For Loop Python | Working in Python 2.7.
I have a dictionary with team names as the keys and the values are contained in lists. The first value is the amount of runs the team scored, the second is runs allowed:
NL = {'Phillies': [662, 476], 'Braves': [610, 550], 'Mets': [656, 687]}
I have a function that iterates over each key and prov... | [
"If you want the team_removed_runs for every team in the dictionary, you'll need to go back through the dictionary and compute the total number of runs minus the runs for each team. Something like\nteam_removed_runs = {}\nfor team, scores in league.iteritems():\n team_removed_runs[team] = [total_runs_scored - s... | [
6
] | [] | [] | [
"dictionary",
"iteration",
"list",
"python",
"subtraction"
] | stackoverflow_0007459588_dictionary_iteration_list_python_subtraction.txt |
Q:
Python error when retrieving a url from a database and opening it with webbrowser()
I am trying to make an app similar to StumbleUpon using Python as a back end for a personal project . From the database I retrieve a website name and then I open that website with webbrowser.open("http://www.website.com"). Sounds p... | Python error when retrieving a url from a database and opening it with webbrowser() | I am trying to make an app similar to StumbleUpon using Python as a back end for a personal project . From the database I retrieve a website name and then I open that website with webbrowser.open("http://www.website.com"). Sounds pretty straight forward right but there is a problem. When I try to open the website with ... | [
"webbrowser.open is expecting a character buffer, but fetchmany returns a list. So webbrowser.open(x[0]) should do the trick.\n"
] | [
1
] | [] | [] | [
"python",
"sqlite",
"web"
] | stackoverflow_0007459740_python_sqlite_web.txt |
Q:
Hiding API key in code (Python)
I am using an API key in some Python code which I am looking to distribute. This API key is for Google Maps. Are there any security issues with regards to distributing this API key and if so, how is it best to hide this?
A:
It isn't necessary, the Google API key is tied to your do... | Hiding API key in code (Python) | I am using an API key in some Python code which I am looking to distribute. This API key is for Google Maps. Are there any security issues with regards to distributing this API key and if so, how is it best to hide this?
| [
"It isn't necessary, the Google API key is tied to your domain so the referrer is checked when it is used.\nYou can read more about how it works here\nRelevant part\n\nNote that a key for http://www.mygooglemapssite.com/ will only be accepted when the site is accessed using this address. It will not be accepted if ... | [
5,
1,
0,
0,
0
] | [] | [] | [
"api",
"google_maps",
"google_maps_api_3",
"python"
] | stackoverflow_0007458227_api_google_maps_google_maps_api_3_python.txt |
Q:
Difficulty Importing GASP Using Script
Using interpreter mode, from gasp import * runs, but when I place it in a script it doesn't. I'm copying this straight from chapter 4 of How to Think Like a Computer Scientist: Learning with Python (under heading 4.11. GASP).
Script:
from gasp import *
begin_graphics()
Circ... | Difficulty Importing GASP Using Script | Using interpreter mode, from gasp import * runs, but when I place it in a script it doesn't. I'm copying this straight from chapter 4 of How to Think Like a Computer Scientist: Learning with Python (under heading 4.11. GASP).
Script:
from gasp import *
begin_graphics()
Circle((200, 200), 60)
Line((100, 400), (580, 20... | [
"Rename your script. You're hiding the real gasp module:\nben@ubuntu:~$ python '/home/ben/Documents/Python/gasp.py' \n\nWhen you\nfrom gasp import *\n\nit's trying to import itself because you called it gasp.py.\n",
"\nRenaming the script does not solve the problem.\nben@ubuntu:~$ python '/home/ben/Documents/Pyth... | [
1,
0
] | [] | [] | [
"gasp",
"python"
] | stackoverflow_0007452508_gasp_python.txt |
Q:
Rendering Admin Forms When An Error Occurs in Django
I have a model that contains a field with a foreign key and this field can be NULL and is optional. I can save this form in admin page without any problems if this field has no values. However, when there's an error on my form, my form cannot be rendered and Dja... | Rendering Admin Forms When An Error Occurs in Django | I have a model that contains a field with a foreign key and this field can be NULL and is optional. I can save this form in admin page without any problems if this field has no values. However, when there's an error on my form, my form cannot be rendered and Django returns the following error:
Caught ValueError while r... | [
"@GeoffroyCALA is right, you need condition to raise an exception. If you do not check the condition, exception will be raised anyway. Moreover, you do not specify a form field for which you set the custom exception. See the docs example.\nTry something like that:\ndef clean(self):\n \"\"\"Custom port range vali... | [
0
] | [] | [] | [
"django",
"foreign_keys",
"forms",
"python",
"render"
] | stackoverflow_0006378271_django_foreign_keys_forms_python_render.txt |
Q:
XML parsing python
<dict>
<key>1208</key>
<dict>
<key>Track ID</key><integer>1208</integer>
<key>Name</key><string>Kings And Queens</string>
<key>Artist</key><string>30 Seconds To Mars</string>
<key>Album Artist</key><string>30 Seconds to Mars</string>
... | XML parsing python | <dict>
<key>1208</key>
<dict>
<key>Track ID</key><integer>1208</integer>
<key>Name</key><string>Kings And Queens</string>
<key>Artist</key><string>30 Seconds To Mars</string>
<key>Album Artist</key><string>30 Seconds to Mars</string>
<key>Composer</key... | [
"How about:\nimport xml.dom.minidom as minidom\ndom = minidom.parse('test.xml')\ndata={}\nfor dct in dom.getElementsByTagName('dict'):\n keys=dct.getElementsByTagName('key')\n # key.nextSibling can be an integer or string or date element, or Text node\n # key.nextSibling.firstChild is a Text node or None\n... | [
3
] | [] | [] | [
"python",
"xml",
"xml_parsing"
] | stackoverflow_0007459970_python_xml_xml_parsing.txt |
Q:
Python: Parse Text File
My file looks like this:
A matrix of 2 by 100 ,
I would like to create a list for each column one list which correspond to the first element of each row mapping to current and the second element maps to the temperature.
As shown below. any better way to make the code look fancier?
-12,30
... | Python: Parse Text File | My file looks like this:
A matrix of 2 by 100 ,
I would like to create a list for each column one list which correspond to the first element of each row mapping to current and the second element maps to the temperature.
As shown below. any better way to make the code look fancier?
-12,30
-34,50
-33,89
-900,9
-2,37
-7... | [
"To avoid doing the split call twice for every line, I'd suggest the following solution\ndef parse_log(fname):\n with open(fname) as f:\n samples = [line.strip() for line in f.readlines()\n if not line.startswith('*')]\n ints = [map(int, line.split(\",\")) for line in samples]\n ... | [
1,
1,
0
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0007459250_parsing_python.txt |
Q:
re-import module-under-test to lose context
Many Python modules preserve an internal state without defining classes, e.g. logging maintains several loggers accessible via getLogger().
How do you test such a module? Using the standard unittest tools, I would like the various tests inside a TestCase class to re-impo... | re-import module-under-test to lose context | Many Python modules preserve an internal state without defining classes, e.g. logging maintains several loggers accessible via getLogger().
How do you test such a module? Using the standard unittest tools, I would like the various tests inside a TestCase class to re-import my module-under-test so that each time it lose... | [
"import unittest\nimport sys\n\nclass Test(unittest.TestCase):\n def tearDown(self):\n try:\n del sys.modules['logging']\n except KeyError:\n pass\n def test_logging(self):\n import logging\n logging.foo=1\n def test_logging2(self):\n import logging\... | [
14,
10
] | [] | [] | [
"import",
"python",
"python_module",
"unit_testing"
] | stackoverflow_0007460363_import_python_python_module_unit_testing.txt |
Q:
Django translation and py2exe
I have just compiled my django application to an exe using py2exe. But I don't have any idea how to make django translation work (I mean built in translation, not my own translation files).
There is LANGUAGE_CODE set in my settings file, I also tried importing django.utils.translation... | Django translation and py2exe |
I have just compiled my django application to an exe using py2exe. But I don't have any idea how to make django translation work (I mean built in translation, not my own translation files).
There is LANGUAGE_CODE set in my settings file, I also tried importing django.utils.translation and django.conf.locale.pl in py2e... | [
"Finally solved! And in so easy way..\nAs https://docs.djangoproject.com/en/dev/topics/i18n/deployment/ says we can put locale files into different localizations. So I copy all locale files from django/conf to my template folder.\nThis line of my py2exe setup.py copy it to my compilation with templates:\npy2exe_dat... | [
1
] | [] | [] | [
"django",
"py2exe",
"python",
"translation"
] | stackoverflow_0007458487_django_py2exe_python_translation.txt |
Q:
Getting a list value from key/value pair
If I have a list with key/value pair, how do I get the value of the key?
I'm working with this code snippet:
>>> items = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status',
'pending'), ('timeout','120')]}
>>> print [items[i] for i in items.keys()]
[[('stat... | Getting a list value from key/value pair | If I have a list with key/value pair, how do I get the value of the key?
I'm working with this code snippet:
>>> items = {'fees':[('status','pending'), ('timeout',60)], 'hostel':[('status',
'pending'), ('timeout','120')]}
>>> print [items[i] for i in items.keys()]
[[('status', 'pending'), ('timeout', '120')], [('statu... | [
"I’m not sure I understand your question completely, but the easy solution is probably:\n>>> dict(items['fees'])['status']\n'pending'\n\n",
"You're already printing the values in your \"print\" statement, so I assume you just want to print the name of the keys.\nThis modification of your print statement will prin... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007460675_python.txt |
Q:
Perform Numpy operation on matrix of user-defined type items
In my cryptography project, I have to deal with GF(2^8) arithmetic operations. Essentially, the sum operation in this this field (GF(2^8) is normal XOR operation, and the product operation a*b is (a*b) mod m(x). You can skip this mathematics part.
My job... | Perform Numpy operation on matrix of user-defined type items | In my cryptography project, I have to deal with GF(2^8) arithmetic operations. Essentially, the sum operation in this this field (GF(2^8) is normal XOR operation, and the product operation a*b is (a*b) mod m(x). You can skip this mathematics part.
My job is to inverse a matrix 4x4 in GF(2^8). This is not difficult, but... | [
"Declare a to be of dtype object:\na = np.array([(GF28(10), GF28(20), GF28(30)),\n (GF28(12), GF28(21), GF28(4)),\n (GF28(9), GF28(16), GF28(13))],dtype='object')\n\nThen the type of the elements in the array are GF28. For example:\ntype(a[0,0])\n# <class '__main__.GF28'>\n\n"
] | [
2
] | [] | [] | [
"cryptography",
"numpy",
"python"
] | stackoverflow_0007460672_cryptography_numpy_python.txt |
Q:
QWebView - dealing with javascript infinite loop
web_view_crash.py
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
view = QWebView()
view.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
view.load(QUrl('infinite_loop.html'))
v... | QWebView - dealing with javascript infinite loop | web_view_crash.py
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
app = QApplication(sys.argv)
view = QWebView()
view.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
view.load(QUrl('infinite_loop.html'))
view.show()
app.exec_()
infinite_loop.html
<script>
... | [
"sip.delete(page) will kill the page object, stopping the execution, then all you have to do after that is delete the reference to the page in Python: del page\nYou might also want to check out subclassing WebPage and re-implementing shouldInterruptJavaScript(), perhaps killing your page when it executes.\n",
"??... | [
1,
0
] | [] | [] | [
"javascript",
"pyqt",
"pyqt4",
"python",
"qwebview"
] | stackoverflow_0003285731_javascript_pyqt_pyqt4_python_qwebview.txt |
Q:
Comparing multiple lines of strings in a variable
How to check whether a para is present in a file or not using python.
For example, sampleData is
backtick escapes like _so_
quote by placing > at start of line
to make links
<http://foo.com>
[foo](http://foo.com)
<a href="http://foo.com">fo... | Comparing multiple lines of strings in a variable | How to check whether a para is present in a file or not using python.
For example, sampleData is
backtick escapes like _so_
quote by placing > at start of line
to make links
<http://foo.com>
[foo](http://foo.com)
<a href="http://foo.com">foo</a>
and i want to search for
quote by placing > at st... | [
"The in operator and any search functions work no matter the value:\n>>> needle = '`Searching > for text`'\n>>> haystack = 'You are `Searching > for text`, are you not?'\n>>> needle in haystack\nTrue\n\nIf you want more advanced matching (like skip certain characters, and allow arbitrary whitespace in between), use... | [
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007443177_python_string.txt |
Q:
Parse JavaScript to instrument code
I need to split a JavaScript file into single instructions. For example
a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
has to be separated into three instructions. (assignment, function call and function definition).
Basically I need to instrument the code, injec... | Parse JavaScript to instrument code | I need to split a JavaScript file into single instructions. For example
a = 2;
foo()
function bar() {
b = 5;
print("spam");
}
has to be separated into three instructions. (assignment, function call and function definition).
Basically I need to instrument the code, injecting code between these instructions to p... | [
"Why not use a JavaScript parser? There are lots, including a Python API for ANTLR and a Python wrapper around SpiderMonkey.\n",
"JavaScript is tricky to parse; you need a full JavaScript parser.\nThe DMS Software Reengineering Toolkit can parse full JavaScript and build a corresponding AST.\nAST operators can th... | [
4,
2,
0,
0,
0
] | [] | [] | [
"javascript",
"parsing",
"python",
"spidermonkey"
] | stackoverflow_0000843546_javascript_parsing_python_spidermonkey.txt |
Q:
Django / general caching question
One common pattern when caching with Django is to use the current site's ID in each cache key, in order to, in essence, namespace your keys. The problem I have is that I'd love to be able to delete all values in cache under a namespace (e.g. Delete all cache values for site 45 bec... | Django / general caching question | One common pattern when caching with Django is to use the current site's ID in each cache key, in order to, in essence, namespace your keys. The problem I have is that I'd love to be able to delete all values in cache under a namespace (e.g. Delete all cache values for site 45 because they've made some fundamental chan... | [
"It's generally difficult to delete large categories of keys. A better approach is for each site to have a generation number associated with it. Start the generation at 1. Use the generation number in the cache keys for that site. When you make a fundamental change, or any other time you want to invalidate the ... | [
2,
1
] | [] | [] | [
"caching",
"django",
"memcached",
"python"
] | stackoverflow_0007455325_caching_django_memcached_python.txt |
Q:
Matplotlib + Pylab import error
Been struggling to resolve this for most of the day, hoping someone can assist...
I'm running python 2.7, have installed matplotlib but when attempting to get started and import pylab I receive errors saying that no module is found, even when there is clearly a pylab module in the m... | Matplotlib + Pylab import error | Been struggling to resolve this for most of the day, hoping someone can assist...
I'm running python 2.7, have installed matplotlib but when attempting to get started and import pylab I receive errors saying that no module is found, even when there is clearly a pylab module in the matplotlib directory and we're using:
... | [
"Solved! \nI had the script I was testing with in the same directory as the original 'matplotlib' directory from install. Using print sys.path I saw this was where the script was looking for the pylab files rather than the matplotlib directory in site-packages.\nThanks. \n",
"An easy mistake could be to name the ... | [
3,
2,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0007458675_matplotlib_python.txt |
Q:
Initializing Python class
I am newbie in object-oriented design.
I try to incorporate a python function into my init . (Function works, as I asked earlier).
Here is my code:
import struct
import urllib2
import StringIO
class wallpaper:
def __init__(self, url):
self.url = url
self.content_typ... | Initializing Python class | I am newbie in object-oriented design.
I try to incorporate a python function into my init . (Function works, as I asked earlier).
Here is my code:
import struct
import urllib2
import StringIO
class wallpaper:
def __init__(self, url):
self.url = url
self.content_type = ''
self.height = 0... | [
"You're only reading 2 bytes into data.\n",
"It will be difficult to determine the problem if you simply ignore exceptions:\n except struct.error:\n pass\n except ValueError:\n pass\n\nAt least you should print the error messages:\n except struct.error as exc:\n print str(exc)\n e... | [
3,
1,
1
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0007462209_oop_python.txt |
Q:
Python class design
I'm writing an expense tracking program. At the moment I have three class
Lineitem stores the attributes for individual transactions and has methods format a transaction for output (payee, amount date), etc. Each lineitem is one transaction.
Account is a collection of lineitems and has methods... | Python class design | I'm writing an expense tracking program. At the moment I have three class
Lineitem stores the attributes for individual transactions and has methods format a transaction for output (payee, amount date), etc. Each lineitem is one transaction.
Account is a collection of lineitems and has methods to add a lineitem, list ... | [
"\n1) Does this seem a sensible way of organizing classes?\n\nYes, it seems so. Remember that LineItem \"ispartof\" Account, and Account itself is part of Journal. There are no inheritance relationships around, you just have a collection of Accounts in Journal, and a collection of LineItem's in Account.\nThe only i... | [
2
] | [] | [] | [
"class_design",
"oop",
"python"
] | stackoverflow_0007462283_class_design_oop_python.txt |
Q:
Issue launching Wing from C#
I have this snippet of code:
void wing()
{
Process wing = new Process();
wing.StartInfo.UseShellExecute = true;
wing.StartInfo.FileName = "C:\\Program Files\\Wing IDE 4.0\\bin\\wing.exe";
wing.StartInfo.Arguments = "C:\\Documents and Settings\\User\\Desktop\\hello.py";
... | Issue launching Wing from C# | I have this snippet of code:
void wing()
{
Process wing = new Process();
wing.StartInfo.UseShellExecute = true;
wing.StartInfo.FileName = "C:\\Program Files\\Wing IDE 4.0\\bin\\wing.exe";
wing.StartInfo.Arguments = "C:\\Documents and Settings\\User\\Desktop\\hello.py";
wing.Start();
}
Every time t... | [
"Try putting double quotes around the filename i.e. @\"\"\"\" + \"C:\\....your file\" + @\"\"\"\"\n"
] | [
0
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0007458444_c#_python.txt |
Q:
accessing values from a nested dictionary
I am trying to create a list of the input with their corresponding values accessing from the global nested dictionary. Here is the code,
import sys
param_values = {
'vowels':{
'aa' : [(-1,-1), (-1,-1), (-1,-1), (-1,-1), (0.1,1.0), (-1,-1... | accessing values from a nested dictionary | I am trying to create a list of the input with their corresponding values accessing from the global nested dictionary. Here is the code,
import sys
param_values = {
'vowels':{
'aa' : [(-1,-1), (-1,-1), (-1,-1), (-1,-1), (0.1,1.0), (-1,-1)],
'ae' : [(-1,-1), (-1,-1)... | [
"param_values.get should not be used there, since you already used param_values[...] to read the value.\ni.e. instead of:\nparam_values.get(param_values[group][phones])\n\nUse:\nparam_values[group][phones]\n\nYou can use get instead of (not in addition to) [...] if you want a default value in case the key doesn't e... | [
1,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0007462361_python.txt |
Q:
How to display images using different color maps in different figures in matplotlib?
I want to display images using different color maps in different figures.
Following code displays the image with two different windows but the same color map
import scipy.misc
from pylab import *
a = scipy.misc.imread('... | How to display images using different color maps in different figures in matplotlib? | I want to display images using different color maps in different figures.
Following code displays the image with two different windows but the same color map
import scipy.misc
from pylab import *
a = scipy.misc.imread('lena.jpg')
figure(1)
image = mean(a,axis=2)
imshow(image)
#if I call show() he... | [
"To do subplots, use the subplot command (!)\nTo change the colormap, you can use the cmap argument of the imshow function. See the documentation.\nfigure() # You don't need to specify 1\nsubplot(121) # 121 is a shortcut for 1 line, 2 columns, item number 1\nimage = mean(a,axis=2)\nimshow(image, cmap='gray')\nsubpl... | [
9,
7,
6,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006768946_matplotlib_python.txt |
Q:
Adding blank nodes in triples
The code written below gives the following output:
Code:
person = BNode()
dataStore.add((URIRef(stringrd),FOAF_NS['knows'],person))
dataStore.add((person,FOAF_NS['Person'],URIRef(fetchKnowsRowString)))
dataStore.add((person,TRUST_NS['hasValue'],Literal(trustString)))
Output:
<rdf:Des... | Adding blank nodes in triples | The code written below gives the following output:
Code:
person = BNode()
dataStore.add((URIRef(stringrd),FOAF_NS['knows'],person))
dataStore.add((person,FOAF_NS['Person'],URIRef(fetchKnowsRowString)))
dataStore.add((person,TRUST_NS['hasValue'],Literal(trustString)))
Output:
<rdf:Description rdf:about="http://www.iamr... | [
"It seems that you are looping somehow wrongly over the bNode person. You are using always the same bNode, that might be the cause of the error.\nSo if your code looks like ...\nperson = BNode()\nfor (fetchKnowsRowString, trustString) in friends:\n dataStore.add((URIRef(stringrd),FOAF_NS['knows'],person))\n dat... | [
0,
0
] | [] | [] | [
"blank_nodes",
"python",
"rdf",
"rdflib"
] | stackoverflow_0007435384_blank_nodes_python_rdf_rdflib.txt |
Q:
Posting a form back with it's default values in the Django TestClient
I'm writing some tests for some forms in Django. These forms change quite often so I'm trying to avoid hard-coding the form parameters into my tests as because every time my form would change, I'd have to modify the tests as well. I have quite a... | Posting a form back with it's default values in the Django TestClient | I'm writing some tests for some forms in Django. These forms change quite often so I'm trying to avoid hard-coding the form parameters into my tests as because every time my form would change, I'd have to modify the tests as well. I have quite a few forms of this nature. I'm mainly testing that the information is store... | [
"I've had to do something like this before, and unfortunately there is no easy way to do it. The best I could come up with was to render the form, then parse the result with BeautifulSoup to get all the values of the inputs and selects. Something like:\nfrom BeautifulSoup import BeautifulSoup\nmyform = MyForm()\nre... | [
1
] | [] | [] | [
"django",
"django_forms",
"django_testing",
"python"
] | stackoverflow_0007462544_django_django_forms_django_testing_python.txt |
Q:
if, elif, else chain not working correctly?
I'm working through 'Learn Python the Hard Way' and I've hit a roadblock. The book gives a unit test and asks you to write a function to satisfy the tests. But when I import this function to the interactive shell to test it out, any input returns 'direction' and I can't ... | if, elif, else chain not working correctly? | I'm working through 'Learn Python the Hard Way' and I've hit a roadblock. The book gives a unit test and asks you to write a function to satisfy the tests. But when I import this function to the interactive shell to test it out, any input returns 'direction' and I can't figure out why.
Here's my code:
def pos(item):
... | [
"You should have written this:\nif item == 'north' or item == 'south' or item == 'east':\n\nor, alternatively:\nif item in ('north', 'south', 'east'):\n\nThe same applies for the remaining branches.\nTo explain why your original code failed, consider how Python parses the following expression:\nitem == 'north' or '... | [
8,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0007463256_python.txt |
Q:
Django form.is_valid keeps throwing KeyError
I have this code in my view:
def add_intern(request):
if request.method == 'POST':
form = InternApplicationForm(request.POST)
if form.is_valid():
form.save()
form = InternApplicationForm()
else:
form = InternApplic... | Django form.is_valid keeps throwing KeyError | I have this code in my view:
def add_intern(request):
if request.method == 'POST':
form = InternApplicationForm(request.POST)
if form.is_valid():
form.save()
form = InternApplicationForm()
else:
form = InternApplicationForm()
return render_to_response('applic... | [
"Okay, so I just nailed it down.\nI followed this advice to set my custom error message for validation.\nSo I had this code:\ndef __init__(self, *args, **kwargs):\n super(InternApplicationForm, self).__init__(*args, **kwargs)\n for field in self.fields.values():\n field.error_messages = {'required':'*'... | [
7
] | [] | [] | [
"django",
"django_1.3",
"django_forms",
"django_validation",
"python"
] | stackoverflow_0007463159_django_django_1.3_django_forms_django_validation_python.txt |
Q:
Motion Animation
I have a project in Python 2.7 and PyGTK 2.24. I am using the following code to create a motion animation of a gtk.Image inside a gtk.Fixed.
def fishmove():
global fishmove
if fishmove < 640:
fishmove = fishmove + 10
fixed_hab.move(fish1, fishmove, 50) ... | Motion Animation | I have a project in Python 2.7 and PyGTK 2.24. I am using the following code to create a motion animation of a gtk.Image inside a gtk.Fixed.
def fishmove():
global fishmove
if fishmove < 640:
fishmove = fishmove + 10
fixed_hab.move(fish1, fishmove, 50)
gobject.timeout... | [
"Pay attention to the naming of the variables! If you have a global integer fishmove and a method of the same name, those two will almost certainly interfere in some unexpected way!\nTry renaming the method to move_fish or sth.\n",
"I solved it. I just needed to add the line \"return True\" at the end of the func... | [
2,
1
] | [] | [] | [
"animation",
"gobject",
"pygtk",
"python"
] | stackoverflow_0007459204_animation_gobject_pygtk_python.txt |
Q:
Simultaneous simulations in python
I have a large set of simple simulations that I need to run, and I'm wondering if they can be done simultaneously. Let me describe the situation: I have 1000 draws of prevalence for ~100 diseases, and 1000 draws of corresponding disability weights for those diseases (how bad it... | Simultaneous simulations in python | I have a large set of simple simulations that I need to run, and I'm wondering if they can be done simultaneously. Let me describe the situation: I have 1000 draws of prevalence for ~100 diseases, and 1000 draws of corresponding disability weights for those diseases (how bad it is to have that disease on a 0-1 scale)... | [
"If you have multiple processors/cores, you could take a look at the multiprocessing module.\nRunning 1000 simulations at the same time might be a bit expensive though. You should probably run your simulations at the rate of one per core at a time.\nYou could use the Queue module and work with a Process pool.\nHere... | [
4
] | [] | [] | [
"numpy",
"performance",
"python",
"simulation"
] | stackoverflow_0007463268_numpy_performance_python_simulation.txt |
Q:
Don't understand this python For loop
I'm still a python newb, but I'm working through the Pyneurgen neural network tutorial, and I don't fully understand how the for loop used to create the input data works in this instance:
for position, target in population_gen(population):
pos = float(position)
all_inp... | Don't understand this python For loop | I'm still a python newb, but I'm working through the Pyneurgen neural network tutorial, and I don't fully understand how the for loop used to create the input data works in this instance:
for position, target in population_gen(population):
pos = float(position)
all_inputs.append([random.random(), pos * factor])... | [
"The function population_gen is returning a list of tuples, which are unpacked automatically into variable names using this syntax.\nSo basically, you're getting something like the following as return value from the function:\n[(\"pos1\", \"target1\"), (\"pos2\", \"target2\"), ]\n\nGiven this example, in the the fo... | [
21,
6,
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0007463683_python.txt |
Q:
How to import a range of lines in a file in python
I have a set of data files where there is a bunch of header information followed by columns of values that I want to store in a data structure using python.
ie:
%multiple lines of header information
%column headers
dataincol1 dataincol2 dataincol3
....
etc
Th... | How to import a range of lines in a file in python | I have a set of data files where there is a bunch of header information followed by columns of values that I want to store in a data structure using python.
ie:
%multiple lines of header information
%column headers
dataincol1 dataincol2 dataincol3
....
etc
The starting point and length of the columns are not the s... | [
"A flag is just fine. However one other way is to stop the iteration and continue it in another loop:\niter = open(filename).__iter__()\nfor line in iter: # process all lines until column header\n if line == \"COLUMN_HEADERS\": # or whatever\n break\nfor line in iter: # process all subsequent lines\n ... | [
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0007211732_file_io_python.txt |
Q:
How to convert a string containing the month's name to an integer?
Is there a way to convert a string containing the month's name to an integer that is dependent on the current locale?
I know that somedate.strftime("%B") can convert a date time object to a string containing the month's name according to the curren... | How to convert a string containing the month's name to an integer? | Is there a way to convert a string containing the month's name to an integer that is dependent on the current locale?
I know that somedate.strftime("%B") can convert a date time object to a string containing the month's name according to the current locale but is there way to go backwards?
| [
"strptime() does the inverse of what strftime() does.\n>>> datetime.datetime.strptime(\"February\", \"%B\").month\n2\n\n"
] | [
6
] | [] | [] | [
"python"
] | stackoverflow_0007463896_python.txt |
Q:
How to deal with Linux/Python dependencies?
Due to lack of support for some libraries I want to use, I moved some Python development from Windows to Linux development. I've spent most of the day messing about getting nowhere with dependencies.
The question
Whenever I pick up Linux, I usually run into some kind of ... | How to deal with Linux/Python dependencies? | Due to lack of support for some libraries I want to use, I moved some Python development from Windows to Linux development. I've spent most of the day messing about getting nowhere with dependencies.
The question
Whenever I pick up Linux, I usually run into some kind of dependency issue, usually with development librar... | [
"I see two separate problems here:\n\nKeeping track of all the python modules you need for your project.\nKeeping track of all the dynamic libraries you need for the python modules in your project.\n\nFor the first problem, I have found that buildout is good help, althought it takes a litle while to grasp. \nIn you... | [
13,
0
] | [] | [] | [
"dependencies",
"dependency_management",
"linux",
"python"
] | stackoverflow_0007463530_dependencies_dependency_management_linux_python.txt |
Q:
Could I use array slicing instead of creating vectors?
This is not homework!
Simply example to complex problem.
Right now I take arrays, create vectors, then use equation with vectors as inputs.
Everything works fine. But, wondering if I could skip vector creation and use the array slicing to the samething.
... | Could I use array slicing instead of creating vectors? | This is not homework!
Simply example to complex problem.
Right now I take arrays, create vectors, then use equation with vectors as inputs.
Everything works fine. But, wondering if I could skip vector creation and use the array slicing to the samething.
import numpy as np
a = [[ 7., 5.], [ 9., 3.], [ 7., 2.],... | [
"import numpy as np\n\na = np.array([[ 7., 5.], [ 9., 3.], [ 7., 2.], [ 7., 8.], [ 6., 8.], [ 3., 2.]])\n\nfoo = 5*a[:,0] + a[:,1]**2 \n\n"
] | [
5
] | [] | [] | [
"numpy",
"python",
"slice"
] | stackoverflow_0007464052_numpy_python_slice.txt |
Q:
Make PNG sprites in PIL but want to preserve alpha channel
I'm creating a script to grab a bunch of favicons, convert them to png and make a single sprite image out of all of them.
The helpful g.etfv.co will detect and convert favicons in PNG format, and I'm using PIL to montage the images into a sprite sheet.
It ... | Make PNG sprites in PIL but want to preserve alpha channel | I'm creating a script to grab a bunch of favicons, convert them to png and make a single sprite image out of all of them.
The helpful g.etfv.co will detect and convert favicons in PNG format, and I'm using PIL to montage the images into a sprite sheet.
It all works fine except I seem to lose the alpha transparency chan... | [
"The result image inew has no alpha chanel.\nUPDATE:\ntry \ninew = PIL.Image.new('RGBA',(len(icons)*16,16))\n\n"
] | [
0
] | [] | [] | [
"image",
"image_processing",
"png",
"python",
"python_imaging_library"
] | stackoverflow_0007464177_image_image_processing_png_python_python_imaging_library.txt |
Q:
Cycling through array elements efficiently in python
I'm trying to sum the elements of separate data array by their characteristics efficiently. I have three identifying characteristics (age, year, and cause) in a given array, and for each age, year, cause, I have 1000 values. I need to add those values to anoth... | Cycling through array elements efficiently in python | I'm trying to sum the elements of separate data array by their characteristics efficiently. I have three identifying characteristics (age, year, and cause) in a given array, and for each age, year, cause, I have 1000 values. I need to add those values to another data array when the characteristics are the same. For ... | [
"I'd recommend something like accumarray. Your output should be a 3-dimensional data cube where each dimension corresponds to a variable (age, year, cause). Each index in each dimension corresponds to a unique value in your input lists. You can then use something like this cookbook example to accumulate the data... | [
2,
0
] | [] | [] | [
"arrays",
"numpy",
"performance",
"python"
] | stackoverflow_0007382764_arrays_numpy_performance_python.txt |
Q:
How to prevent duplicate values in a shared queue
A producer thread queries a data store and puts objects into a queue. Each consumer thread(s) will then pull an object off of the shared queue and do a very long call to an external service. When the call returns, the consumer marks the object as having been comp... | How to prevent duplicate values in a shared queue | A producer thread queries a data store and puts objects into a queue. Each consumer thread(s) will then pull an object off of the shared queue and do a very long call to an external service. When the call returns, the consumer marks the object as having been completed.
My problem is that I basically have to wait unti... | [
"It seems to me like it's not really a problem to have duplicate objects in the queue; you just want to make sure you only do the processing once per object.\nEDIT: I originally suggested using a set or OrderedDict to keep track of the objects, but Python has a perfect solution: functools.lru_cache\nUse @functools.... | [
4,
1,
0
] | [] | [] | [
"python",
"queue"
] | stackoverflow_0007464000_python_queue.txt |
Q:
Trying to loop just some parts of a math quiz program
I'm trying to figure out the best way to loop this simple math quiz program (best here meaning the neatest and simplest method). I get two random numbers and their sum, prompt the user to enter, and evaluate that input. Ideally, it should get new numbers when t... | Trying to loop just some parts of a math quiz program | I'm trying to figure out the best way to loop this simple math quiz program (best here meaning the neatest and simplest method). I get two random numbers and their sum, prompt the user to enter, and evaluate that input. Ideally, it should get new numbers when they want to play again and ask the same question when the p... | [
"You're missing two things here. First, you need some sort of loop construct, such as:\nwhile <condition>:\n\nOr:\nfor <var> in <list>:\n\nAnd you need some way to \"short-circuit\" the loop so that you can start again\nat the top if your user types in a non-numeric value. For that you want to\nread up on the con... | [
2,
1
] | [] | [] | [
"loops",
"python",
"user_input"
] | stackoverflow_0007464345_loops_python_user_input.txt |
Q:
problem with implenting __len__ with sqlalchemy func.count getting some kind of recursion error
the code - supposed to implent the len magic method with the following code:
def __len__(self):
from sqlalchemy import func
self.len = session.query(func.count(Question.id)).scalar()
return int(self.len... | problem with implenting __len__ with sqlalchemy func.count getting some kind of recursion error | the code - supposed to implent the len magic method with the following code:
def __len__(self):
from sqlalchemy import func
self.len = session.query(func.count(Question.id)).scalar()
return int(self.len)
def __repr__(self):
self.repr = "traffic theory question, current number of questions:{0}".fo... | [
"You're trying to format an instance method, self.__len__, not the length returned by that instance method.\nWhen you try to format(self.__len__), it calls repr on the instance referred to by self, creating the recursion.\nYou need to use format on self.__len__() (or len(self) or self.len).\n"
] | [
2
] | [] | [] | [
"database",
"python",
"sqlalchemy"
] | stackoverflow_0007464642_database_python_sqlalchemy.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.