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:
Why are certain elements of this python list ignored?
I'm new to Python, and i'm struggling to understand the output of this simple program:
list = os.listdir(os.getcwd())
print(list)
print()
for element in list:
print(element)
if 'txt' not in element: list.remove(element)
Which gives me this output :
['e... | Why are certain elements of this python list ignored? | I'm new to Python, and i'm struggling to understand the output of this simple program:
list = os.listdir(os.getcwd())
print(list)
print()
for element in list:
print(element)
if 'txt' not in element: list.remove(element)
Which gives me this output :
['examples_list.txt', 'generate_patterns.py', 'lehoczky_exampl... | [
"You cannot remove elements from the list while looping through it. Try and loop over a copy of the list, or create a new one with only the elements you want to keep.\nSee also Python strange behavior in for loop or lists\n",
"Try list comprehension. This will keep your list of files and create a new list noTxtFi... | [
10,
5
] | [] | [] | [
"python"
] | stackoverflow_0004023739_python.txt |
Q:
since X variables are in a list, call a function with X parameters
I have mylist = [var1, var2, var3... varn].
os.path.join is called not one list, but with many vars.
I can't call os.path.join(mylist).
How to call os.path.join(var1, var2, var3... varn)?
A:
Try:
os.path.join(*mylist)
| since X variables are in a list, call a function with X parameters | I have mylist = [var1, var2, var3... varn].
os.path.join is called not one list, but with many vars.
I can't call os.path.join(mylist).
How to call os.path.join(var1, var2, var3... varn)?
| [
"Try:\nos.path.join(*mylist)\n\n"
] | [
11
] | [] | [] | [
"python"
] | stackoverflow_0004024156_python.txt |
Q:
How to get source line number from a Python generator object?
Here is an example:
def g():
yield str('123')
yield int(123)
yield str('123')
o = g()
while True:
v = o.next()
if isinstance( v, str ):
print 'Many thanks to our generator...'
else:
# Or GOD! I don't know what to do with this type
... | How to get source line number from a Python generator object? | Here is an example:
def g():
yield str('123')
yield int(123)
yield str('123')
o = g()
while True:
v = o.next()
if isinstance( v, str ):
print 'Many thanks to our generator...'
else:
# Or GOD! I don't know what to do with this type
raise TypeError( '%s:%d Unknown yield value type %s.' % \
... | [
"Your generator object \"o\" in this case has all the information you want. You can paste your example into a Python console, and inspect with dir both the function \"g\" and the generator \"o\".\nThe generator has the attributes \"gi_code\" and \"gi_frame\" which contain the information you want:\n>>> o.gi_code.co... | [
8
] | [
"I don't think you can get the information you want. That's the sort of thing captured in exceptions, but there has been no exception here.\n"
] | [
-2
] | [
"generator",
"python"
] | stackoverflow_0004024609_generator_python.txt |
Q:
How to parse multiple XML documents from a single stream?
I've got a socket from which I'm reading XML data. However, this socket will spit out multiple different XML documents, so I can't simply parse all the output I receive.
Is there a good way, preferably using the Python standard library, for me to parse mul... | How to parse multiple XML documents from a single stream? | I've got a socket from which I'm reading XML data. However, this socket will spit out multiple different XML documents, so I can't simply parse all the output I receive.
Is there a good way, preferably using the Python standard library, for me to parse multiple XML documents? In other words, if I end up getting
<foo/... | [
"If you get separate documents, you'll need something to divide them; and if you have that, you can simply split the stream before you parse the individual documents.\nAnother possibility would be to wrap that into another document, so each XML document is actually a subdocument of a parent's you create (and wrap a... | [
4
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004024739_python_xml.txt |
Q:
Change the bpm of a song while playing it in python
i'am looking for a way to attune a song to the heart rate of someone.
I have a song in mp3 or wav format and i want to accelerate the speed of it while playing it.
Or playing it in loop and between each loop accelerate it or slow it.
Ideally it will be in python.... | Change the bpm of a song while playing it in python | i'am looking for a way to attune a song to the heart rate of someone.
I have a song in mp3 or wav format and i want to accelerate the speed of it while playing it.
Or playing it in loop and between each loop accelerate it or slow it.
Ideally it will be in python.
Do you know a way to do that ?
Regards and thanks.
Bussi... | [
"There are a few different pieces here, each of which needs to be solved. None of them are trivial and require a decent amount of signal processing knowledge, so you'll probably want to look for libraries to handle that part of the heavy lifting.\n\nCardiac beat detection. This is outside my area of knowledge, but ... | [
4,
2
] | [] | [] | [
"audio",
"audio_processing",
"controls",
"python"
] | stackoverflow_0004024389_audio_audio_processing_controls_python.txt |
Q:
why doesn't (list1[-1]+=list2.pop(0))+=list2 work in Python?
I have two lists of strings that, in a better world, would be one list. I need to concatenate the lists, but the last element of the first list needs to be concatenated with the first element of the second list. So these guys:
list1 = ["bob", "sal"]
list... | why doesn't (list1[-1]+=list2.pop(0))+=list2 work in Python? | I have two lists of strings that, in a better world, would be one list. I need to concatenate the lists, but the last element of the first list needs to be concatenated with the first element of the second list. So these guys:
list1 = ["bob", "sal"]
list2 = ["ly", "nigel"]
needs to become
out = ["bob", "sally", "nigel... | [
"Remove all those += operators, they don't make sense here. If you want to use them as a replacement for a.extend(b), then remember, that they cannot be used as an expression. This command modifies the a list, but does not return anything. So c = a.extend(b) gives nothing to c.\nTry this instead (it even does not m... | [
10,
3,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004024339_list_python.txt |
Q:
PyGtk Program is not responding on Windows
I just managed to get py2exe work on a Windows Virtual Machine but stumbled on another problem which I didn't have right after I installed GTK, Pango, Gobject etc. on that machine: When I launch a Python Script the window appears but it immediately stops responding. This ... | PyGtk Program is not responding on Windows | I just managed to get py2exe work on a Windows Virtual Machine but stumbled on another problem which I didn't have right after I installed GTK, Pango, Gobject etc. on that machine: When I launch a Python Script the window appears but it immediately stops responding. This happens too if I open a python interpreter and t... | [
"You need to run a main loop so GTK can process events, draw in the window, etc.\nAdd this to your program:\ngtk.main()\n\nSee also: http://live.gnome.org/PyGTK/QuickStart\n",
"Solved! It seems installing ActivePython the installing GTK runtime, PyCairo, PyObject, PyGtk as administrator with compatibility mode fo... | [
2,
1
] | [] | [] | [
"py2exe",
"pygtk",
"python",
"windows"
] | stackoverflow_0004009566_py2exe_pygtk_python_windows.txt |
Q:
Average the duplicated values from two paired lists in Python
in my code I obtain two different lists from different sources, but I know they are in the same order. The first list ("names") contains a list of keys strings, while the second ("result_values") is a series of floats. I need to make the pair unique, bu... | Average the duplicated values from two paired lists in Python | in my code I obtain two different lists from different sources, but I know they are in the same order. The first list ("names") contains a list of keys strings, while the second ("result_values") is a series of floats. I need to make the pair unique, but I can't use a dictionary as only the last value inserted would be... | [
"from collections import defaultdict\ndef averages(names, values):\n # Group the items by name.\n value_lists = defaultdict(list)\n for name, value in zip(names, values):\n value_lists[name].append(value)\n\n # Take the average of each list.\n result = {}\n for name, values in value_lists.i... | [
5,
3,
3,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004022465_list_python.txt |
Q:
Pylons FormEncode with an array of form elements
I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)
<tr>
<td>Yardage</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)... | Pylons FormEncode with an array of form elements | I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)
<tr>
<td>Yardage</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size... | [
"Turns out what I wanted to do wasn't quite right. \nTemplate:\n<tr>\n <td>Yardage</td>\n % for hole in range(9):\n <td>${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}</td>\n % endfor\n</tr>\n\n(Should have made it in a loop to begin with.) You'll notice that the name of the first element will become h... | [
5,
1
] | [] | [] | [
"formencode",
"htmlfill",
"pylons",
"python"
] | stackoverflow_0000994460_formencode_htmlfill_pylons_python.txt |
Q:
Selecting only text within a div tag
I'm working on a web parser using urllib. I need to be able to only save lines that lie within a certain div tag. for instance: I'm saving all text in the div "body." This means all text within the div tags will be returned. It also means if there are other divs inside of ... | Selecting only text within a div tag | I'm working on a web parser using urllib. I need to be able to only save lines that lie within a certain div tag. for instance: I'm saving all text in the div "body." This means all text within the div tags will be returned. It also means if there are other divs inside of it thats fine, but as soon as I hit the pa... | [
"If you're not really excited at the idea of parsing the HTML code yourself, there are two good options:\nBeautiful Soup \nLxml\nYou'll probably find that lxml runs faster than BeautifulSoup, but in my uses, Beautiful Soup was very easy to learn and use, and handled typical crappy HTML as found in the wild well eno... | [
3,
3,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0004025181_python_urllib.txt |
Q:
Show pdf only to authenticated users
I'm building a web site from the old one and i need to show a lot of .pdf files.
I need users to get authenficated before the can't see any of my .pdf but i don't know how (and i can't put my pdf in my database).
I'm using Pylons with Python.
Thank for you help.
If you have any... | Show pdf only to authenticated users | I'm building a web site from the old one and i need to show a lot of .pdf files.
I need users to get authenficated before the can't see any of my .pdf but i don't know how (and i can't put my pdf in my database).
I'm using Pylons with Python.
Thank for you help.
If you have any question, ask me! :)
| [
"Here's my stab at how to do it in Pylons. I haven't tested this but there should be enough links to get you going.\n\nEnable X-SendFile on your HTTP server (as Paul said, the implementation depends on the server): Apache mod_xsendfile, Nginx equivalent\nPut the PDFs outside the /public directory in your Pylons ins... | [
4,
2,
2,
0
] | [] | [] | [
"html",
"pdf",
"permissions",
"pylons",
"python"
] | stackoverflow_0003980878_html_pdf_permissions_pylons_python.txt |
Q:
Django MultiWidget Phone Number Field
I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common "(" ")" "-" delimiters. Below is my code for the field and the widget, I'm getting the following error when trying to iterate the fields in my form during in... | Django MultiWidget Phone Number Field | I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common "(" ")" "-" delimiters. Below is my code for the field and the widget, I'm getting the following error when trying to iterate the fields in my form during initial rendering (it happens when the for lo... | [
"This uses widget.value_from_datadict() to format the data so no need to subclass a field, just use the existing USPhoneNumberField. Data is stored in db like XXX-XXX-XXXX.\nfrom django import forms\n\nclass USPhoneNumberMultiWidget(forms.MultiWidget):\n \"\"\"\n A Widget that splits US Phone number input int... | [
6,
4,
1,
0
] | [] | [] | [
"django_forms",
"django_models",
"django_templates",
"django_widget",
"python"
] | stackoverflow_0001777435_django_forms_django_models_django_templates_django_widget_python.txt |
Q:
(Python) How can I print a variable to a Tweepy "API.update_status()" command?
I am trying to add some information to a python script that posts the information to twitter. Here is the code so far:
#!/usr/bin/python
import os
import subprocess
import psutil
import sys
import tweepy
#------------------------------... | (Python) How can I print a variable to a Tweepy "API.update_status()" command? | I am trying to add some information to a python script that posts the information to twitter. Here is the code so far:
#!/usr/bin/python
import os
import subprocess
import psutil
import sys
import tweepy
#----------------------------------------
# Gives a human-readable uptime string
def uptime():
try:
f = open( ... | [
"So what's the problem? The tweepy docs say you can pass a string to update_status():\napi.update_status('uptime: %s / mem: %i%%' % (time, mem))\n\nAlso, I'm guessing you meant\ntime = uptime()\nmem = psutil.Process(2360).get_memory_percent()\n\n"
] | [
1
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0004020781_python_tweepy_twitter.txt |
Q:
Problem Writing Image file in Python with PIL
I'm writing a small Python script using the PIL module to change the size of some textures used on a 3D Model in MultiGen Creator. I'm also using the openflight API so that's what the mg* functions are.
Here's the script
import PIL
from PIL import Image
db = mgGetCur... | Problem Writing Image file in Python with PIL | I'm writing a small Python script using the PIL module to change the size of some textures used on a 3D Model in MultiGen Creator. I'm also using the openflight API so that's what the mg* functions are.
Here's the script
import PIL
from PIL import Image
db = mgGetCurrentDb()
ret,index,name = mgGetFirstTexture (db)
wh... | [
"You need to double up the \\ characters in your file name or use a raw string:\n ImgOut = \"C:\\\\DB\\\\PLW\\\\out.jpg\" \n ImgOut = r\"C:\\DB\\PLW\\out.jpg\" \n\nThe error message is basically saying it couldn't open the file.\n"
] | [
2
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0004025545_python_python_imaging_library.txt |
Q:
How to save a temporarily jpg file by using python?
Hey I need to save a temporarily jpg file and then remove it, is there any better way to do?
I tested the tempfile, but looks that doesn't work.
A:
tempfile does work. What did you try?
>>> with tempfile.NamedTemporaryFile(mode="wb") as jpg:
... jpg.write(b... | How to save a temporarily jpg file by using python? | Hey I need to save a temporarily jpg file and then remove it, is there any better way to do?
I tested the tempfile, but looks that doesn't work.
| [
"tempfile does work. What did you try?\n>>> with tempfile.NamedTemporaryFile(mode=\"wb\") as jpg:\n... jpg.write(b\"Hello World!\")\n... print jpg.name\n...\nc:\\users\\<...>\\appdata\\local\\temp\\tmpv7hy__\n\njpg will be closed as soon as the with block is left. If you pass in the optional argument delete... | [
5
] | [] | [] | [
"python",
"temporary_files"
] | stackoverflow_0004025726_python_temporary_files.txt |
Q:
Accessing private variables when there's a getter/setter for them
I have a question about righteous way of programming in Python... Maybe there can be several different opinions, but here it goes:
Let's say I have a class with a couple of private attributes and that I have implemented two getters/setters (not over... | Accessing private variables when there's a getter/setter for them | I have a question about righteous way of programming in Python... Maybe there can be several different opinions, but here it goes:
Let's say I have a class with a couple of private attributes and that I have implemented two getters/setters (not overloading __getattr__ and __setattr__, but in a more “Java-tistic” style)... | [
"You can't present a classic example of bad Python and then expect people to have opinions on what do to about it. Use getters and setters.\nclass MyClass:\n def __init__(self): \n self._private1 = \"Whatever1\"\n\n @property\n def private1(self):\n return self._private1\n\n @private1.se... | [
9,
2
] | [] | [] | [
"oop",
"private_members",
"python"
] | stackoverflow_0004025888_oop_private_members_python.txt |
Q:
Python Swig wrapper: how access underlying PyObject
I've got class A wrapped with method foo implemented using %extend:
class A {
...
%extend {
void foo()
{
self->foo_impl();
}
}
Now I want to increase ref count to an A inside foo_impl, but I only got A* (as self).
Question: how can I write/wrap f... | Python Swig wrapper: how access underlying PyObject | I've got class A wrapped with method foo implemented using %extend:
class A {
...
%extend {
void foo()
{
self->foo_impl();
}
}
Now I want to increase ref count to an A inside foo_impl, but I only got A* (as self).
Question: how can I write/wrap function foo, so that I have an access both to A* and unde... | [
"I think it's not possible. If you need to increase the refcount, it's because you don't want the C++ object to be destroyed when it goes out of scope because there is a pointer to that object elsewhere. In that case, look at using the DISOWN typemap to ensure the target language doesn't think it \"owns\" the C++... | [
1
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0004005355_c++_python_swig.txt |
Q:
How can I move my Python2.6 site-packages into Python2.7?
I just ran an update on ArchLinux which gave me Python3 and Python2.7.
Before this update, I was using Python2.6. The modules I have installed reside in /usr/lib/python2.6/site-package. I now want to use Python2.7 and remove Python2.6.
How can I move my Pyt... | How can I move my Python2.6 site-packages into Python2.7? | I just ran an update on ArchLinux which gave me Python3 and Python2.7.
Before this update, I was using Python2.6. The modules I have installed reside in /usr/lib/python2.6/site-package. I now want to use Python2.7 and remove Python2.6.
How can I move my Python2.6 modules into Python2.7 ?
Is it as simple as doing mv /us... | [
"Your question is really, \"How can I get the packages I have in python 2.6 into my [new] python 2.7 configuration? Would copying the files work?\"\nI would recommend installing the packages into 2.7 the same way you did your 2.6 packages. I would not recommend you copy the files.\nReasonable ways to install the fi... | [
1,
0,
0,
0,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0003968339_module_python.txt |
Q:
quick question: how to associate a file with an ImageField in django?
i have an image saved on my HDD and i want to assign it to an ImageField, but i don't know how.
i've tried something like this:
object.imagefield.save(path,File(open(path)))
But this makes an additional (invalid) copy of the image.
Can someone ... | quick question: how to associate a file with an ImageField in django? | i have an image saved on my HDD and i want to assign it to an ImageField, but i don't know how.
i've tried something like this:
object.imagefield.save(path,File(open(path)))
But this makes an additional (invalid) copy of the image.
Can someone help me please?
thanks!
| [
"I usually simply assign to the image field a string with the image's path, like this:\nMyObject.image=\"/photo_path/photo_name.jpg\"\nMyObject.save()\n\nI don't know if there is something wrong in doing that, but it always works.\n",
"There might be a better way, but I do something like:\nfrom django.core.files.... | [
7,
2
] | [] | [] | [
"django",
"filefield",
"imagefield",
"python"
] | stackoverflow_0004025676_django_filefield_imagefield_python.txt |
Q:
operating over strings, python
How to define a function that takes a string (sentence) and inserts an extra space after a period if the period is directly followed by a letter.
sent = "This is a test.Start testing!"
def normal(sent):
list_of_words = sent.split()
...
This should print out
"This is a test... | operating over strings, python | How to define a function that takes a string (sentence) and inserts an extra space after a period if the period is directly followed by a letter.
sent = "This is a test.Start testing!"
def normal(sent):
list_of_words = sent.split()
...
This should print out
"This is a test. Start testing!"
I suppose I shoul... | [
"Use re.sub. Your regular expression will match a period (\\.) followed by a letter ([a-zA-Z]). Your replacement string will contain a reference to the second group (\\2), which was the letter matched in the regular expression. \n>>> import re\n>>> re.sub(r'\\.([a-zA-Z])', r'. \\1', 'This is a test.This is a tes... | [
8,
3,
1,
1,
0
] | [] | [] | [
"python",
"split",
"tokenize"
] | stackoverflow_0004026287_python_split_tokenize.txt |
Q:
How can I calculate the latitude and longitude of each pixel of an image in a kml file using Python?
I am using .kml file which points to an overlay image (presumably in UTM projection?).
The KML file provides the latitudes and longitudes of the bounding box using the "LatLonBox" tag.
I need to calculate the lat... | How can I calculate the latitude and longitude of each pixel of an image in a kml file using Python? | I am using .kml file which points to an overlay image (presumably in UTM projection?).
The KML file provides the latitudes and longitudes of the bounding box using the "LatLonBox" tag.
I need to calculate the latitudes and longitudes of each pixel in this image.
Are there any pre-existing libraries in Python that wo... | [
"The overlay image referenced by the kml file was in standard geographic projection.\nThis means that the latitudes and longitudes vary linearly within the image. \nCalculating the latitude and longitude of each pixel became a trivial case of interpolation given that we already known the lat/lon bounds of the image... | [
0
] | [] | [] | [
"geospatial",
"kml",
"latitude_longitude",
"python"
] | stackoverflow_0004019611_geospatial_kml_latitude_longitude_python.txt |
Q:
Buildout, psycopg2, postgresql
I'm trying to make buildout config that installs psycopg2 egg and postgres from source if needed:
parts =
...
postgre
psycopg2
...
[postgre]
recipe = hexagonit.recipe.cmmi
url = ftp://ftp3.ua.postgresql.org/pub/mirrors/postgresql/source/v9.0.0/postgresql-9.0.0.tar.gz... | Buildout, psycopg2, postgresql | I'm trying to make buildout config that installs psycopg2 egg and postgres from source if needed:
parts =
...
postgre
psycopg2
...
[postgre]
recipe = hexagonit.recipe.cmmi
url = ftp://ftp3.ua.postgresql.org/pub/mirrors/postgresql/source/v9.0.0/postgresql-9.0.0.tar.gz
configure-options =
--without-r... | [
"You can do it, but you'll have to make your own recipe to do that check. There's no existing recipe that does what you want.\nAn alternative is to have two buildout configs. The main buildout.cfg assumes postgresql is available and doesn't attempt to build it.\nA second withpostgres.cfg could look like this:\n[b... | [
2
] | [] | [] | [
"buildout",
"django",
"python"
] | stackoverflow_0003999081_buildout_django_python.txt |
Q:
how can i limit my django foreign key selection by a property stored in the django session
i have a small application i am implementing with django and i'm having a slight challenge. I'm trying to limit the queryset for my relationships within my application by a particular property. Now the catch is, the exact va... | how can i limit my django foreign key selection by a property stored in the django session | i have a small application i am implementing with django and i'm having a slight challenge. I'm trying to limit the queryset for my relationships within my application by a particular property. Now the catch is, the exact value of the property isn't known until the user logs into the application. an example is limiting... | [
"It is perfectly ok to pass your session property, user or company or whatnot, to other functions in different parts of your system.\nFor example:\ndef view(request):\n user = request.user\n filtered_stuff = my_filter_function(..., user = user)\n\nThe my_filter_function may filter on the argument or may pass ... | [
1,
0,
0
] | [] | [] | [
"django",
"python",
"session_variables"
] | stackoverflow_0004016227_django_python_session_variables.txt |
Q:
Django - Replicating the admin list_display
What's the easiest method to get list_display functionality in my main website (outside of the admin pages).
I have a group of elements I'd like to select and perform an action. Any ideas?
A:
An application called django-filter is by far the best and easiest way to im... | Django - Replicating the admin list_display | What's the easiest method to get list_display functionality in my main website (outside of the admin pages).
I have a group of elements I'd like to select and perform an action. Any ideas?
| [
"An application called django-filter is by far the best and easiest way to implement this. \n",
"Try the Object List from generic views.\n"
] | [
2,
1
] | [] | [] | [
"css",
"django",
"html",
"javascript",
"python"
] | stackoverflow_0004012361_css_django_html_javascript_python.txt |
Q:
Django: saving a ModelForm with custom many-to-many models
I have Publications and Authors. Since the ordering of Authors matters (the professor doesn't want to be listed after the intern that contributed some trivial data), I defined a custom many-to-many model:
class Authorship(models.Model):
author = models... | Django: saving a ModelForm with custom many-to-many models | I have Publications and Authors. Since the ordering of Authors matters (the professor doesn't want to be listed after the intern that contributed some trivial data), I defined a custom many-to-many model:
class Authorship(models.Model):
author = models.ForeignKey("Author")
publication = models.ForeignKey("Publi... | [
"If you are using a custom M2M table using the through parameter, I believe you must do the saves manually in order to save the additional fields. So in your view you would add:\n...\npublication = form.save()\n#assuming that these records are in order! They may not be\norder_idx = 0\nfor author in request.POST.get... | [
2,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004026137_django_django_forms_python.txt |
Q:
provider cannot be found error in python connecting to SQL Server
I'm attempting to connect to a SQL Server database within a Python script. I'm using SQLNCLI as provider on my connection string.
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;pas... | provider cannot be found error in python connecting to SQL Server | I'm attempting to connect to a SQL Server database within a Python script. I'm using SQLNCLI as provider on my connection string.
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd)
dbConn = Dispatch("ADODB.Connectio... | [
"install SQLNCLI. if it still not working change :\n\"Provider=SQLNCLI;server=%...\n\nto\n\"Provider=SQLNCLI10;server=%...\n\n",
"...It is so simple just install this: SQLNCLI.msi\nyou can find it here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en... | [
1,
-1
] | [] | [] | [
"adodb",
"python",
"sql_server",
"win32com"
] | stackoverflow_0004026776_adodb_python_sql_server_win32com.txt |
Q:
How to connect to a DB on windows
I have a SQL server 2005 server database on a server and need to conect to it from a client on the same server network, any ideas?
A:
The pymssql library is one option.
A:
see here for the ensemble of database connector:
http://wiki.python.org/moin/DatabaseInterfaces
for sql s... | How to connect to a DB on windows | I have a SQL server 2005 server database on a server and need to conect to it from a client on the same server network, any ideas?
| [
"The pymssql library is one option.\n",
"see here for the ensemble of database connector:\nhttp://wiki.python.org/moin/DatabaseInterfaces\nfor sql server see here:\nhttp://wiki.python.org/moin/SQL%20Server\n",
"from win32com.client import Dispatch \n\nconnection_string = \"Provider=SQLNCLI;server=%s;initial cat... | [
2,
0,
0
] | [] | [] | [
"python",
"sql_server",
"windows"
] | stackoverflow_0004026428_python_sql_server_windows.txt |
Q:
django ModelMultipleChoiceField (default values)
I've been searching and trying to get this to work for the past few hours and I can't
I have a list of skills that I take from the database:
forms.ModelMultipleChoiceField(
skills.objects.all(),
required=T... | django ModelMultipleChoiceField (default values) | I've been searching and trying to get this to work for the past few hours and I can't
I have a list of skills that I take from the database:
forms.ModelMultipleChoiceField(
skills.objects.all(),
required=True,
widget=forms.Check... | [
"Your question(s) are a little unclear, but il still try my best.\nFirstly, \n\nI wanna display all skills and the one\n the user checked to be checked ...\n\nThe form doesnot have access to the user, so you need to pass it the user. You could do this by overloading the __init__ method like so:\n def __init__(s... | [
2
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0004010878_django_forms_python.txt |
Q:
What is C#'s version of the GIL?
In the current implementation of CPython, there is an object known as the "GIL" or "Global Interpreter Lock". It is essentially a mutex that prevents two Python threads from executing Python code at the same time. This prevents two threads from being able to corrupt the state of th... | What is C#'s version of the GIL? | In the current implementation of CPython, there is an object known as the "GIL" or "Global Interpreter Lock". It is essentially a mutex that prevents two Python threads from executing Python code at the same time. This prevents two threads from being able to corrupt the state of the Python interpreter, but also prevent... | [
"Most other languages that support threading don't have an equivalent of the Python GIL; they require you to use mutexes, either implicitly or explicitly.\n",
"Using lock, you would do this:\nlock(some_list)\n{\n some_list.Add(3);\n}\n\nand in thread 2:\nlock(some_list)\n{\n some_list.Add(4);\n}\n\nThe lock... | [
12,
4,
3,
1,
0,
0
] | [] | [] | [
"c#",
"gil",
"java",
"python"
] | stackoverflow_0004026238_c#_gil_java_python.txt |
Q:
Fade in/out the background color of wxpython grid cell
I've got a wxpython grid, and I'm changing the background color of a cell to show that something has happened to it.
I'd like to fade the color change in/out (like JavaScript in the browser) for a smoother look. Is this possible to do?
Right now, I'm just chan... | Fade in/out the background color of wxpython grid cell | I've got a wxpython grid, and I'm changing the background color of a cell to show that something has happened to it.
I'd like to fade the color change in/out (like JavaScript in the browser) for a smoother look. Is this possible to do?
Right now, I'm just changing the background color, and then changing it back after a... | [
"This is something I did a while ago to get a ListCtrl with items that fade out when deleted. Save the code to fade.py and run it to see the demo. Shouldn't be too hard to adapt it to a Grid.\nimport wx\n\nclass FadeMixin(object):\n ''' FadeMixin provides one public method: DeleteItem. It is meant to\n be mix... | [
4,
1
] | [] | [] | [
"grid",
"python",
"wxpython"
] | stackoverflow_0003985305_grid_python_wxpython.txt |
Q:
Confusing expression in python
If I have the list:
lista=[99, True, "Una Lista", [1,3]]
What does the following expression mean?
mi_var = lista[0:4:2]
A:
The syntax lista[0:4:2] is called extended slice syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), ... | Confusing expression in python | If I have the list:
lista=[99, True, "Una Lista", [1,3]]
What does the following expression mean?
mi_var = lista[0:4:2]
| [
"The syntax lista[0:4:2] is called extended slice syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), but only including the even indexes (step = 2).\nIn your example it will give [99, \"Una Lista\"]. More generally you can get a slice consisting of every ele... | [
8,
0,
0
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0004027103_list_python_slice.txt |
Q:
Python differences between running as script and running via interactive shell
I am attempting to debug a problem with a ctypes wrapper of a windows DLL and have noticed differences when I run tests via an interactive shell (python or ipython) and when I run the scripts non-interactively.
I was wondering if there ... | Python differences between running as script and running via interactive shell | I am attempting to debug a problem with a ctypes wrapper of a windows DLL and have noticed differences when I run tests via an interactive shell (python or ipython) and when I run the scripts non-interactively.
I was wondering if there is any explanation for the differences I am seeing here?
Specifically, when I intera... | [
"The Python interactive interpreter is not thread safe. So, if you try to send a blocking command, the whole interpreter will hang.\nSee this article as to why this happens (tl; dr is that the IDLE and threads don't mix). As for how to fix this, use the console rather than the IDLE GUI. Or, you can just use a scrip... | [
1,
1
] | [] | [] | [
"com",
"ctypes",
"multithreading",
"python"
] | stackoverflow_0004026820_com_ctypes_multithreading_python.txt |
Q:
Python 2.7/Windows resizable ttk progressbar?
I'm experimenting with Python 2.7's new Tkinter Tile support (ttk). Is there a way to make the ttk.Progressbar() control auto-resize in proportion to its parent container? In reading the documentation on this control, it appears that one must explicitly set this widget... | Python 2.7/Windows resizable ttk progressbar? | I'm experimenting with Python 2.7's new Tkinter Tile support (ttk). Is there a way to make the ttk.Progressbar() control auto-resize in proportion to its parent container? In reading the documentation on this control, it appears that one must explicitly set this widget's height or width?
I'm looking for a way to place ... | [
"Try using the fill option of pack (or grid) to have the widget fill its container.\nimport Tkinter as tk\nimport ttk\n\nroot=tk.Tk()\npb = ttk.Progressbar(mode=\"indeterminate\")\npb.pack(side=\"bottom\", fill=\"x\")\npb.start()\nroot.wm_geometry(\"300x300\")\nroot.mainloop()\n\n"
] | [
1
] | [] | [] | [
"progress_bar",
"python",
"tkinter",
"ttk",
"user_interface"
] | stackoverflow_0004027120_progress_bar_python_tkinter_ttk_user_interface.txt |
Q:
single list to dictionary
I have this list:
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
What's the best way to create a dictionary from this?
Thanks.
A:
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(single[::2], single[1::2]))
{'key3': 'value3', 'key2': 'va... | single list to dictionary | I have this list:
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
What's the best way to create a dictionary from this?
Thanks.
| [
">>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']\n>>> dict(zip(single[::2], single[1::2]))\n{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}\n\n",
"Similar to SilentGhost's solution, without building temporary lists:\n>>> from itertools import izip\n>>> single = ['key1', 'value1', 'key2'... | [
11,
8,
2,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004026080_dictionary_list_python.txt |
Q:
How to import protocol buffer definitions from another Python package?
I have my directory structure like this:
root/
sift/
__init__.py
sift_descriptors.proto
sift_descriptors_pb2.py
project/
__init__.py
filtered_descriptors.proto
filtered_descriptors_pb2.py
filtered_descriptors_tes... | How to import protocol buffer definitions from another Python package? | I have my directory structure like this:
root/
sift/
__init__.py
sift_descriptors.proto
sift_descriptors_pb2.py
project/
__init__.py
filtered_descriptors.proto
filtered_descriptors_pb2.py
filtered_descriptors_test.py
The root directory is in my $PYTHONPATH.
I build root/sift/sift_descri... | [
"You don't add .py to the import statement: \"from sift import sift_descriptors_pb2\"\n",
"I fixed it!\nThe solution was to use import \"sift/sift_descriptors.proto\" in filtered_descriptors.proto, and then point protoc to --proto_path=../ instead of --proto_path=../sift.\nThen, protoc generates python code that... | [
1,
1
] | [] | [] | [
"protocol_buffers",
"python"
] | stackoverflow_0004027414_protocol_buffers_python.txt |
Q:
Python version mismatch, but there's just the one app
I have a C/C++ application in which I define a Python module. I set up Python like this:
PyImport_AppendInittab("myModule", initmymodule);
Py_Initialize();
PyObject *module = PyImport_ImportModule("myModule");
On the ImportModule call, I get this warning:
sy... | Python version mismatch, but there's just the one app | I have a C/C++ application in which I define a Python module. I set up Python like this:
PyImport_AppendInittab("myModule", initmymodule);
Py_Initialize();
PyObject *module = PyImport_ImportModule("myModule");
On the ImportModule call, I get this warning:
sys:1: RuntimeWarning: Python C API version mismatch for modu... | [
"Are there any other Pythons installed in /Library/Frameworks/, like ones from a python.org installer?\n"
] | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0004027670_macos_python.txt |
Q:
Optional parameters in OpenERP field definitions
I couldn't find any documentation of the optional parameters that are available to all field types in OpenERP models, so I added what I knew to the fields documentation page.
There are a bunch of parameters that I don't understand, so I'd appreciate help fleshing ou... | Optional parameters in OpenERP field definitions | I couldn't find any documentation of the optional parameters that are available to all field types in OpenERP models, so I added what I knew to the fields documentation page.
There are a bunch of parameters that I don't understand, so I'd appreciate help fleshing out the documentation. You can post answers here, and I'... | [
"Are you sure that they are still in use this fields ? because i just did a find /openerp | grep \"field\" and i didn't find much code that use them ? and because in my experience with openerp the core code is such a mess it's not the first time that i found such a thing (unused code, unused function ...) \nbut her... | [
2
] | [] | [] | [
"odoo",
"python"
] | stackoverflow_0004027231_odoo_python.txt |
Q:
Python exit code in SciTE -1073741819
A small piece of python code breaks/exits with -1073741819 within SciTE.
Is there a way to attach a system sound or anything to alert me on exit.
So far, its a silent break.
A:
Scite has way of configuring various aspects of the editor via properties file.
Some of the pro... | Python exit code in SciTE -1073741819 | A small piece of python code breaks/exits with -1073741819 within SciTE.
Is there a way to attach a system sound or anything to alert me on exit.
So far, its a silent break.
| [
"Scite has way of configuring various aspects of the editor via properties file.\nSome of the properties of interest to you configuring following events for system sound:\nwarning.findwrapped\nwarning.notfound\nwarning.wrongfile\nwarning.executeok\nwarning.executeko\nwarning.nootherbookmark\n\nSee Scite doc: http:/... | [
1
] | [] | [] | [
"audio",
"python",
"scite",
"system"
] | stackoverflow_0004027709_audio_python_scite_system.txt |
Q:
Pythonic Boolean Conversion
I'm writing a module to act on data being sent to a database from Python. Since boolean is not a SQL datatype, those values have to be converted to some pre-defined value. I decided while defining the tables that I would use 'T' and 'F' in a varchar(1) field as my Boolean stand in.
In... | Pythonic Boolean Conversion | I'm writing a module to act on data being sent to a database from Python. Since boolean is not a SQL datatype, those values have to be converted to some pre-defined value. I decided while defining the tables that I would use 'T' and 'F' in a varchar(1) field as my Boolean stand in.
In attempting to make this conversi... | [
"You can use is:\nif SQLParameters[i] is True:\n SQLParameters[i] = 'T' \nelif SQLParameters[i] is False:\n SQLParameters[i] = 'F'\n\n",
"if isinstance(SQLParameters[i], bool):\n SQLParameters[i] = 'T' if SQLParameters[i] else 'F'\n\nor\nif isinstance(SQLParameters[i], bool):\n SQLParam... | [
9,
3,
1,
1,
0,
0
] | [] | [] | [
"boolean",
"database",
"python"
] | stackoverflow_0004027773_boolean_database_python.txt |
Q:
Return minimum X (that can contain Y items) for arbitrary number of items
Feeling pretty brain-dead right now. I can, of course, brute-force this, but I feel like there has to be a simple function to return this number. Concerning native functions, I'm using PHP and/or Python.
For example: there exists containers... | Return minimum X (that can contain Y items) for arbitrary number of items | Feeling pretty brain-dead right now. I can, of course, brute-force this, but I feel like there has to be a simple function to return this number. Concerning native functions, I'm using PHP and/or Python.
For example: there exists containers that hold X (5) breadsticks each, and
I need to feed Y (25) people Z (3) brea... | [
"It sounds like you want arithmetic:\nmin_containers = y*z/x\n\nIf you have situations that may give a remainder:\nmin_full_containers = floor(y*z/x)\nremaining_items = y*z%x\n\n",
"def f(X, Y, Z):\n d, r = divmod(Y * Z, X)\n return d + bool(r)\n\n",
"#python\nimport math\n\nint(math.ceil(float(Y) * Z / X))\n... | [
3,
2,
1,
1,
1
] | [
"($people * $breadSticksPerPerson) / $holders isn't correct?\nEDIT: Sorry, misread your question, posted the correct solution in comments\n"
] | [
-1
] | [
"math",
"php",
"python"
] | stackoverflow_0004027975_math_php_python.txt |
Q:
Numpy array broadcasting with vector parameters
Is it possible to do array broadcasting in numpy with parameters that are vectors?
For example, I know that I can do this
def bernoulli_fraction_to_logodds(fraction):
if fraction == 1.0:
return inf
return log(fraction / (1 - fraction))
bernoulli_fract... | Numpy array broadcasting with vector parameters | Is it possible to do array broadcasting in numpy with parameters that are vectors?
For example, I know that I can do this
def bernoulli_fraction_to_logodds(fraction):
if fraction == 1.0:
return inf
return log(fraction / (1 - fraction))
bernoulli_fraction_to_logodds = numpy.frompyfunc(bernoulli_fraction_... | [
"I don't think frompyfunc can do this, though I could be wrong.\nRegarding np.vectorize A. M. Archibald wrote:\n\nIn fact, anything that goes through\n python code for the \"combine two\n scalars\" will be slow. The slowness of\n looping in python is not because\n python's looping constructs are slow,\n it's b... | [
4,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004024350_numpy_python.txt |
Q:
extract a sentence using python
I would like to extract the exact sentence if a particular word is present in that sentence. Could anyone let me know how to do it with python. I used concordance() but it only prints lines where the word matches.
A:
Just a quick reminder: Sentence breaking is actually a pretty co... | extract a sentence using python | I would like to extract the exact sentence if a particular word is present in that sentence. Could anyone let me know how to do it with python. I used concordance() but it only prints lines where the word matches.
| [
"Just a quick reminder: Sentence breaking is actually a pretty complex thing, there's exceptions to the period rule, such as \"Mr.\" or \"Dr.\" There's also a variety of sentence ending punctuation marks. But there's also exceptions to the exception (if the next word is Capitalized and is not a proper noun, then ... | [
4,
1,
0
] | [] | [] | [
"python",
"text_segmentation"
] | stackoverflow_0004001800_python_text_segmentation.txt |
Q:
OSS implementation of Google app engine?
After Google pioneered map-reduce the community came out with Hadoop, is there a OSS Google AppEngine project? Or, put another way: What is the best off the shelf python or java cloud software?
Specifically I'm looking for something that I could host on my own and have some... | OSS implementation of Google app engine? | After Google pioneered map-reduce the community came out with Hadoop, is there a OSS Google AppEngine project? Or, put another way: What is the best off the shelf python or java cloud software?
Specifically I'm looking for something that I could host on my own and have some sort of auto-scale feature (more frequently u... | [
"I'm not sure what you mean by having an OSS version of Google app engine, but AppScale is an open source framework for running Google app engine apps. You'll have to provide your own cloud, however.\nI think with the right technical expertise and hardware you could host this on your own. Not so sure about auto-sca... | [
9,
5
] | [] | [] | [
"cloud",
"google_app_engine",
"java",
"python"
] | stackoverflow_0004026816_cloud_google_app_engine_java_python.txt |
Q:
Python and win32 API - using a C file
With ActiveState Python comes a win32api module. I need to implement something that monitors directories recursively for file-changes. Actually there's an example in the MSDN library using C. I don't know whether the win32api bindings are sufficient for something like this.
Ca... | Python and win32 API - using a C file | With ActiveState Python comes a win32api module. I need to implement something that monitors directories recursively for file-changes. Actually there's an example in the MSDN library using C. I don't know whether the win32api bindings are sufficient for something like this.
Can I import this into a Python project? Beca... | [
"Why not try some of the python win32 examples here. It uses pywin32 and does what you want.\n\nhttp://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html\n\nThe \"C\" code that you have mentioned with link to MSDN uses FindFirstChangeNotification. Tim Golden's example uses the same through pytho... | [
4,
2
] | [] | [] | [
"c++",
"python",
"winapi"
] | stackoverflow_0004028571_c++_python_winapi.txt |
Q:
Python ignores SIGINT in multithreaded programs - how to fix that?
I have Python 2.6 on MacOS X and a multithread operation. Following test code works fine and shuts down app on Ctrl-C:
import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
sys.exit( 0 )
signal.signal( signal.SIGINT, SigInt... | Python ignores SIGINT in multithreaded programs - how to fix that? | I have Python 2.6 on MacOS X and a multithread operation. Following test code works fine and shuts down app on Ctrl-C:
import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
def run( self ) :
... | [
"I'm not an expert on Threads with Python but quickly reading the docs leads to a few conclusions.\n1) Calling os.system() spawns a new subshell and is not encouraged. Instead the subprocess module should be used. http://docs.python.org/release/2.6.6/library/os.html?highlight=os.system#os.system\n2) The threading m... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004022248_python.txt |
Q:
python regex finding all groups of words
Here is what I have so far
text = "Hello world. It is a nice day today. Don't you think so?"
re.findall('\w{3,}\s{1,}\w{3,}',text)
#['Hello world', 'nice day', 'you think']
The desired output would be ['Hello world', 'nice day', 'day today', 'today Don't', 'Don't you', 'yo... | python regex finding all groups of words | Here is what I have so far
text = "Hello world. It is a nice day today. Don't you think so?"
re.findall('\w{3,}\s{1,}\w{3,}',text)
#['Hello world', 'nice day', 'you think']
The desired output would be ['Hello world', 'nice day', 'day today', 'today Don't', 'Don't you', 'you think']
Can this be done with a simple regex... | [
"map(lambda x: x[0] + x[1], re.findall('(\\w{3,}(?=(\\s{1,}\\w{3,})))',text))\n\nMay be you can rewrite the lambda for shorter (like just '+')\nAnd BTW ' is not part of \\w or \\s\n",
"Something like this with additional checks for list boundaries should do:\n>>> text = \"Hello world. It is a nice day today. Don'... | [
1,
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004028480_python_regex.txt |
Q:
PyQt4: Removing a child from its parent
I've created two uis using the Qt Designer, imported them into my script and set them in the normal way using the setupUi() method. When a button is clicked, and the appropriate method is executed, the new ui is loaded, but all of the widgets and connections from the old one... | PyQt4: Removing a child from its parent | I've created two uis using the Qt Designer, imported them into my script and set them in the normal way using the setupUi() method. When a button is clicked, and the appropriate method is executed, the new ui is loaded, but all of the widgets and connections from the old one persist.
What is the proper way to remove th... | [
"I'm trying to imagine what your goal is here. If you are trying to implement a wizard type application where the screen presents one set of controls and then switches to another screen with forward and backward buttons then you should try using a QStackedWidget.\nA QStackedWidget will allow you to define one or mo... | [
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0004028401_pyqt_pyqt4_python.txt |
Q:
Can an object's methods act on itself?
I'm not sure where to put some methods.
Let's say I want to send an email.
Which of the following options should I choose:
email = new Email("title", "adress", "body");
email.send();
or
email = new Email("title", "adress", "body");
Postman.send(email);
Because how can an em... | Can an object's methods act on itself? | I'm not sure where to put some methods.
Let's say I want to send an email.
Which of the following options should I choose:
email = new Email("title", "adress", "body");
email.send();
or
email = new Email("title", "adress", "body");
Postman.send(email);
Because how can an email send itself? And isn't it better to have... | [
"I disagree with Arseny. An email can send itself, and that's exactly where the code should live. That's what methods are: actions that can be performed on the object.\nHowever, note that your approaches are not mutually incompatible. An email's send action could easily just contain the code to add itself to the Po... | [
8,
3,
2,
1,
1
] | [] | [] | [
"design_patterns",
"javascript",
"oop",
"python",
"ruby"
] | stackoverflow_0004022419_design_patterns_javascript_oop_python_ruby.txt |
Q:
Vim's advance word broken in python, how do I fix this?
Vim works fine for all other languages, but word detection seems wonky in python. For example, in the following snippet, with the cursor on the 'h' in shutil, I would expect prssing the w key to advance me to the period, instead I get moved to the "'" in fron... | Vim's advance word broken in python, how do I fix this? | Vim works fine for all other languages, but word detection seems wonky in python. For example, in the following snippet, with the cursor on the 'h' in shutil, I would expect prssing the w key to advance me to the period, instead I get moved to the "'" in front of export.
shutil.copytree(os.path.join('export', 'app'), o... | [
"Look to see what the option \"iskeyword\" is set to. Chances are the Python syntax file is changing it. Normally it's set to @,48-57,_,192-255.\n"
] | [
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0004028839_python_vim.txt |
Q:
How do I run a python file that is read into a std::string using PyRun
I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.
What I have done is loaded a python.py file a std::string but am now having troubles running it. PyRun_SimpleFileEx didn't ... | How do I run a python file that is read into a std::string using PyRun | I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.
What I have done is loaded a python.py file a std::string but am now having troubles running it. PyRun_SimpleFileEx didn't seem to do the trick either so some help would be great!
std::string con... | [
"I solved my problem by using a string vector and reading each line of the file into the vector, then executing each one using PyRun_SimpleString.\nHere's the finished code, no error checking though.\n std::vector string_vector;\n std::string content;\n if(python_script.empty())\n re... | [
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004028681_c++_python.txt |
Q:
How do I download a zip file in python using urllib2?
Two part question. I am trying to download multiple archived Cory Doctorow podcasts from the internet archive. The old one's that do not come into my iTunes feed. I have written the script but the downloaded files are not properly formatted.
Q1 - What do I chan... | How do I download a zip file in python using urllib2? | Two part question. I am trying to download multiple archived Cory Doctorow podcasts from the internet archive. The old one's that do not come into my iTunes feed. I have written the script but the downloaded files are not properly formatted.
Q1 - What do I change to download the zip mp3 files?
Q2 - What is a better way... | [
"Here's how I'd deal with the url building and downloading. I'm making sure to name the file as the basename of the url (the last bit after the trailing slash) and I'm also using the with clause for opening the file to write to. This uses a ContextManager which is nice because it will close that file when the block... | [
54,
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004028697_python_urllib2.txt |
Q:
Any ideas about the best work around for __new__ losing its arguments?
So, I only realised today that __new__ is deprecated for receiving arguments, as of python 2.6 (it isn't mentioned in the documentation, which is also not true in terms of the behavior of __new__ calling __init__ as far as I can see). This mean... | Any ideas about the best work around for __new__ losing its arguments? | So, I only realised today that __new__ is deprecated for receiving arguments, as of python 2.6 (it isn't mentioned in the documentation, which is also not true in terms of the behavior of __new__ calling __init__ as far as I can see). This means my functional code has started raising warnings, and I want to rid myself ... | [
"__new__ is not \"deprecated for receiving arguments\". What changed in Python 2.6 is that object.__new__, the __new__ method of the object class, no longer ignores any arguments it's passed. (object.__init__ also doesn't ignore the arguments anymore, but that's just a warning in 2.6.) You can't use object as the t... | [
12,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004028321_python.txt |
Q:
Loading New Content with Ajax
This is a situation I've run into several times, not sure what the best approach is.
Let's say I have some kind of dynamic content that users can add to via Ajax. For example, take Stack Overflow's comments - people can add comments directly on to the page using Ajax.
The question is,... | Loading New Content with Ajax | This is a situation I've run into several times, not sure what the best approach is.
Let's say I have some kind of dynamic content that users can add to via Ajax. For example, take Stack Overflow's comments - people can add comments directly on to the page using Ajax.
The question is, how do I implement the addition it... | [
"If the content is simple, I would get JSON and build the HTML in jQuery. If it's complex, I would create a template and call render() on it on the server and return the HTML (which jQuery could either append to other content or replace existing content).\n",
"The reason to update all of the comments is to take i... | [
4,
1,
1
] | [] | [] | [
"ajax",
"django",
"javascript",
"python"
] | stackoverflow_0004027508_ajax_django_javascript_python.txt |
Q:
Getting a Python function to cleanly return a scalar or list, depending on number of arguments
Disclaimer: I'm looking for a Python 2.6 solution, if there is one.
I'm looking for a function that returns a single value when passed a single value, or that returns a sequence when passed multiple values:
>>> a = foo(1... | Getting a Python function to cleanly return a scalar or list, depending on number of arguments | Disclaimer: I'm looking for a Python 2.6 solution, if there is one.
I'm looking for a function that returns a single value when passed a single value, or that returns a sequence when passed multiple values:
>>> a = foo(1)
2
>>> b, c = foo(2, 5)
>>> b
3
>>> c
6
To be clear, this is in an effort to make some function ca... | [
"You can always write a decorator to elide that if statement if that is nicer to you:\nimport functools\ndef unpacked(method):\n @functools.wraps(method)\n def _decorator(*args):\n result = method(*args)\n return results if len(results) != 1 else results[0]\n return _decorator\n\nUsage:\n@unp... | [
7,
6,
0,
0,
0
] | [] | [] | [
"iterable_unpacking",
"python",
"python_2.6",
"python_2.x"
] | stackoverflow_0004029001_iterable_unpacking_python_python_2.6_python_2.x.txt |
Q:
Can't tell if a file exists on a samba share
I know that the file name is file001.txt or FILE001.TXT, but I don't know which. The file is located on a Windows machine that I'm accessing via samba mount point.
The functions in os.path seem to be acting as though they were case-insensitive, but the open function se... | Can't tell if a file exists on a samba share | I know that the file name is file001.txt or FILE001.TXT, but I don't know which. The file is located on a Windows machine that I'm accessing via samba mount point.
The functions in os.path seem to be acting as though they were case-insensitive, but the open function seems to be case-sensitive:
>>> from os.path impor... | [
"You might try adding nocase to the mount in your fstab, as in the example I dug up below if it isn't already there:\n//server/acme/app /home/joe/.wine/drive_c/App cifs guest,rw,iocharset=utf8,nocase,file_mode=0777,dir_mode=0777 0 0\n\nFound a link explaining normcase\n\nnormcase is a useful little f... | [
1,
0,
0
] | [] | [] | [
"case_insensitive",
"python",
"samba"
] | stackoverflow_0004029280_case_insensitive_python_samba.txt |
Q:
python argument taking 3 arguments? Where?
I'm working with the google safebrowsing api, and the following code:
def getlist(self, type):
dlurl = "safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=" + api_key + "&appver=1.0&pver=2.2"
phish = "googpub-phish-shavar"
mal = "goog-mal... | python argument taking 3 arguments? Where? | I'm working with the google safebrowsing api, and the following code:
def getlist(self, type):
dlurl = "safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=" + api_key + "&appver=1.0&pver=2.2"
phish = "googpub-phish-shavar"
mal = "goog-malware-shavar"
self.type = type
if self.ty... | [
"Basically, you didn't supply a method in the url, so Python assumed it was a file URL, and tried to open it as a file--which doesn't work (and throws a confusing error message in the process of failing).\nTry:\ndlurl = \"http://safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=\" + api_key +... | [
4,
0
] | [] | [] | [
"arguments",
"python",
"urllib"
] | stackoverflow_0004029747_arguments_python_urllib.txt |
Q:
Python: How to ensure the last line of code has completed?
I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file has written on the disk then read it. Always, the next line of code fires while the file haven't ... | Python: How to ensure the last line of code has completed? | I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file has written on the disk then read it. Always, the next line of code fires while the file haven't written on disk , and thus error came up. How resolve this?
Oka... | [
"Seems like you just want to check is that there's a file at path before trying to open it.\nYou could check for the path's existence before trying to open it and sleep for a bit if it doesn't exist, but that sleep might not be long enough, and you still might have a problem opening the file.\nYou really should jus... | [
1,
1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004029784_file_python.txt |
Q:
error: [Errno 32] Broken pipe when paypal calls back to python django app
Hi I am doing papal integration with my django app.
i am using latest version of django from svn and python 2.6.
However, i found every time when paypal's sandbox accessing my notify url i got 500 [Errno 32] Broken pipe my django stack.
Does... | error: [Errno 32] Broken pipe when paypal calls back to python django app | Hi I am doing papal integration with my django app.
i am using latest version of django from svn and python 2.6.
However, i found every time when paypal's sandbox accessing my notify url i got 500 [Errno 32] Broken pipe my django stack.
Does anyone have similar experience with this ?
Cheers,
Traceback (most recent call... | [
"The first error Connection reset by peer show you that the connection have been closed by peer (in your case Pypal) and for the Error Broken pipe this error is raised when a connection is closed suddenly without informing the other peer (in your case your machine).\n",
"There are two problems. First, some of th... | [
0,
0
] | [] | [] | [
"django",
"paypal",
"python"
] | stackoverflow_0004029297_django_paypal_python.txt |
Q:
Python text to image generation problems
I'm using PIL to load in various fonts and draw text to images. At the basic level, it all works.
However, I am running into a number of problems such as letters being clipped (mainly cursive or stylistic fonts with lots of tails and such). textsize() does return width/heig... | Python text to image generation problems | I'm using PIL to load in various fonts and draw text to images. At the basic level, it all works.
However, I am running into a number of problems such as letters being clipped (mainly cursive or stylistic fonts with lots of tails and such). textsize() does return width/height values, yet letters are still clipped. Ther... | [
"The Cairo cookbook has a number of examples for using Cairo, and the Python routines are almost mirror images of the C routines.\n",
"I've had some fine results with PyGame, but I don't know if it will necessarily solve your problem.\n"
] | [
2,
0
] | [] | [] | [
"fonts",
"python",
"text"
] | stackoverflow_0004029958_fonts_python_text.txt |
Q:
Django Poll for new records
In ajax I am polling a django url to retrieve the latest records. I do not want to display any records I have retrieved previously and I only want to retrieve 1 record for each poll request.
What would be the best way to do this?
A:
class Article(models.Model):
headline = model... | Django Poll for new records | In ajax I am polling a django url to retrieve the latest records. I do not want to display any records I have retrieved previously and I only want to retrieve 1 record for each poll request.
What would be the best way to do this?
| [
"class Article(models.Model):\n headline = models.CharField(max_length=100)\n pub_date = models.DateField()\n expire_date = models.DateField()\n class Meta:\n get_latest_by = 'pub_date'\n\n>>> from mysite.models import Article\n>>> Article.objects.latest()\n\nIf I'm not wrong in understanding you... | [
2,
0
] | [] | [] | [
"django",
"polling",
"python"
] | stackoverflow_0004029807_django_polling_python.txt |
Q:
Overwriting default behavior for python operators
I know that to alter the default behavior of operators in python you can override some default methods like __add__ or __sub__ for + and -, but didn't find anything to override the behavior of the and and or keywords, while there are some for the bitwise operators ... | Overwriting default behavior for python operators | I know that to alter the default behavior of operators in python you can override some default methods like __add__ or __sub__ for + and -, but didn't find anything to override the behavior of the and and or keywords, while there are some for the bitwise operators &, |: respectively __and__ and __or__.
Do you know if t... | [
"is, and, and or cannot be overloaded. Use the Python language services if you want to write a Pythonesque DSL.\n"
] | [
2
] | [] | [] | [
"dynamic_languages",
"python"
] | stackoverflow_0004030153_dynamic_languages_python.txt |
Q:
Decimal to JSON
I'm pulling a sum from a DB which is a decimal value.
I'm trying to use that value in a JSON result
json.dumps( { 'sum': amount } ) #where amount is my Decimal
Django can't serialize the Decimal.
I can convert it to a string, but I'd like a numeric type within the JSON.
If I try and convert it to ... | Decimal to JSON | I'm pulling a sum from a DB which is a decimal value.
I'm trying to use that value in a JSON result
json.dumps( { 'sum': amount } ) #where amount is my Decimal
Django can't serialize the Decimal.
I can convert it to a string, but I'd like a numeric type within the JSON.
If I try and convert it to a float I end up with... | [
"What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, similar to the example in this document: http://docs.python.org/py3k/library/json.html\n>>> import json\n>>> class DecimalEncoder(json.JSONEncoder):\n... def default(self, obj):\n... if isinstance(obj, ... | [
12,
0,
0
] | [
"There's no such thing as a Decimal type in Javascript, and also among the standard types in python. It is a database-spcific type and not part of JSON. Take Float or do an integer arithmetic.\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0004019856_django_python.txt |
Q:
How to set PATH to use Java and Python simultaneously
I was just wondering if there was any way to set to %PATH% variables so I can compile my Java code, along with my Python code?
For instance.. PATH is currently C:\ ... JDK_bin blah blah, and that's it. To run my python code, I have to change my path variable co... | How to set PATH to use Java and Python simultaneously | I was just wondering if there was any way to set to %PATH% variables so I can compile my Java code, along with my Python code?
For instance.. PATH is currently C:\ ... JDK_bin blah blah, and that's it. To run my python code, I have to change my path variable completely.
Any answers?
| [
"Just add a semicolon after your present path, and write the new one after that.\nset PATH=\"C:\\Program Files\\Java\\blah\\blah\";C:\\Python31\\;C:\\Windows\\System32\n\netc...\n",
"You need to add the path to python exe to your existing PATH variable which already has path to Java exes and many more paths in it... | [
9,
7,
4
] | [] | [] | [
"java",
"path",
"python",
"windows"
] | stackoverflow_0004030440_java_path_python_windows.txt |
Q:
Why doesn't a %en0 suffix work to connect a link-local IPv6 TCP socket in Python?
A week or so ago someone on StackOverflow asked why their Python code for connecting to an IPv6 link-local address wasn't working, and I replied that since it was a link-local address they needed to add a %en0 (or whatever the desire... | Why doesn't a %en0 suffix work to connect a link-local IPv6 TCP socket in Python? | A week or so ago someone on StackOverflow asked why their Python code for connecting to an IPv6 link-local address wasn't working, and I replied that since it was a link-local address they needed to add a %en0 (or whatever the desired local-interface-name is) suffix to their target IP address. I thought I knew what I ... | [
"This is the correct way to do an ipv6 connection:\n>>> addrinfo = getaddrinfo('fe80::225:ff:fecd:5aa0%en0', 2001, AF_INET6, SOCK_STREAM)\n>>> addrinfo\n[(30, 1, 6, '', ('fe80::225:ff:fecd:5aa0%en0', 2001, 0, 4))]\n>>> (family, socktype, proto, canonname, sockaddr) = addrinfo[0]\n>>> s = socket(family, socktype, pr... | [
13
] | [] | [] | [
"ipv6",
"link_local",
"python",
"scope_id",
"tcp"
] | stackoverflow_0004030269_ipv6_link_local_python_scope_id_tcp.txt |
Q:
signal.alarm() handler causing problem with pyserial
so i have a motion sensor connected to an avr micro that is communicating with my python app via usb. im using pyserial to do the comm. during my script i have an infinate loop checking for data from the avr micro. before this loop i start a timer with signal.al... | signal.alarm() handler causing problem with pyserial | so i have a motion sensor connected to an avr micro that is communicating with my python app via usb. im using pyserial to do the comm. during my script i have an infinate loop checking for data from the avr micro. before this loop i start a timer with signal.alarm() that will call a function to end a subprocess. when ... | [
"The problem is that your alarm will interrupt the read from the serial port, which isn't at all what you want.\nIt sounds like you probably want to break this into two threads that do work separately.\n",
"You are using alarm(), which send a signal, and pyserial, which does reads and writes to a serial port. Whe... | [
0,
0
] | [] | [] | [
"alarm",
"pyserial",
"python",
"signals"
] | stackoverflow_0004030296_alarm_pyserial_python_signals.txt |
Q:
django multiple select in admin change-list
Our product model can have multiple campaigns. Our customers change these campaigns frequently and generally on multiple products. So what we need right now seems that we need to show a multiple select widget on a change-list of Product model where our customers can easi... | django multiple select in admin change-list | Our product model can have multiple campaigns. Our customers change these campaigns frequently and generally on multiple products. So what we need right now seems that we need to show a multiple select widget on a change-list of Product model where our customers can easily change the campaigns.
Any idea on this? Maybe... | [
"say you have a product model\n\n\nclass Product(models.Model):\n name=models.CharField(max_length=20)\n cost=models.DecimalField(max_length=10)\n\n\n\n\nyou can subclass the admin's Modeladmin to show a list display for the products or you can do a custom modelform for the product which you can call in the prod... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004013733_django_django_admin_django_models_python.txt |
Q:
AppEngine fetch through a free proxy
My (Python) AppEngine program fetches a web page from another site to scrape data from it -- but it seems like the 3rd party site is blocking requests from Google App Engine! -- I can fetch the page from development mode, but not when deployed.
Can I get around this by using a ... | AppEngine fetch through a free proxy | My (Python) AppEngine program fetches a web page from another site to scrape data from it -- but it seems like the 3rd party site is blocking requests from Google App Engine! -- I can fetch the page from development mode, but not when deployed.
Can I get around this by using a free proxy of some sort?
Can I use a free ... | [
"Probably the correct approach is to request permission from the owners of the site you are scraping. \nEven if you use a proxy, there is still a big chance that requests coming through the proxy will end up blocked as well.\n",
"Have you considered changing the user-agent?\nresult = urlfetch.fetch(u,headers = {'... | [
2,
1,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"proxy",
"python"
] | stackoverflow_0002050256_google_app_engine_proxy_python.txt |
Q:
Form is not running after adding fields in it
Hie friends, I made a form using the class forms.py it was running smoothly, but next time when I added two new fields in that forms.py class then on executing the command "python manage.py syncdb " it gives me the following error:
Traceback (most recent call last):
... | Form is not running after adding fields in it | Hie friends, I made a form using the class forms.py it was running smoothly, but next time when I added two new fields in that forms.py class then on executing the command "python manage.py syncdb " it gives me the following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute... | [
"Making changes to forms does not affect you database schema, there is no need to run syncdb after changing a form. \nThe error you are receiving has its roots elsewhere.\n",
"it seems the problem is not with your forms.py but with your sqlite database file.can you delete the sqlite database file and syncdb agai... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004030086_django_python.txt |
Q:
Generate Python function in runtime and invoke them with string name
foo.py
def foo_001(para): tmp = para + 2 return tmp
def foo_002(para): tmp = para * 2 return tmp
def foo_003(para): tmp = para / 2 return tmp
...
def foo_100(para): tmp = #complex algo, return tmp
main.py
from foo import *
fun_name = ["fo... | Generate Python function in runtime and invoke them with string name | foo.py
def foo_001(para): tmp = para + 2 return tmp
def foo_002(para): tmp = para * 2 return tmp
def foo_003(para): tmp = para / 2 return tmp
...
def foo_100(para): tmp = #complex algo, return tmp
main.py
from foo import *
fun_name = ["foo_001","foo_002","foo_002" ... "foo_100"]
src = 1
rzt = []
for i in f... | [
"fnmap = {\n 'foo_001': foo_001,\n 'foo_002': foo_002,\n 'foo_003': foo_003,\n}\n\nprint fnmap['foo_002'](3)\n\nUse a decorator to enumerate the functions if you don't feel like typing out the whole map.\n"
] | [
0
] | [] | [] | [
"function",
"python",
"runtime"
] | stackoverflow_0004030729_function_python_runtime.txt |
Q:
Using Python to read images from a www.flickr.com account
Ok, so I need to build this application where I'll read images from a www.flickr.com account and use the images in my Python app. How will I do that? Any ideas? Thanks.
A:
You could use one of the various flickr python libraries :
http://code.google.com... | Using Python to read images from a www.flickr.com account | Ok, so I need to build this application where I'll read images from a www.flickr.com account and use the images in my Python app. How will I do that? Any ideas? Thanks.
| [
"You could use one of the various flickr python libraries :\n\nhttp://code.google.com/p/flickrpy/\nhttp://pypi.python.org/pypi/Flickr.API/\nhttp://stuvel.eu/projects/flickrapi\n\nAnd for a good overview of flickr API, always look at the docs: http://www.flickr.com/services/api/\nAn example:\nimport flickrapi\napi_k... | [
9
] | [] | [] | [
"flickr",
"python"
] | stackoverflow_0004030824_flickr_python.txt |
Q:
Difference between qt and PyQt4
Well I am new to Qt and found its easier to work with python , I dont know how far its true .
but some of the code snippets have
import qt
and some have
import PyQt4
I don't know what the difference is, when I tried to interchange them I did get some errors , like some func... | Difference between qt and PyQt4 | Well I am new to Qt and found its easier to work with python , I dont know how far its true .
but some of the code snippets have
import qt
and some have
import PyQt4
I don't know what the difference is, when I tried to interchange them I did get some errors , like some function was not recognizable and so on, ... | [
"Old PyQt3 use qt\nimport qt\n\nCurrent PyQt4 use PyQt4\nimport PyQt4\n\nIf you use PySide, use PySide\nimport PySide\n\n"
] | [
5
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0004025849_pyqt4_python_qt.txt |
Q:
Why does Python complain about reference before assignment when increasing variables in a function?
Why does Python complain about chrome being referenced before assignment? It does not complain about the dictionary. This is with Python 2.5 if it makes a difference.
def f():
google['browser'] = 'chrome'
chrome... | Why does Python complain about reference before assignment when increasing variables in a function? | Why does Python complain about chrome being referenced before assignment? It does not complain about the dictionary. This is with Python 2.5 if it makes a difference.
def f():
google['browser'] = 'chrome'
chrome += 1
google = dict()
chrome = 1
f()
I can make it work with global chrome of course, but I'd like to k... | [
"In the statement \nchrome += 1\n\nand it has not been created yet. \nThe variables are created the first time they are assigned. In this case, when python sees the code incrementing 'chrome', it doesn't see this variable at all.\nTry rearranging your code as\nchrome = 1\n\ndef f():\n global chrome\n google['brow... | [
5,
-1
] | [] | [] | [
"function",
"python",
"variables"
] | stackoverflow_0004030968_function_python_variables.txt |
Q:
Initialise class object by name
Since everything in python is an object, i was wondering if there was a way i could initialise a class object using the name of the class
for example,
class Foo:
"""Class Foo"""
How could i access this class by "Foo", ie something like c = get_class("Foo")
A:
If the class is... | Initialise class object by name | Since everything in python is an object, i was wondering if there was a way i could initialise a class object using the name of the class
for example,
class Foo:
"""Class Foo"""
How could i access this class by "Foo", ie something like c = get_class("Foo")
| [
"If the class is in your scope:\nget_class = lambda x: globals()[x]\n\nIf you need to get a class from a module, you can use getattr:\nimport urllib2\nhandlerClass = getattr(urllib2, 'HTTPHandler')\n\n",
"Have you heard of the inspect module?\nCheck out this snippet I found.\n"
] | [
44,
1
] | [
"I think your searching reflection \nsee http://en.wikipedia.org/wiki/Reflection_%28computer_science%29#Python\nOr a better Example from the german wikipedia:\n>>> # the object\n>>> class Person(object):\n... def __init__(self, name):\n... self.name = name\n... def say_hello(self):\n... return '... | [
-2
] | [
"python"
] | stackoverflow_0004030982_python.txt |
Q:
Python : is there a shortcut for pattern [sth = get_sth() ; if sth: do_a_thing_on(sth)]
HI !
I guess everything is in the question ...
I was just wondering if there is a nice way in Python to shorten this pattern :
something = get_something()
if something:
do_a_thing_with(something)
Meaning that I would like ... | Python : is there a shortcut for pattern [sth = get_sth() ; if sth: do_a_thing_on(sth)] | HI !
I guess everything is in the question ...
I was just wondering if there is a nice way in Python to shorten this pattern :
something = get_something()
if something:
do_a_thing_with(something)
Meaning that I would like to enter in the if context only if the variable something is not None (or False), and then i... | [
"This is as pythonic as it gets. \nThings should be no more simplified than they are and no more complex than they should be. \nSee how the with statement works and providing a context guard. would be complicated enough.\n\nhttp://effbot.org/pyref/with.htm\nhttp://effbot.org/pyref/context-managers.htm\n\n",
"If i... | [
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004031106_python.txt |
Q:
Possible to programmatically ALTER multiple MySQL tables?
I have multiple MySQL tables with names of the form "Shard_0", "Shard_1", "Shard_2" ... "Shard_n" All of them have identical table structure. They all live in the same database.
Say I want to add a column to all those tables. Is there a way to do that progr... | Possible to programmatically ALTER multiple MySQL tables? | I have multiple MySQL tables with names of the form "Shard_0", "Shard_1", "Shard_2" ... "Shard_n" All of them have identical table structure. They all live in the same database.
Say I want to add a column to all those tables. Is there a way to do that programmatically?
Something like:
# pseudo code
for i in range(... | [
"No problem. Python has several third party libraries to connect to a db. But the simplest approach if you have to do this for just one time would be a python script that writes the SQL instructions just to stdout:\nfor i in range(n):\n tablename = \"shard_\"+str(i)\n print 'ALTER TABLE tablename ...'\n\nThen... | [
4,
1,
0
] | [] | [] | [
"database",
"database_administration",
"mysql",
"python",
"schema"
] | stackoverflow_0004030579_database_database_administration_mysql_python_schema.txt |
Q:
Python Syntax doubt
Hey, I have been using the Pymt library and they have this convention to referring their widgets:
from pymt import *
# create a slider from 0.-1.
sl = MTXYSlider()
@sl.event
def on_value_change(x, y):
print 'Slider value change', x, y
runTouchApp(sl)
what's with the "@"? What does it si... | Python Syntax doubt | Hey, I have been using the Pymt library and they have this convention to referring their widgets:
from pymt import *
# create a slider from 0.-1.
sl = MTXYSlider()
@sl.event
def on_value_change(x, y):
print 'Slider value change', x, y
runTouchApp(sl)
what's with the "@"? What does it signify in Python?Thanks.
| [
"It signifies a decorator\n",
"basically it is a function that takes another function as an argument . if is a way python implements a Decorator Pattern. \nthe equivalent code would be \n\n\nsl.event(on_value_change(x, y))\n\n\n\n\n\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004031288_python.txt |
Q:
Why does my python interactive console not work properly?
I made a very simple interactive console that I'd like to use in a complicated scraping application. It looks like this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs, code
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sy... | Why does my python interactive console not work properly? | I made a very simple interactive console that I'd like to use in a complicated scraping application. It looks like this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs, code
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sys.__stderr__ = codecs.getwriter('utf8')(sys.__stderr__)
if 'DE... | [
"OK, I found out it was ME that was causing the problem, my older boiler-plate code used to this before I noticed it causing problems in some cases:\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\nsys.stderr = codecs.getwriter('utf8')(sys.stderr)\n\nThat old code was still present in one of my own files, changi... | [
3
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0004031135_python_readline.txt |
Q:
How to get the convert a Jython class to Java class in Jython intepreter?
I am trying to register a User Defined Function with Esper API. It take a class or string type arguement
http://esper.codehaus.org/esper-4.0.0/doc/api/com/espertech/esper/client/ConfigurationOperations.html#addImport(java.lang.String)
class ... | How to get the convert a Jython class to Java class in Jython intepreter? | I am trying to register a User Defined Function with Esper API. It take a class or string type arguement
http://esper.codehaus.org/esper-4.0.0/doc/api/com/espertech/esper/client/ConfigurationOperations.html#addImport(java.lang.String)
class MyUdf():
@staticmethod
def udf():
return 50
conf.addImport(myu... | [
"I don't think this is possible. Jython classes are not Java classes, and as far as I can tell there's no pure-jython mechanism to corce it.\nGenerally, I would say that you should take the object factory method mentioned in the Jython book, and combine with a proxy class, which is what you'd pass as the parameter.... | [
0
] | [] | [] | [
"esper",
"java",
"jython",
"python"
] | stackoverflow_0003850493_esper_java_jython_python.txt |
Q:
python semantic proxy/server, which framework to use?
This year me and a friend have to make a project for the final year of university. The plan is to make a proxy/sever that allows to store ontologies and RDF's, by this way this data is "chained" to a web, so you can make a request for that web and the proxy wil... | python semantic proxy/server, which framework to use? | This year me and a friend have to make a project for the final year of university. The plan is to make a proxy/sever that allows to store ontologies and RDF's, by this way this data is "chained" to a web, so you can make a request for that web and the proxy will send you the homepage with metadata.
We have been thinkin... | [
"I have developed several Web applications with Python framworks consuming RDF data. The choice always depends on the performance needed and the amount of data you'll have to handle.\nIf the number of triples you'll handle is in the magnitude of few thousands then you can easily put together a framework with RDFlib... | [
3
] | [] | [] | [
"proxy",
"python",
"rdf",
"semantics"
] | stackoverflow_0004031393_proxy_python_rdf_semantics.txt |
Q:
Removing non-english words from a sentence in python
I have written a code which sends queries to Google and returns the results. I extract the snippets(summaries) from these results for further processing. However, sometime non-english words are in these snippets which I don't want them. for example:
/\u02b0w\u02... | Removing non-english words from a sentence in python | I have written a code which sends queries to Google and returns the results. I extract the snippets(summaries) from these results for further processing. However, sometime non-english words are in these snippets which I don't want them. for example:
/\u02b0w\u025bn w\u025bn unstressed \u02b0w\u0259n w\u0259n/
I only ... | [
"PyEnchant might be a simple option for you. I do not know about its speed, but you can do things like:\n>>> import enchant\n>>> d = enchant.Dict(\"en_US\")\n>>> d.check(\"Hello\")\nTrue\n>>> d.check(\"Helo\")\nFalse\n>>>\n\nA tutorial is found here, it also has options to return suggestions which you can you again... | [
4,
1,
1
] | [] | [] | [
"non_english",
"python",
"unicode"
] | stackoverflow_0004031556_non_english_python_unicode.txt |
Q:
ArcGIS python 2.5 script - create a stats table by iterating the recordset
I need to iterate the fields and compute sum of few columns group by the value in another column .
For ex base table is
C1 C2 C3 C4 C5
a1 2 3 4 q
a1 4 5 7 a
a2 34 56 6 e
a2 4 5 5 5
a3 3 3 3 4
a3 3 3 3 3
The resu... | ArcGIS python 2.5 script - create a stats table by iterating the recordset | I need to iterate the fields and compute sum of few columns group by the value in another column .
For ex base table is
C1 C2 C3 C4 C5
a1 2 3 4 q
a1 4 5 7 a
a2 34 56 6 e
a2 4 5 5 5
a3 3 3 3 4
a3 3 3 3 3
The result table should be
c2 c3 c4
a1 6 8 11
a2 38 61 11
a3 6 6 6
50 75 28
I... | [
"Working from a lot of assumptions here since the question is quite unspecific...\n# table containing only the actual data\ntable = [[2,3,4,\"q\"],[4,5,7,\"a\"],[34,56,6,\"e\"],[4,5,5,5],[3,3,3,4],[3,3,3,3]]\nresult = []\n\n# iterate through table[0/2/4/...] zipped together with table[1/3/5/...]\nfor (row1, row2) i... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004031550_python.txt |
Q:
Python WSGI deployment on Windows for CPU-bound application
What options do I have for the deployment of a CPU bound Python-WSGI application on Windows?
The application benefits greatly from multiple CPUs (image manipulation/encoding) but the GIL prevents it from using them.
My understanding is:
mod_wsgi has no s... | Python WSGI deployment on Windows for CPU-bound application | What options do I have for the deployment of a CPU bound Python-WSGI application on Windows?
The application benefits greatly from multiple CPUs (image manipulation/encoding) but the GIL prevents it from using them.
My understanding is:
mod_wsgi has no support for WSGIDaemonProcess on Windows and Apache itself only ru... | [
"I have successfully used isapi-wsgi to deploy WSGI web apps on Windows IIS (I assume that since you're deploying on Windows, IIS is an option).\nCreate an IIS Application Pool to host your application in and configure it as a Web Garden (Properties | Performance | Maximum number of worker processes).\nDisclaimer: ... | [
1,
0
] | [] | [] | [
"mod_wsgi",
"python",
"windows",
"wsgi"
] | stackoverflow_0004012621_mod_wsgi_python_windows_wsgi.txt |
Q:
About the image size that generated from matplotlib
I generated a histogram by using matplotlib
import numpy as np
import pylab as P
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
P.figure()
bins = 10
n, bins, patches = P.hist(x, bins, normed=1, histtype='bar', rwidth=0.8)
P.show()
I want to make the picture... | About the image size that generated from matplotlib | I generated a histogram by using matplotlib
import numpy as np
import pylab as P
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
P.figure()
bins = 10
n, bins, patches = P.hist(x, bins, normed=1, histtype='bar', rwidth=0.8)
P.show()
I want to make the picture smaller, how could I do that?
Thanks for your help
| [
"If you just want to set it for this specific figure, then change your figure declaration to:\nP.figure(figsize=(i,j))\n\nwhere i is the width in inches and j is the height in inches.\n",
"In addition to specifying the figsize, there's also a dpi option - although this is more important if you're using one of the... | [
4,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004012047_matplotlib_python.txt |
Q:
Is python logger thread-safe or not?
Is python logger thread-safe or not? I use python 2.6.
A:
Yes, it is thread-safe, but there are some cautions in the documentation that you need to be aware of. Search for "thread" in this page.
A:
Yes it is.
A:
Seems to be:
http://chrisrbennett.com/2008/04/python-logger-... | Is python logger thread-safe or not? | Is python logger thread-safe or not? I use python 2.6.
| [
"Yes, it is thread-safe, but there are some cautions in the documentation that you need to be aware of. Search for \"thread\" in this page.\n",
"Yes it is.\n",
"Seems to be:\nhttp://chrisrbennett.com/2008/04/python-logger-config-thread-safety.html\nNot sure he's talking about 2.6 though.\n"
] | [
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004032155_python.txt |
Q:
slow File Processing in python
I am trying a file operation using python.Aim is to continuously read a file of size(100bytes),pack and send them through socket. These files are read from a directory.
Problem: when i run the program continuously, execution time is increasing. Initially, execution time is less than ... | slow File Processing in python | I am trying a file operation using python.Aim is to continuously read a file of size(100bytes),pack and send them through socket. These files are read from a directory.
Problem: when i run the program continuously, execution time is increasing. Initially, execution time is less than a second; later it reaches till 8~10... | [
"From what I see, packMessage is growing monotonically:\npackMessage = packMessage + struct.pack(\"<b\",msg[i])\n\nIf you repeat it many times, it may grow big, consume a lot of memory, and at some point your application may become much slower. Try looking at top or htop when you run your program (in top, press M ... | [
4,
3
] | [] | [] | [
"file_handling",
"python"
] | stackoverflow_0004032012_file_handling_python.txt |
Q:
How save implement class in python?
I have instance of the my class. I want to save implementation of class with instance's pickle copy in file. After, I want to use this instance to another computer where there is no implementation of the my class. I don't want to save text of implementation manually.
How can I d... | How save implement class in python? | I have instance of the my class. I want to save implementation of class with instance's pickle copy in file. After, I want to use this instance to another computer where there is no implementation of the my class. I don't want to save text of implementation manually.
How can I do this?
| [
"Use a dict instead of a class.\n",
"If you don't want to copy your source code to the \"other computer\" then the best best is to use native data structures, i.e. dict or list or tuples etc.\nPack what ever you want to pack & store it in these data structures, then simply do this -\nimport pickle\n\ndef save_to_... | [
0,
0
] | [] | [] | [
"class",
"python",
"serialization"
] | stackoverflow_0004031453_class_python_serialization.txt |
Q:
Changing the key name of an entity
I understand that they are not supposed to be changed, this is somewhat of a schema migration and only a one-time thing.
I would like to change the key names of entities in my Google App Engine application, effectively deleting and re-crating an entity and updating all references... | Changing the key name of an entity | I understand that they are not supposed to be changed, this is somewhat of a schema migration and only a one-time thing.
I would like to change the key names of entities in my Google App Engine application, effectively deleting and re-crating an entity and updating all references to it.
What is the best way to do this?... | [
"Since changing the key name is functionally identical to creating a new, identical entity with that key, what you want to do is clone the entity with the new key. Here's some code that does just that.\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004032247_google_app_engine_python.txt |
Q:
what is the fastest way to update thousands rows in mysql
lets assume you have a table with 1M rows and growing ...
every five minutes of every day you run a python programm which have to update some fields of 50K rows
my question is: what is the fastest way to do the work?
runs those updates in loop and after ... | what is the fastest way to update thousands rows in mysql |
lets assume you have a table with 1M rows and growing ...
every five minutes of every day you run a python programm which have to update some fields of 50K rows
my question is: what is the fastest way to do the work?
runs those updates in loop and after last one is executed than fire up a cursor commit?
or generate... | [
"Here's some ways you could speed up your UPDATES.\nWhen you UPDATE, the table records are just being rewritten with new data. And all this must be done again on INSERT. That's why you should always use INSERT ... ON DUPLICATE KEY UPDATE instead of REPLACE.\nThe former one is an UPDATE operation in case of a key vi... | [
4,
0
] | [] | [] | [
"mysql",
"performance",
"python"
] | stackoverflow_0004031814_mysql_performance_python.txt |
Q:
Pip, Virtualenv & Git project setup and bootstrapping
Assuming you have a project setup like this:
-WebApp
|_ requirements.txt
|_ bootstrap.py (virtualenv bootstrap script)
|_ src
|_ setup.py
|_ develop-app
|_ somecode.py
|_ morecode.py
The bootstrap.py is created ... | Pip, Virtualenv & Git project setup and bootstrapping | Assuming you have a project setup like this:
-WebApp
|_ requirements.txt
|_ bootstrap.py (virtualenv bootstrap script)
|_ src
|_ setup.py
|_ develop-app
|_ somecode.py
|_ morecode.py
The bootstrap.py is created with virtualenv:
https://virtualenv.pypa.io/en/latest/refer... | [
"How about not adding your develop app to the requirements.txt list.. and just run the code from your git repro? The point of requirements is to specify which requirements your development app has right? It is rather strange to me to make it require itself.\n"
] | [
4
] | [] | [] | [
"development_environment",
"pip",
"python",
"virtualenv"
] | stackoverflow_0003996708_development_environment_pip_python_virtualenv.txt |
Q:
python hex hmac md5 of passwords not matching javascript
i have a javascript password coder
md5 = hex_hmac_md5(secret, password)
How can i emulate this in python - ive tried md5 but that is not the same value
i got my md5 javascript code from this website:
Pajs Home
(md5.js)
He states the use is as follows:
... | python hex hmac md5 of passwords not matching javascript | i have a javascript password coder
md5 = hex_hmac_md5(secret, password)
How can i emulate this in python - ive tried md5 but that is not the same value
i got my md5 javascript code from this website:
Pajs Home
(md5.js)
He states the use is as follows:
In many uses of hashes you end up
wanting to combine a key w... | [
"That's what Python's hmac module is for, don't use the MD5 function directly.\n# Right\nimport hmac\n# Note that hmac.new defaults to using MD5\nhmac.new(\"password\", \"message\").hexdigest() # 'f37438341e3d22aa11b4b2e838120dcf'\n\n# Wrong\nfrom hashlib import md5\nmd5(\"message\"+\"password\").hexdigest() # 'd06... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004032694_python.txt |
Q:
Is it possible for my Mercurial hook to call code from another file?
I have a hook function named precommit_bad_branch which imports hook_utils. When invoking precommit_bad_branch via a commit I get the following error message:
error: precommit.branch_check hook raised an exception: No module named hook_utils
abor... | Is it possible for my Mercurial hook to call code from another file? | I have a hook function named precommit_bad_branch which imports hook_utils. When invoking precommit_bad_branch via a commit I get the following error message:
error: precommit.branch_check hook raised an exception: No module named hook_utils
abort: No module named hook_utils!
It looks like I'm not allowed to call hook... | [
"Put the C:\\workspaces\\hg_hooks directory in your PYTHONPATH and you will be able to write\n[hooks]\nprecommit.branch_check = python:next_hooks.precommit_bad_branch\n\nin your configuration file and you will also be able to do\nimport hook_utils\n\ninside any Python file, including the next_hooks.py file.\nAltern... | [
2
] | [] | [] | [
"mercurial",
"mercurial_hook",
"python",
"python_import"
] | stackoverflow_0004031290_mercurial_mercurial_hook_python_python_import.txt |
Q:
How to find all words that have the same appearence in two different languages?
The russian alphabet includes many letters that are the same in the English alphabet. Here is the list of common letters: L='acekopuxy'
Now, given two huge lists R and E, each in the form [word_A, word_B, ...], where each word_N is a... | How to find all words that have the same appearence in two different languages? | The russian alphabet includes many letters that are the same in the English alphabet. Here is the list of common letters: L='acekopuxy'
Now, given two huge lists R and E, each in the form [word_A, word_B, ...], where each word_N is a lowercase word, I want to create a list C, which should contain only those words tha... | [
"You can use sets for this:\nenglish_set = set(E)\nrussian_set = set(R)\ncommon_words = english_set.intersection(russian_set)\n\nI'm not sure I got the encoding part right though, but if that means letters that look similar are actually different bytes, you can for example prepare the russian list by replacing thes... | [
3,
1,
1,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0004032835_algorithm_python.txt |
Q:
Serialize django model with foreign key models
How to serialize Django model in json format if I want to include foreign key models fields?
If I have:
class Model1(models.Model):
name=models.CharField()
child=models.ForeignKey(Model2)
class Mode2(models.Model):
field1=models.CharField()
field2=mod... | Serialize django model with foreign key models | How to serialize Django model in json format if I want to include foreign key models fields?
If I have:
class Model1(models.Model):
name=models.CharField()
child=models.ForeignKey(Model2)
class Mode2(models.Model):
field1=models.CharField()
field2=models.IntegerField()
I wanna include everything in js... | [
"I had similar problems so I took some code that I had done before, and improved it. It actually ended-up in a full python serialization framework SpitEat. You can download an try it here. The documentation is not very good yet, so here is the code you have to use to serialize your thing :\n>>> from spiteat.djangos... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004015229_django_python.txt |
Q:
Closing Perspective Broker connection in Twisted
I have program which has servers interacting with each other using Twisted's remote procedure calls, and I run in problems with closing connections when they are not needed anymore. Connections should be able to close itself in both sides.
Case 1: How do I close con... | Closing Perspective Broker connection in Twisted | I have program which has servers interacting with each other using Twisted's remote procedure calls, and I run in problems with closing connections when they are not needed anymore. Connections should be able to close itself in both sides.
Case 1: How do I close connection in connecting part?
factory = pb.PBClientFacto... | [
"Another option is reference.broker.transport.loseConnection(). \nRemoteReference instances which are created over a PB connection are given a broker attribute. The broker attribute refers to the protocol instance that created them. As usual for a protocol, the broker has a transport attribute, and the transport... | [
1
] | [] | [] | [
"python",
"rpc",
"twisted"
] | stackoverflow_0004032699_python_rpc_twisted.txt |
Q:
django-piston : Overriding default serialization in emitters
I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.
More precisely, my models are subclassed from a special Model class, which inherits from django.... | django-piston : Overriding default serialization in emitters | I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.
More precisely, my models are subclassed from a special Model class, which inherits from django.db.models.base.ModelBase, but cannot be serialized as regular djan... | [
"You can do the serialization yourself. The handlers only expect and return a python dictionary. For this though, you can't just plug it into a model. Create your own resource handler for your base type, which is capable of building your Model from a dict.\nclass ModelHandler(HandlerBase):\n allowed_methods = ('... | [
1,
1
] | [] | [] | [
"django",
"django_piston",
"python",
"serialization"
] | stackoverflow_0003966490_django_django_piston_python_serialization.txt |
Q:
Stopping an application (punjab) that is run using Twisted
I am trying to run punjab connection manager with very less python knowledge. I followed the punjab docs and can start the application. But how do I stop/restart it ?
twistd -y punjab.tac
starts punjab first time but after that if I enter the same comman... | Stopping an application (punjab) that is run using Twisted | I am trying to run punjab connection manager with very less python knowledge. I followed the punjab docs and can start the application. But how do I stop/restart it ?
twistd -y punjab.tac
starts punjab first time but after that if I enter the same command , it says
Another twistd server is running, PID 3726.
Precise... | [
"A server started with twistd is stopped in the somewhat typical UNIX fashion: send it a signal - INT is a good first choice:\nkill -INT 3726\n\nThis should initiate shutdown. You can check in the log file, generally twistd.log in the same directory as you started the server.\nSince the PID of the running process ... | [
5
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0004032839_python_twisted.txt |
Q:
Django and MongoDB Engine - Problem with object IDs!
I'm using Django 1.3beta and django-mongodb-engine for database backend.
Problem is when I save an object with a pk set I get this error:
/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.pyc in get_prep_lookup(self, lookup_type, value)
... | Django and MongoDB Engine - Problem with object IDs! | I'm using Django 1.3beta and django-mongodb-engine for database backend.
Problem is when I save an object with a pk set I get this error:
/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.pyc in get_prep_lookup(self, lookup_type, value)
290 return value
291 elif lookup_... | [
"You'll need django-nonrel fork of django. If you'll follow the link you've posted, you'll see it's specified in \"Requirements\"\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"mongodb",
"python"
] | stackoverflow_0004031788_django_django_models_mongodb_python.txt |
Q:
what would be a quick way to do nested splitting of brackets in python?
I have a file of the following format:
ID1 { some text }
ID2 { some text }
They don't have to come line by line format, so that we can have:
ID1 { some [crlf]
text [crlf]
}
ID2 [crlf] { some t [crlf]
ex [crlf]
t}
and so on, meaning some tex... | what would be a quick way to do nested splitting of brackets in python? | I have a file of the following format:
ID1 { some text }
ID2 { some text }
They don't have to come line by line format, so that we can have:
ID1 { some [crlf]
text [crlf]
}
ID2 [crlf] { some t [crlf]
ex [crlf]
t}
and so on, meaning some text can be more than one line and there could be a CRLF immediately following I... | [
"Using pyparsing you can knock this out in about 6 lines, and then get on with your other work. Here are two variations on a solution, depending on how you want the parse results structured:\ndata = \"\"\"ID1 { some text } ID2 { some {with some more text nested in braces} text }\"\"\"\n\nfrom pyparsing import Word,... | [
4,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004029235_python.txt |
Q:
Python logic in assignment
Given that secure is a boolean, what do the following statements do?
Especially the first statement.
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
A:
I hate this Python idiom, it's completely opaque until someone ex... | Python logic in assignment | Given that secure is a boolean, what do the following statements do?
Especially the first statement.
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
| [
"I hate this Python idiom, it's completely opaque until someone explains it. In 2.6 or higher, you'd use:\nprotocol = \"https\" if secure else \"http\"\n\n",
"It sets protocol to \"https\" if secure is true, else it sets it to \"http\".\nTry it in the interpreter:\n>>> True and \"https\" or \"http\"\n'https'\n>>... | [
13,
5,
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004033298_python.txt |
Q:
capitalization of library class names
Why do collection.defaultdict and collection.OrderedDict have different capitalizations?
Is there some subtle difference that I should be aware of?
(P3K)
A:
The capitalization of the class names is irrelevant, it doesn't signify anything. Except that Python has sometimes gr... | capitalization of library class names | Why do collection.defaultdict and collection.OrderedDict have different capitalizations?
Is there some subtle difference that I should be aware of?
(P3K)
| [
"The capitalization of the class names is irrelevant, it doesn't signify anything. Except that Python has sometimes grown organically and the standard library doesn't have the same homogenous feel as other large libraries such as the Win32 API or the Java standard library.\n",
"Usually, that is in accordance wit... | [
5,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004032925_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.