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: Generate blocks of Python code with for loop I made a small GUI program with PyGtk for parametrically drawing the frame of a bike (the idea: you move some slider, and the frame gets redrawn with the updated parameter). Somewhere in the code, I must create a slider for each parameter, and I get this very non-python...
Generate blocks of Python code with for loop
I made a small GUI program with PyGtk for parametrically drawing the frame of a bike (the idea: you move some slider, and the frame gets redrawn with the updated parameter). Somewhere in the code, I must create a slider for each parameter, and I get this very non-pythonic and repetitive code (sorry, I could not get the...
[ "I think this is more or less what you're after:\ndef makeAdjuster(name, attr, lower, upper, step):\n def doAdjust(par):\n setattr(Bikedrawing.p, attr, par.get_value())\n panelhoriz.queue_draw()\n\n val = getattr(Bikedrawing.p, attr)\n adjust = gtk.Adjustment(value=val, lower=lower, upper=upp...
[ 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "code_generation", "pygtk", "python" ]
stackoverflow_0005080756_code_generation_pygtk_python.txt
Q: Python/Matplotlib - Adjusting the spacing between the edge of the plot and the x-axis How can I adjust the amount of space between the x-axis and the edge of the plot window? My x-axis labels are oriented vertically and they are running off of the edge of the window that Matplotlib draws. Here's some example code:...
Python/Matplotlib - Adjusting the spacing between the edge of the plot and the x-axis
How can I adjust the amount of space between the x-axis and the edge of the plot window? My x-axis labels are oriented vertically and they are running off of the edge of the window that Matplotlib draws. Here's some example code: import matplotlib.pyplot as plt x=[1,2,3,4,5] y=[1,2,3,4,5] plt.plot(x,y) plt.xticks(rotat...
[ "As Paul said, you are using figures. You can get a reference to the current figure with gcf() and then set the spacing as per the FAQ. I've added two lines to your code:\nimport matplotlib.pyplot as plt\nx=[1,2,3,4,5]\ny=[1,2,3,4,5]\nplt.plot(x,y)\nplt.xticks(rotation='vertical')\n\nfig = plt.gcf()\nfig.subplots_a...
[ 18, 4 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005080058_matplotlib_python.txt
Q: How to select all objects that are foreign keyed from another model in django? Sorry for title, I do not know how else to express myself. For example, I have this three models: class Person(models.Model): name = models.CharField() class Teacher(models.Model): person = models.ForeignKey(Person) subject...
How to select all objects that are foreign keyed from another model in django?
Sorry for title, I do not know how else to express myself. For example, I have this three models: class Person(models.Model): name = models.CharField() class Teacher(models.Model): person = models.ForeignKey(Person) subject = models.CharField() class Student(models.Model): person = models.ForeignKey(P...
[ "Person.objects.filter(teacher__isnull=False) \n# return Person who has a teacher pointing to it\n\n" ]
[ 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005081374_django_python.txt
Q: Python command line SETUP for ABSOLUTE BEGINNER with Python I'm "new school" meaning that i've never really used the command prompt(they didn't teach us anything but IDE's in school). I would like to setup Python using Notepad++ for the editor, and winpdb as my debugger. I want stuff to work really easy from the c...
Python command line SETUP for ABSOLUTE BEGINNER with Python
I'm "new school" meaning that i've never really used the command prompt(they didn't teach us anything but IDE's in school). I would like to setup Python using Notepad++ for the editor, and winpdb as my debugger. I want stuff to work really easy from the cmd prompt but it is not. This is what I put in my System Environm...
[ "The PATH doesn't affect where data files are found. (And your script is a data file as far as Windows is concerned). You should cd C:\\Path\\to\\folder\\with\\your\\scripts when you open your command prompt, and then you'll be able to python myscript.py from there.\n(You might like to make a dedicated shortcut to ...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0005081501_python.txt
Q: Tell reboot from shutdown on Windows Server 2008 As per MSDN, it is not possible to determine, whether reboot or shutdown occurred using WM_ENDSESSION Message. I've found the only way to do this, but it's quite ugly and works only for Windows 2000 Server, not for 2008 Server. The reason I'm asking is that I'm in p...
Tell reboot from shutdown on Windows Server 2008
As per MSDN, it is not possible to determine, whether reboot or shutdown occurred using WM_ENDSESSION Message. I've found the only way to do this, but it's quite ugly and works only for Windows 2000 Server, not for 2008 Server. The reason I'm asking is that I'm in process of porting Linux daemon to Windows as System Se...
[ "You need to investigate using HookAPI (SetWindowsHookEx?) to capture all ExitWindowsEx calls before they happen.\nLinks that may help:\nhttp://pastebin.com/raw.php?i=KMKiMfBD\nhttp://www.codeproject.com/KB/system/Paladin.aspx\n" ]
[ 0 ]
[]
[]
[ "python", "pywin32", "winapi", "windows", "windows_server_2008" ]
stackoverflow_0004079311_python_pywin32_winapi_windows_windows_server_2008.txt
Q: Python HTTP Server gets multiple requests from iPhone I created a very basic Python http server (Python v3.2) that uses BaseHTTPRequestHandler to handle GET requests. It works fine when I use any web browser on a computer. But, when I use a mobile browser on an iPhone, I always see three GET requests. For exam...
Python HTTP Server gets multiple requests from iPhone
I created a very basic Python http server (Python v3.2) that uses BaseHTTPRequestHandler to handle GET requests. It works fine when I use any web browser on a computer. But, when I use a mobile browser on an iPhone, I always see three GET requests. For example, if I run this: import http.server from http.server imp...
[ "Safari returns a request up to three times - obviously in case of some HTTP error.\nGenerating a proper HTTP response from inside your do_GET() method will solve this issue.\n" ]
[ 1 ]
[]
[]
[ "http", "iphone", "python", "request" ]
stackoverflow_0005081610_http_iphone_python_request.txt
Q: In Zope/ZODB, how to delete objects from a BTreeFolder2 I'm a Zope newb. I need to delete a bunch of objects from a BTreeFolder2 from say, id 1 to id 15000. When going to the admin web interface, the objects are not ordered correctly so I can't just select and delete them. The order is strictly alpha so I get: 1 1...
In Zope/ZODB, how to delete objects from a BTreeFolder2
I'm a Zope newb. I need to delete a bunch of objects from a BTreeFolder2 from say, id 1 to id 15000. When going to the admin web interface, the objects are not ordered correctly so I can't just select and delete them. The order is strictly alpha so I get: 1 10 1000 10000 10001 etc... My guess is I will have to use zope...
[ "app.restrictedTraverse('/path/to/folder').manage_delObjects(list_of_ids)\ntransaction.commit()\n\n" ]
[ 0 ]
[]
[]
[ "python", "zodb", "zope" ]
stackoverflow_0005081745_python_zodb_zope.txt
Q: Python/Matplotlib - x tick label formatted into multiple columns? Is it possible to take: hello world 12345 as an x-tick label (already being displayed vertically) and turn it into this: hello world 12345 which is an x-tick label with (rotated) two columns? A: You could format the text using the textwrap modul...
Python/Matplotlib - x tick label formatted into multiple columns?
Is it possible to take: hello world 12345 as an x-tick label (already being displayed vertically) and turn it into this: hello world 12345 which is an x-tick label with (rotated) two columns?
[ "You could format the text using the textwrap module from the standard library:\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport textwrap\n\nmu, sigma=100, 15\nN=4\nx=mu + sigma*np.random.randn(N)\nplt.bar(range(N), x, align='center')\nlabels=[\n 'hello world 12345',\n 'another long one',\n 'w...
[ 8 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005081798_matplotlib_python.txt
Q: python udisks - enumerating device information It's apparently possible to get a lot of info relating to attached disks using the udisks binary: udisks --show-info /dev/sda1 udisks is apparently just enumerating the data which is available udev. Is it possible to get this information using python? say for examp...
python udisks - enumerating device information
It's apparently possible to get a lot of info relating to attached disks using the udisks binary: udisks --show-info /dev/sda1 udisks is apparently just enumerating the data which is available udev. Is it possible to get this information using python? say for example if i just wanted to retrieve the device serial, m...
[ "You can use Udisks via dbus directly in python.\nimport dbus\n\nbus = dbus.SystemBus()\nud_manager_obj = bus.get_object(\"org.freedesktop.UDisks\", \"/org/freedesktop/UDisks\")\nud_manager = dbus.Interface(ud_manager_obj, 'org.freedesktop.UDisks')\n\nfor dev in ud_manager.EnumerateDevices():\n device_obj = bus....
[ 14, 2 ]
[]
[]
[ "linux", "python", "udev" ]
stackoverflow_0005067005_linux_python_udev.txt
Q: Django signals on GAE with django-nonrel I am using django-nonrel for my project on GAE. My requirement is that in my application at a time only one user should login with the given username. I tried to implement the following suggested approaches: Allow only one concurrent login per user in django app and How ca...
Django signals on GAE with django-nonrel
I am using django-nonrel for my project on GAE. My requirement is that in my application at a time only one user should login with the given username. I tried to implement the following suggested approaches: Allow only one concurrent login per user in django app and How can I detect multiple logins into a Django web a...
[ "1.\nYou should not be editing the django framework like you are doing. Don't touch the files inside django.contrib.auth\nIf you wish to send a signal after someone is logged in, then send the signal in your view where you log the person in\n2.\nNot sure what your actual error is because you are not displaying it (...
[ 2 ]
[]
[]
[ "django_nonrel", "google_app_engine", "python" ]
stackoverflow_0005055608_django_nonrel_google_app_engine_python.txt
Q: Preventing New Windows from Capturing Focus wxPython How do I make a newly created window in wxPython not take focus? I'd like to be able to create a new window, without focus jumping to it. A: I've never tried it, but I've heard you can do window.Disable() window.Show() window.Enable() A: That seems a little...
Preventing New Windows from Capturing Focus wxPython
How do I make a newly created window in wxPython not take focus? I'd like to be able to create a new window, without focus jumping to it.
[ "I've never tried it, but I've heard you can do\nwindow.Disable()\nwindow.Show()\nwindow.Enable()\n\n", "That seems a little counter-intuitive. However, you can also simulate this by creating and showing the second frame and then calling Raise() on the original frame.\n" ]
[ 2, 1 ]
[]
[]
[ "focus", "python", "wxpython" ]
stackoverflow_0005073054_focus_python_wxpython.txt
Q: How to color surface with stronger contrast In Matlab, I am trying to plot a function on 2-dim Euclidean space with following code s=.05; x=[-2:s:2+s]; y=[-1:s:3+s]; [X,Y]=meshgrid(x,y); Z=(1.-X).^2 + 100.*(Y-X.*X).^2; surf(X,Y,Z) colormap jet Here is what my plot look like: I hope to color the surface with stro...
How to color surface with stronger contrast
In Matlab, I am trying to plot a function on 2-dim Euclidean space with following code s=.05; x=[-2:s:2+s]; y=[-1:s:3+s]; [X,Y]=meshgrid(x,y); Z=(1.-X).^2 + 100.*(Y-X.*X).^2; surf(X,Y,Z) colormap jet Here is what my plot look like: I hope to color the surface with stronger contrast, just as Wikipedia shows The plot ...
[ "You can achieve a similar appearance by:\n\nSetting the 'EdgeColor' property of the surface object to 'none' to remove edge coloring.\nModifying the 'CData' property of the surface to mimic the log-scaling of the color data in the Python code.\n\nHere's how you can modify your code:\ns = .05;\nx = [-2:s:2+s];\ny =...
[ 7, 1 ]
[]
[]
[ "matlab", "plot", "python" ]
stackoverflow_0005073865_matlab_plot_python.txt
Q: How can I make a large python data structure more efficient to unpickle? I have a list of ~1.7 million "token" objects, along with a list of ~130,000 "structure" objects which reference the token objects and group them into, well, structures. It's an ~800MB memory footprint, on a good day. I'm using __slots__ to k...
How can I make a large python data structure more efficient to unpickle?
I have a list of ~1.7 million "token" objects, along with a list of ~130,000 "structure" objects which reference the token objects and group them into, well, structures. It's an ~800MB memory footprint, on a good day. I'm using __slots__ to keep my memory footprint down, so my __getstate__ returns a tuple of serializab...
[ "Pickle is not the best method for storing large amounts of similar data. It can be slow for large data sets, and more importantly, it is very fragile: changing around your source can easily break all existing datasets. (I would recommend reading what pickle at its heart actually is: a bunch of bytecode expressions...
[ 10 ]
[]
[]
[ "performance", "pickle", "python", "serialization" ]
stackoverflow_0005082451_performance_pickle_python_serialization.txt
Q: Python Tkinter - Scrollable canvas containing expandable widgets I'm using Python Tkinter and I want to place a variable number of text box widgets in a frame or canvas. The text boxes are packed vertically down the frame, so the first one is on top, the second one is found below, etc.. I can have all the button, ...
Python Tkinter - Scrollable canvas containing expandable widgets
I'm using Python Tkinter and I want to place a variable number of text box widgets in a frame or canvas. The text boxes are packed vertically down the frame, so the first one is on top, the second one is found below, etc.. I can have all the button, listbox, etc widgets in a "left section" of the GUI, while a "right se...
[ "The solution is pretty simple: bind to the <Configure> event of the canvas -- this will cause your callback to be called whenever the canvas widget is resized. You then simply need to get the width of the canvas and use that to iteratively resize all the embedded windows.\n" ]
[ 0 ]
[]
[]
[ "canvas", "python", "scroll", "tkinter", "widget" ]
stackoverflow_0005082642_canvas_python_scroll_tkinter_widget.txt
Q: Is there a Python alternative to Matlab's cp2tform and imtransform? Code: pt1=[input_points(:,2) input_points(:,1)]; pt2=[base_points(:,2) base_points(:,1)]; [pt1 pt2]=preProcessPoints(pt1,pt2); transPr = cp2tform(pt1,pt2,'piecewise linear'); res = imtransform(I,transPr,'Xdata',[1 texturesize(1)],'YData',[1 textur...
Is there a Python alternative to Matlab's cp2tform and imtransform?
Code: pt1=[input_points(:,2) input_points(:,1)]; pt2=[base_points(:,2) base_points(:,1)]; [pt1 pt2]=preProcessPoints(pt1,pt2); transPr = cp2tform(pt1,pt2,'piecewise linear'); res = imtransform(I,transPr,'Xdata',[1 texturesize(1)],'YData',[1 texturesize(2)],'XYscale',1);
[ "Short answer: yes. You may check scipy.ndimage. If somehow not all functionality needed exists there, its still should be pretty straightforward to implement them your self.\nUpdate:\nDon't expect a one to one correspondence between the functionality. Study more on map_coordinates and geometric_transform, they sho...
[ 0 ]
[]
[]
[ "matlab", "python", "scipy" ]
stackoverflow_0005081932_matlab_python_scipy.txt
Q: working example of multiprocessing.Queue I am looking for a working example of multiprocessing.Queue after being pointed to it from this question: Python utilizing multiple processors I came across this, but it only seems to use one of my 12 processors even when I change num_processes=12. I also changed num_jobs =...
working example of multiprocessing.Queue
I am looking for a working example of multiprocessing.Queue after being pointed to it from this question: Python utilizing multiple processors I came across this, but it only seems to use one of my 12 processors even when I change num_processes=12. I also changed num_jobs = 200000 so that it wouldn't complete so fast. ...
[ "There are examples in the Python docs.\nDo these examples work? If not, it may be that the problem itself is not Python, but something else instead.\n" ]
[ 3 ]
[]
[]
[ "multiprocessing", "multithreading", "python", "queue" ]
stackoverflow_0005082391_multiprocessing_multithreading_python_queue.txt
Q: How to set the tcp option timestamp while building a tcp SYN packet using python? I need to send a tcp SYN packet with timestamp value in tcp option. Since tcp opts should be prepacked in 32-bit representation, can anyone brief me how to set the value in 32 bit packet representaion with a example. Thanks in advanc...
How to set the tcp option timestamp while building a tcp SYN packet using python?
I need to send a tcp SYN packet with timestamp value in tcp option. Since tcp opts should be prepacked in 32-bit representation, can anyone brief me how to set the value in 32 bit packet representaion with a example. Thanks in advance
[ "You should be able to do that pretty easily with Scapy. When defining your TCP layer, just use\nTCP(flags='S', options=[('Timestamp', (TSval, 0))])\n\nwhere TSval is your timestamp value. If you want to convert the resultant packet to its binary representation, call str() on it.\nIn future packets, you can replace...
[ 1 ]
[]
[]
[ "32_bit", "python", "tcp" ]
stackoverflow_0005082516_32_bit_python_tcp.txt
Q: App engine datastore query issue I have a weired problem with couple of queries I am trying to run. I have built a method which returns a tuple of result from the query- def get_activeproducts(): query = Product.gql("WHERE active = True") choices = [] for obj in query: choices.append((str(obj.k...
App engine datastore query issue
I have a weired problem with couple of queries I am trying to run. I have built a method which returns a tuple of result from the query- def get_activeproducts(): query = Product.gql("WHERE active = True") choices = [] for obj in query: choices.append((str(obj.key()), obj.name)) return choices ...
[ "Your class definition is getting cached by the App Engine runtime when an instance is started, with the default set to what it was when the instance started. To make the choices dynamic, you need to set them at runtime.\nExample from the wtforms (which IIRC is what tipfy is using) docs; will need to be adjusted f...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "tipfy" ]
stackoverflow_0005077274_google_app_engine_google_cloud_datastore_python_tipfy.txt
Q: Simple text parsing library I have a method that takes addresses from the web, and therefore, there are many known errors like: 123 Awesome St, Pleasantville, NY, Get Directions Which I want to be: 123 Awesome St, Pleasantville, NY Is there a web service or Python library that can help with this? It's fine for ...
Simple text parsing library
I have a method that takes addresses from the web, and therefore, there are many known errors like: 123 Awesome St, Pleasantville, NY, Get Directions Which I want to be: 123 Awesome St, Pleasantville, NY Is there a web service or Python library that can help with this? It's fine for us to start creating a list of it...
[ "If the address contains one of those bad strings, walk backwards till you find another non-whitespace character. If the character is one of your separators, say , or :, drop everything from that character onwards. If it's a different character, drop everything after that character. \nMake a list of known bad strin...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005081296_python.txt
Q: One-to-Many in Django with multiple models as target I'm making a patient database application. Each diagnosis would be filled in a form, which have many types of form. I'm doing this with Django with each form as a model. However, seems that I cannot join the model to the Patient model. How should I join them? No...
One-to-Many in Django with multiple models as target
I'm making a patient database application. Each diagnosis would be filled in a form, which have many types of form. I'm doing this with Django with each form as a model. However, seems that I cannot join the model to the Patient model. How should I join them? Note that I'm not restricted to Django's ORM. I can move to ...
[ "\nscale to 10k patient records and over 100k diagnosis.\n\nThis is not a scale to be concerned about. Pretty much anything that can do this, can do this scale.\n\nI'm doing this with Django with each form as a model.\n\nI don't see why that would be necessary. You should rather create dynamic forms (another tutori...
[ 0 ]
[]
[]
[ "django", "nosql", "python" ]
stackoverflow_0005079734_django_nosql_python.txt
Q: django signal on GAE Does Django signals work on google app engine ? I am using django-nonrel. Thanks A: Works fine. Signals do not use the db. A: Does Django signals work on google app engine ? Yes, as long as you save those models use the Model.save()
django signal on GAE
Does Django signals work on google app engine ? I am using django-nonrel. Thanks
[ "Works fine. Signals do not use the db.\n", "\nDoes Django signals work on google app engine ?\n\nYes, as long as you save those models use the Model.save()\n" ]
[ 0, 0 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "python" ]
stackoverflow_0005080844_django_django_nonrel_google_app_engine_python.txt
Q: Concatenating field values in Django I have created with the "extra" clause a concatenated field out of three text fields in a model - and I expect to be able to do this: q.filter(concatenated__icontains="y") but it gives me an error. What alternatives are there? >>> q = Patient.objects.extra(select={'concatenated...
Concatenating field values in Django
I have created with the "extra" clause a concatenated field out of three text fields in a model - and I expect to be able to do this: q.filter(concatenated__icontains="y") but it gives me an error. What alternatives are there? >>> q = Patient.objects.extra(select={'concatenated': "mrn||' '||first_name||' '||last_name"}...
[ "If you need something beyond this,\nPatient.objects.filter(first_name__icointains='y' | last_name__icontains='y' | mrn__icontains='y')\n\nyou might have to resort to raw SQL.\nOf course, you can add in your extra either before or after the filter above.\n", "My final solution based on Prasad's answer:\nfrom djan...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005082697_django_python.txt
Q: PIL: Is it possible to fill a mask? Suppose I have a mask (a blank triangle - 1/255/etc in the triangle, 0 elsewhere) and I have the texture I'd like to place inside that triangle, but the texture is sequential instead of being formatted into an image format. For example, if the box containing the triangle/mask is...
PIL: Is it possible to fill a mask?
Suppose I have a mask (a blank triangle - 1/255/etc in the triangle, 0 elsewhere) and I have the texture I'd like to place inside that triangle, but the texture is sequential instead of being formatted into an image format. For example, if the box containing the triangle/mask is 100 x 100, but the triangle itself only ...
[ "mask[mask==1] = data\n", "It sounds like you are asking if you can fill/modify each pixel of the triangle using an array of values without also having to visit the pixels which you don't want to fill using only the image data.\nIf that's so, then the short answer is no. \nCertainly it would be possible to create...
[ 2, 0 ]
[]
[]
[ "image", "python", "python_imaging_library" ]
stackoverflow_0005082992_image_python_python_imaging_library.txt
Q: Google App Engine json post request body I can't read body from POST request on Google app engine application whenever I send string which contains colon ":" This is my request handler class: class MessageSync(webapp.RequestHandler): def post(self): print self.request.body Ad this is my testing script: import...
Google App Engine json post request body
I can't read body from POST request on Google app engine application whenever I send string which contains colon ":" This is my request handler class: class MessageSync(webapp.RequestHandler): def post(self): print self.request.body Ad this is my testing script: import httplib2 json_works = '{"works"}' json_doesn...
[ "In the case of json_doesnt_work, the print function is setting the self.request.body as a Response header because it's in a form of a {key:value} parameter.\n{'status': '200', 'content-length': '0',\n 'expires': 'Fri, 01 Jan 1990 00:00:00 GMT',\n 'server': 'Development/1.0',\n 'cache-control': 'no-cache',\n 'date'...
[ 11 ]
[]
[]
[ "google_app_engine", "json", "post", "python" ]
stackoverflow_0005082832_google_app_engine_json_post_python.txt
Q: what SendMessage to use to send keys directly to another window? I'm trying to use SendMessage to send keyboard input to another window. I know the drawbacks, but I have to do it since I have to send several keys and I can't guarantee that the window will have focus - so this has to work when the window doesnt hav...
what SendMessage to use to send keys directly to another window?
I'm trying to use SendMessage to send keyboard input to another window. I know the drawbacks, but I have to do it since I have to send several keys and I can't guarantee that the window will have focus - so this has to work when the window doesnt have focus. I'm testing it by trying to send keys to a notepad window. I'...
[ "When I wrote the question, I understood that SendKeys is the correct way to generate keyboard input, and that's the only one that works in all cases. However, I couldn't use SendKeys, cause the computer my program is running on will be actively used while my program is running, meaning a mouse-click can happen at ...
[ 7 ]
[]
[]
[ "input", "python", "pywin32", "winapi" ]
stackoverflow_0005080777_input_python_pywin32_winapi.txt
Q: Python: Desktop UI for my python script Im new to python and want to create a GUI front-end (desktop, rather than web) for my python script. The script essentially parses XML files and runs various searches over the contents (eg. accepts regex searches from the user, returns results etc). It works well on the comm...
Python: Desktop UI for my python script
Im new to python and want to create a GUI front-end (desktop, rather than web) for my python script. The script essentially parses XML files and runs various searches over the contents (eg. accepts regex searches from the user, returns results etc). It works well on the command line but I want to present a more user fr...
[ "PyQt is great, although it's on GPL. There is also PySide alternative on LGPL.\nYou can also try wxPython or PyGTK if you don't like Qt for some reason. There is also gui library in python standard library called Tkinter, but I haven't used it and don't have any experience with it.\n", "Here is a page on the Pyt...
[ 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005082141_python.txt
Q: Python SVN Bindings on Windows Server 2008 x64 My goal is to use the python scripts in subversion\tools, specifically validate-extensions.py in this case. I am running VisualSVN Server 2.15, built on Subversion 1.6.15 and have 32-bit Python 2.7.1 set up on the machine at the moment. When I set up the hook, I got ...
Python SVN Bindings on Windows Server 2008 x64
My goal is to use the python scripts in subversion\tools, specifically validate-extensions.py in this case. I am running VisualSVN Server 2.15, built on Subversion 1.6.15 and have 32-bit Python 2.7.1 set up on the machine at the moment. When I set up the hook, I got an error that the svn module could not be found. I ...
[ "I found an answer to this on the Subversion mailing list. The problem is that the Python 2.7 SVN bindings provided by Trac were built using an older version of an Apache dll, namely libapr-1.dll, and they reference a function called '_apr_time_ansi_put@8'. In the later versions of Apache, including VisualSVN 2.1...
[ 2 ]
[]
[]
[ "python", "svn", "visualsvn_server", "windows_server_2008" ]
stackoverflow_0005008718_python_svn_visualsvn_server_windows_server_2008.txt
Q: Adding opion to form label I have form declared like this: field = forms.MultipleChoiceField(choices = STATES, widget=forms.CheckboxSelectMultiple, label_suffix= "(%d)" % id) let say STATES is decladed as STATES = [(0, 'foo'), (1, 'bar')] And I want to acheve labels that looks like this: foo (0) bar (1) id shou...
Adding opion to form label
I have form declared like this: field = forms.MultipleChoiceField(choices = STATES, widget=forms.CheckboxSelectMultiple, label_suffix= "(%d)" % id) let say STATES is decladed as STATES = [(0, 'foo'), (1, 'bar')] And I want to acheve labels that looks like this: foo (0) bar (1) id should be option value (I'll call fu...
[ "You'd need to declare it in the states variable:\nSTATES = [(0, 'foo (0)'), (1, 'bar (1)')]\n\nNow way around that unless you're pulling it in from a States Model, in which case you'd want a ModelChoiceField and a unicode(self) function on your States Model which returns something like:\nreturn self.name + (' (%i)...
[ 0 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005084070_django_django_forms_python.txt
Q: Importing a large amount of XML data into Google App Engine I have a reasonably large amount of XML data (about 200MB) that I want to import into an App Engine datastore. So far I've tried creating the models and using the cElementTree parser to load the entities, but it is taking a long time. I also have concerns...
Importing a large amount of XML data into Google App Engine
I have a reasonably large amount of XML data (about 200MB) that I want to import into an App Engine datastore. So far I've tried creating the models and using the cElementTree parser to load the entities, but it is taking a long time. I also have concerns about how well the datastore will handle this much data, and if ...
[ "I would go with the Bulk Loader that supports reading data from an XML source.\nRegarding the size of the XML, Datastore will have no problem at all to handle such amount of data.\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "xml" ]
stackoverflow_0005083968_google_app_engine_google_cloud_datastore_python_xml.txt
Q: python ObjectListView updating display with blank lines, even though the list has valid data I have a list that updates ObjectListView, it previously worked, but in troubleshooting a different issue, I somehow broke it but now can't figure out why its not working. When the program parses a directory it is supposed...
python ObjectListView updating display with blank lines, even though the list has valid data
I have a list that updates ObjectListView, it previously worked, but in troubleshooting a different issue, I somehow broke it but now can't figure out why its not working. When the program parses a directory it is supposed to updated the list view with info about .mp3 files found. It is updating the display, but only ...
[ "The problem is that the 4th argument in the ColumnDefn in your setTracks method don't match the Track object's attribute names. If they don't match exactly, then it won't map correctly and nothing will be shown in the widget.\nSo, change \"title\" to \"atrTitle\", etc in the setTracks method or do the reverse in t...
[ 2 ]
[]
[]
[ "objectlistview", "python", "wxpython" ]
stackoverflow_0005083563_objectlistview_python_wxpython.txt
Q: What is an efficient way to reinstall all my python libraries after baselining my windows pc? My windows laptop is being replaced due to some hardware problems. I've spent the last two years installing third party libraries every so often, which I'll need to reinstall on the new machine. I just need to: Generat...
What is an efficient way to reinstall all my python libraries after baselining my windows pc?
My windows laptop is being replaced due to some hardware problems. I've spent the last two years installing third party libraries every so often, which I'll need to reinstall on the new machine. I just need to: Generate a list of third party python libs current installed Reinstall those on the new machine My though...
[ "You might want to look into virtualenv. It lets you have a \"virtual environment\" for Python that would eliminate this need in the future. As for getting the old libs on the new system, you can check the PYTHONPATH environment variable and/or sys.path from the interpreter to see what all paths are searched and ...
[ 1, 1 ]
[]
[]
[ "python", "setuptools" ]
stackoverflow_0005084512_python_setuptools.txt
Q: Iteration over python dictionary sorted by an element I have a python dictionary such as { 'FOUR': [['emit', 'build', 'simulate'], 'TestFour', 2], 'HELLO': [['emit', 'build', 'simulate'], 'TestThree', 1] } How can I iterate the elements based on the number 1,2? I mean, how can I get 'HELLO'(1)...
Iteration over python dictionary sorted by an element
I have a python dictionary such as { 'FOUR': [['emit', 'build', 'simulate'], 'TestFour', 2], 'HELLO': [['emit', 'build', 'simulate'], 'TestThree', 1] } How can I iterate the elements based on the number 1,2? I mean, how can I get 'HELLO'(1), and then 'FOUR'(2)?
[ "for x in sorted(d, key=lambda x:d[x][2]):\n print x\n\nThis will print\nHELLO\nFOUR\n\n", "If d is your dictionary:\nfor k in sorted(d.keys(), key=lambda k, d=d: d[k][2]):\n ...\n\nHow does this work? Firstly, we want the keys in a particular order so we use the sorted built-in function. sorted takes a k...
[ 4, 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0005084772_dictionary_python.txt
Q: What are the operator methods for boolean 'and', 'or' in Python? For instance, these are defined in the operator module and can be used as such: import operator print operator.__add__ # alias add -> + print operator.__sub__ # alias sub -> - print operator.__and__ # alias and_ -> & print operator.__or__ # ...
What are the operator methods for boolean 'and', 'or' in Python?
For instance, these are defined in the operator module and can be used as such: import operator print operator.__add__ # alias add -> + print operator.__sub__ # alias sub -> - print operator.__and__ # alias and_ -> & print operator.__or__ # alias or_ -> | Then what is the equivalent of and and or? print opera...
[ "The and and or operators don't have an equivalent in the operator module, because they can't be implemented as a function. This is because they are short-circuiting: they may not evaluate their second operand depending on the outcome of the first.\n", "These do not exist. The best you can do is to replace them ...
[ 12, 6, 3 ]
[]
[]
[ "operator_keyword", "parsing", "python" ]
stackoverflow_0005084615_operator_keyword_parsing_python.txt
Q: windows: disable maximize window on double-click title bar, and minimize on clicking task bar I want to make a window in an application that is not mine (i.e. I don't have the source code) not closable or resizable (sounds annoying, but it's at the request of the users...) Anyway, I've managed to almost accomplish...
windows: disable maximize window on double-click title bar, and minimize on clicking task bar
I want to make a window in an application that is not mine (i.e. I don't have the source code) not closable or resizable (sounds annoying, but it's at the request of the users...) Anyway, I've managed to almost accomplish that fully with this code: def set_window_style(hwnd, resizable=None, sysmenu=None): style = w...
[ "Also remove the WS_MINIMIZEBOX and WS_MAXIMIZEBOX styles.\n" ]
[ 1 ]
[]
[]
[ "python", "pywin32", "winapi", "windows" ]
stackoverflow_0005081915_python_pywin32_winapi_windows.txt
Q: Python Console UI Suggestions I'm currently rewriting a perl console application that was using curses, and planning to implement it in Python. So far I've narrowed my library options to straight curses, urwid, and dialog. The application is basically an installer for an appliance that will accommodate basic confi...
Python Console UI Suggestions
I'm currently rewriting a perl console application that was using curses, and planning to implement it in Python. So far I've narrowed my library options to straight curses, urwid, and dialog. The application is basically an installer for an appliance that will accommodate basic configuration (network options, hostname...
[ "urwid is a very complete UI interface and you can do almost everything. In fact, I'm developing an app using urwid. But, as Paulo Scardine said, dialog is a better choice for a wizard-like app.\n", "Dialog is very easy to use and a good choice for an installer using 'wizard-like' interface.\n" ]
[ 4, 2 ]
[]
[]
[ "console_application", "curses", "python", "urwid" ]
stackoverflow_0004783308_console_application_curses_python_urwid.txt
Q: Eclipse, Python and the Google SDK How do I get Eclipse to load the Google python SDK? I am using OSX 10.6, I have Eclipse (helios) and I have downloaded the GoogleAppEngineLauncher and the Eclipse plugin. When I try to start a new web app project its asks for the SDK. I enter my location as follows: /Applications...
Eclipse, Python and the Google SDK
How do I get Eclipse to load the Google python SDK? I am using OSX 10.6, I have Eclipse (helios) and I have downloaded the GoogleAppEngineLauncher and the Eclipse plugin. When I try to start a new web app project its asks for the SDK. I enter my location as follows: /Applications/GoogleAppEngineLauncher.app/Contents/Re...
[ "You shouldn't need to install the Google App Engine SDK/Launcher separately if using Eclipse. The Google Plugin for Eclipse will install the App Engine SDK/Launcher for you:\nhttp://code.google.com/eclipse/\nIn the event you need to install them separately, it does appear you've got a space in your path between \...
[ 0 ]
[]
[]
[ "eclipse", "python", "sdk", "web_applications" ]
stackoverflow_0005084939_eclipse_python_sdk_web_applications.txt
Q: Is it possible to use variables in PIL (python)? i'm programing in python 3.1 and using a PIL which are updated for it aswel. Now it's so that my program is getting info from a webpage and i want this info to be drawed at a picture which i already got, so i'm using a variable for this & it's also the part i need h...
Is it possible to use variables in PIL (python)?
i'm programing in python 3.1 and using a PIL which are updated for it aswel. Now it's so that my program is getting info from a webpage and i want this info to be drawed at a picture which i already got, so i'm using a variable for this & it's also the part i need help with. What I link is a part of my program (since i...
[ "It is a syntax error. Adding more parenthesis just makes a new datastructure. Try:\ntext = Z + \" \" + title\ndraw.text ( (20,20), text, font=arial16, fill=\"white\")\n\nand for your save command:\nim.save(S)\nim.show(S)\n\n" ]
[ 0 ]
[]
[]
[ "draw", "python", "python_imaging_library", "text", "variables" ]
stackoverflow_0005085040_draw_python_python_imaging_library_text_variables.txt
Q: Python, Zope Component Architecture, Registering an adapter In a stand-alone python application I use zope.interface, zope.component packages to register and access application's adapters. I thought I could use metaclass concept to register adapters from inside init method of the metaclass. This would "automate" a...
Python, Zope Component Architecture, Registering an adapter
In a stand-alone python application I use zope.interface, zope.component packages to register and access application's adapters. I thought I could use metaclass concept to register adapters from inside init method of the metaclass. This would "automate" adapter's registration process. Do you see problems with this appr...
[ "Just because you can, doesn't mean you should.\nRegistering the adapter is a single line of code outside the class, so I would just do that instead of tucking the behaviour in a metaclass.\nExplicit is better than implicit.\n", "Edit: go with @Tobu's advice, Don't Do This. My answer below is incorrect but left i...
[ 3, 1 ]
[]
[]
[ "adapter", "metaclass", "python", "zope", "zope.component" ]
stackoverflow_0005083506_adapter_metaclass_python_zope_zope.component.txt
Q: Are there standard rules and practices for Date serialization between two languages or frameworks? Seems simple but I just don't know. I'm interested in serializing a date to a string or integer and sending it from Objective-C to Python, and I want to know if there's a way I should be doing it. Sending the integer...
Are there standard rules and practices for Date serialization between two languages or frameworks?
Seems simple but I just don't know. I'm interested in serializing a date to a string or integer and sending it from Objective-C to Python, and I want to know if there's a way I should be doing it. Sending the integer seconds since the Unix epoch seems pretty reasonable (and NSDate supplies that readily) but does Python...
[ "Sure, Python can convert seconds from the Epoch to datetime.datetime objects:\nIn [23]: import datetime as dt\n\nfromtimestamp returns the datetime.datetime in your machine's local timezone:\nIn [24]: dt.datetime.fromtimestamp(0)\nOut[25]: datetime.datetime(1969, 12, 31, 19, 0)\n\nutcfromtimestamp returns the UTC ...
[ 3, 0 ]
[]
[]
[ "date", "datetime", "objective_c", "python", "serialization" ]
stackoverflow_0005085365_date_datetime_objective_c_python_serialization.txt
Q: In Python, how can I convert both numbers and strings into byte arrays? I want to encode a set of configuration options into a long string of hex digits. The input is a mix of numbers (integers and floats) and strings. I can use binascii.a2b_hex from the standard library for the strings, bit-wise operators for the...
In Python, how can I convert both numbers and strings into byte arrays?
I want to encode a set of configuration options into a long string of hex digits. The input is a mix of numbers (integers and floats) and strings. I can use binascii.a2b_hex from the standard library for the strings, bit-wise operators for the integers, and probably, if I go and read some on floating point representati...
[ "You want struct.\n>>> struct.pack('16sdl', 'Hello, world!', 3.141592654, 42)\n'Hello, world!\\x00\\x00\\x00PERT\\xfb!\\t@*\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n\n", "You easiest bet is to pickle the whole list to a string and then use binascii.a2b_hex() to convert this string to hex digits:\na = [\"Hello\", 42, ...
[ 3, 2, 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0005085096_python_serialization.txt
Q: Python not splitting CRLF correctly I'm writing a script to convert very simple function documentation to XML in python. The format I'm using would convert: date_time_of(date) Returns the time part of the indicated date-time value, setting the date part to 0. to: <item name="date_time_of"> <arg>(date)</arg> <he...
Python not splitting CRLF correctly
I'm writing a script to convert very simple function documentation to XML in python. The format I'm using would convert: date_time_of(date) Returns the time part of the indicated date-time value, setting the date part to 0. to: <item name="date_time_of"> <arg>(date)</arg> <help> Returns the time part of the indicate...
[ "input() only reads one line.\nTry this. Enter a blank line to stop collecting lines.\nlines = []\nwhile True:\n line = input('line: ')\n if line:\n lines.append(line)\n else:\n break\nprint(lines)\n\n", "The best way to handle reading lines from standard input (the console) is to iterate ...
[ 4, 0, 0 ]
[]
[]
[ "newline", "parsing", "python" ]
stackoverflow_0005053831_newline_parsing_python.txt
Q: Django-registration & Django-Socialauth Have anyone used these 2 django apps together? I want to know how well these 2 gel together along with Django's User Authentication system. When I mean Django's User Authentication System, I mean I should be able to use decorators like @login_required or grant permission to ...
Django-registration & Django-Socialauth
Have anyone used these 2 django apps together? I want to know how well these 2 gel together along with Django's User Authentication system. When I mean Django's User Authentication System, I mean I should be able to use decorators like @login_required or grant permission to specific views (or functions in views.py) bas...
[ "There shouldn`t be any problems there. Django-Socialauth adda new auth backends, and it should works fine with permissions and decorators. And Django resistration just register a user on site, so unless you remove standard auth backend, it will work fine too.\n" ]
[ 1 ]
[]
[]
[ "django", "django_apps", "django_authentication", "python" ]
stackoverflow_0005074537_django_django_apps_django_authentication_python.txt
Q: nltk.cluster using a sparse representation I am quite new in Python. I am trying to use the nltk.cluster package to apply a simple kMeans to a word-document matrix. While it works when the matrix is a list of numpy array-like objects, I wasn't able to make it work for a sparse matrix representation (such as csc_ma...
nltk.cluster using a sparse representation
I am quite new in Python. I am trying to use the nltk.cluster package to apply a simple kMeans to a word-document matrix. While it works when the matrix is a list of numpy array-like objects, I wasn't able to make it work for a sparse matrix representation (such as csc_matrix, csr_matrix or lil_matrix). All the inform...
[ "It means that when you pass in the input vector, you can either pass in a numpy.array() or a nltk_contrib.unimelb.tacohn.SparseArrays.\nI suggest you look at the package nltk_contrib.unimelb.tacohn to find the SparseArrays class. Then try to create your data with this class before passing it into nltk.cluster\n" ]
[ 1 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005044359_nltk_python.txt
Q: Execute a python script stored on a web server using beautiful soup I am trying to create a simple form/script combination that will allow someone to replace the contents of a certain div in an html file with the text they input in an html form on a separate page. The script works fine if everything is local : th...
Execute a python script stored on a web server using beautiful soup
I am trying to create a simple form/script combination that will allow someone to replace the contents of a certain div in an html file with the text they input in an html form on a separate page. The script works fine if everything is local : the script is local, i set the working directory to where my html file is, ...
[ "Do you have a shell account on your host? If so, try running the server's version of Python in interactive mode and type:\n>>> import BeautifulSoup\n\nIf the module doesn't exist, you should get an ImportError.\nAlternatively, try putting cgitb.enable() immediately following the line import cgi, cgitb. This should...
[ 0, 0 ]
[]
[]
[ "beautifulsoup", "cgi", "python" ]
stackoverflow_0005072630_beautifulsoup_cgi_python.txt
Q: open a file with shared permission How do I open a file with shared permission in python? There's another process already opens the file that my python script tries to write something to it. I am using open() but it doesn't seem to open the file with shared permission because I can't write anything to the file. A...
open a file with shared permission
How do I open a file with shared permission in python? There's another process already opens the file that my python script tries to write something to it. I am using open() but it doesn't seem to open the file with shared permission because I can't write anything to the file.
[ "The first process that requests exclusive access to a file is the one that determines whether or not other processes can also have access to the file. A process that comes along later (such as your script) has no say in it.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005085571_python.txt
Q: Does any one know of an RTF report generator in Django? I know about the PDF report generator, but I need to use RTF instead. A: There is PyRTF but it hasn't been updated in a while. If that doesn't work and you are willing to do some hacking then I can also point you to the GRAMPS Project that has an RTF report...
Does any one know of an RTF report generator in Django?
I know about the PDF report generator, but I need to use RTF instead.
[ "There is PyRTF but it hasn't been updated in a while.\nIf that doesn't work and you are willing to do some hacking then I can also point you to the GRAMPS Project that has an RTF report generator (look in gramps/docgen/RTFDoc.py). This code is very specific to their genealogy reporting needs, but it is clean and ...
[ 3, 2, 0 ]
[]
[]
[ "django", "python", "report", "rtf" ]
stackoverflow_0000678308_django_python_report_rtf.txt
Q: vim could not load library python26.dll but i'm using python 2.7? Using vim and when I try use omnicomplete for python I get an error Required vim compiled with +python. When I try :python print 'hello' I get E370: Could not load library python26.dll Strangely I'm using python 2.7 anyway so how can I change w...
vim could not load library python26.dll but i'm using python 2.7?
Using vim and when I try use omnicomplete for python I get an error Required vim compiled with +python. When I try :python print 'hello' I get E370: Could not load library python26.dll Strangely I'm using python 2.7 anyway so how can I change what python vim should use or will I have to install python 2.6 to use t...
[ "You have to have the same version of python installed that vim was compiled against. That means you either need to install 2.6 or recompile vim against 2.7 (or find an existing binary that already is).\n" ]
[ 4 ]
[]
[]
[ "omnicomplete", "python", "vim" ]
stackoverflow_0005083819_omnicomplete_python_vim.txt
Q: appending & printing a list of numbers in python I am solving a numerical approximation (square root of two) up to a million or more digits of precision. There is little efficiency improvement I can make because of the insufficient knowledge I guess. But I do have a few questions related to Python itself which may...
appending & printing a list of numbers in python
I am solving a numerical approximation (square root of two) up to a million or more digits of precision. There is little efficiency improvement I can make because of the insufficient knowledge I guess. But I do have a few questions related to Python itself which may help reduce some overhead times .... If we are doing...
[ "(Please try to limit questions to one topic, rather than asking several unrelated questions at once.)\nIf you want to know how much of a difference a change like moving something out of a loop makes, you need to benchmark it yourself. Search for timeit.\nAppending to a string and to a list are completely differen...
[ 4, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005085910_list_python.txt
Q: Dynamic imports + relative imports in Python 3 I have a Python 3 project where I'm dynamically importing modules from disk, using imp.load_module. But, I've run into an problem where relative imports fail, when the relative import occurs within a dynamically imported module. From what I've read, I came to the conc...
Dynamic imports + relative imports in Python 3
I have a Python 3 project where I'm dynamically importing modules from disk, using imp.load_module. But, I've run into an problem where relative imports fail, when the relative import occurs within a dynamically imported module. From what I've read, I came to the conclusion that only __file__, __path__, __package__, an...
[ "The lack of a root.__path__ value is suspicious (it means Python doesn't consider root to be a package).\nThe fact that both load_module() calls are being made with a type value of 1 (a module) instead of the first one having a type of 5 (a package) is also highly dubious.\nAre you using imp.find_module() to work ...
[ 1 ]
[]
[]
[ "import", "python", "python_3.x" ]
stackoverflow_0005078590_import_python_python_3.x.txt
Q: modify admin auth backend By default, after authentication on /admin, function authenticate() returns User object, what if i want to get proxy model for the User (i.g. called HandyUser) in return ? In my project, in all custom auth backends, i'm using HandyUser instead of User. thanks A: According to the django...
modify admin auth backend
By default, after authentication on /admin, function authenticate() returns User object, what if i want to get proxy model for the User (i.g. called HandyUser) in return ? In my project, in all custom auth backends, i'm using HandyUser instead of User. thanks
[ "According to the django docs http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-user, you need to add to your settings file:\nAUTH_PROFILE_MODULE = 'app.HandyUser'\n\nAnd then when you reference your User class, call the user.get_profile method which will return the instance of ...
[ 0 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0003148221_django_django_admin_python.txt
Q: Python: Sort text file twice and split to different files? How do I sort first by line length, then alphabetically, then split by line length into seperate files? I have a word list file like so: a actors an b batter but I require one file (1.txt, 2.txt) for each line length, each sorted alphabetically. How ...
Python: Sort text file twice and split to different files?
How do I sort first by line length, then alphabetically, then split by line length into seperate files? I have a word list file like so: a actors an b batter but I require one file (1.txt, 2.txt) for each line length, each sorted alphabetically. How might this be done? The resulting file should look like: 1.txt a...
[ "You can pass a function into sort. Something like lambda a, b: (len(a) < len(b)) if (len(a) != len(b)) else (a < b) ought to do it.\n", "from collections import defaultdict\n\nOUTF = \"{0}.txt\".format\n\ndef sortWords(wordList):\n d = defaultdict(list)\n for word in wordList:\n d[len(word)].append(...
[ 1, 1, 0, 0 ]
[]
[]
[ "python", "sorting", "split" ]
stackoverflow_0005085767_python_sorting_split.txt
Q: Nested lambda expressions in python map and reduce My code currently contains, as part of the condition for a while loop: reduce(operator.or_, map(lambda y: reduce(operator.or_, map(lambda x: x[0] == y, data[testedoffset:])), footers)) It's purpose is to check if a given slice of a python array.array instance cont...
Nested lambda expressions in python map and reduce
My code currently contains, as part of the condition for a while loop: reduce(operator.or_, map(lambda y: reduce(operator.or_, map(lambda x: x[0] == y, data[testedoffset:])), footers)) It's purpose is to check if a given slice of a python array.array instance contains one of several specific byte values. The error I'm ...
[ "I see you found the answer on your own, but while you're here... \nThat code really could use some work.\nI'm not entirely sure why you're mapping that expression based on data[testedoffset:] across the footers sequence. That doesn't seem to have any effect whatsoever, unless your __getitem__ has side effects.\nBu...
[ 3, 0 ]
[]
[]
[ "arrays", "map", "python", "reduce", "slice" ]
stackoverflow_0005086357_arrays_map_python_reduce_slice.txt
Q: Why selenium can not open some asp page? I use selenium-rc to test an asp.net website, test script is written in Python and the browser is Firefox 3.6. But When selenium open the first page of the website, A download dialog appear, not the web page, seems the page is proccessed as application/octet-stream, this ca...
Why selenium can not open some asp page?
I use selenium-rc to test an asp.net website, test script is written in Python and the browser is Firefox 3.6. But When selenium open the first page of the website, A download dialog appear, not the web page, seems the page is proccessed as application/octet-stream, this cause my test script can not run successfully. S...
[ "Ok, I upgrade my selenium-server to 2.0b2, now it's ok.\n" ]
[ 0 ]
[]
[]
[ "asp.net", "python", "selenium_rc" ]
stackoverflow_0005086524_asp.net_python_selenium_rc.txt
Q: Ajax with JQuery on the Django Dev Server I am putting together an Ajax request with JQuery (1.5) on a Django (1.2.5) site. I am working on the Dev Server currently because I plan on doing demonstrations before a full production roll out. The javascript code in the template: function postTest() { $.post("/...
Ajax with JQuery on the Django Dev Server
I am putting together an Ajax request with JQuery (1.5) on a Django (1.2.5) site. I am working on the Dev Server currently because I plan on doing demonstrations before a full production roll out. The javascript code in the template: function postTest() { $.post("/get_elections", { csrfmiddlewaretoken: $('input...
[ "So I discovered the answer after many long hours of research, and many would do well to learn from my pain.\nThe problem lay here:\n<a href=\"\" onclick='postTest()'>Link</a>\n\nXMLHttpRequests, no matter what their wrapper, cannot be initiated through an onclick in a link tag with an href. I merely changed the c...
[ 2 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0005084860_ajax_django_javascript_python.txt
Q: How to Convert multiple sets of Data going from left to right to top to bottom the Pythonic way? Following is a sample of sets of contacts for each company going from left to right. ID Company ContactFirst1 ContactLast1 Title1 Email1 ContactFirst2 ContactLast2 Title2 Email2 1 ABC John Doe ...
How to Convert multiple sets of Data going from left to right to top to bottom the Pythonic way?
Following is a sample of sets of contacts for each company going from left to right. ID Company ContactFirst1 ContactLast1 Title1 Email1 ContactFirst2 ContactLast2 Title2 Email2 1 ABC John Doe CEO jd@abc.com Steve Bern CIO sb@abc.com How do I get them to go top to bott...
[ "Here is a somewhat cleaner version of the above. It presumes the data is comma-delimited. The sample data appears to be fixed-width instead; I suggest loading it in Excel or OpenOffice and resaving as actual comma-delimited CSV.\nimport csv\n\ndef main():\n infname = 'contacts.csv'\n outfname = 'per_contact...
[ 2, 1 ]
[]
[]
[ "csv", "data_structures", "python" ]
stackoverflow_0005084934_csv_data_structures_python.txt
Q: Methods for Python classes representation I know that methods __repr__ and __str__ exist to give a formal and informal representation of class instances. But does an equivalent exist for class objects too, so that when the class object is printed, a nice representation of it could be shown? >>> class Foo: ... ...
Methods for Python classes representation
I know that methods __repr__ and __str__ exist to give a formal and informal representation of class instances. But does an equivalent exist for class objects too, so that when the class object is printed, a nice representation of it could be shown? >>> class Foo: ... def __str__(self): ... return "instance...
[ "When you call print(foo), foo's __str__ method is called. __str__ is found in the class of foo, which is Foo. \nSimilarly, when you call print(Foo), Foo's __str__ method is called. __str__ is found in the class of Foo, which is normally type. You can change that using a metaclass:\nclass FooType(type):\n def __...
[ 6, 1, 0, 0 ]
[]
[]
[ "class", "instance", "python", "representation" ]
stackoverflow_0005086113_class_instance_python_representation.txt
Q: python - how do you store elements in a tuple how to store elements in a tuple? I did this: for i in range (0, capacity): for elements in self.table[i]: # STORE THE ALL THE ELEMENTS IN THE TUPLE A: tuples are immutable. You can create a tuple. But you cannot store elements to an already created tuple...
python - how do you store elements in a tuple
how to store elements in a tuple? I did this: for i in range (0, capacity): for elements in self.table[i]: # STORE THE ALL THE ELEMENTS IN THE TUPLE
[ "tuples are immutable. You can create a tuple. But you cannot store elements to an already created tuple. To create (or convert) your list of elements to a tuple. Just tuple() it.\nt = tuple([1,2,3])\n\nIn your case it is\nt = tuple(self.table[:capacity])\n\n", "Since you haven't told us - we can only guess what ...
[ 7, 1, 0 ]
[ "I think this is what you want.\nx = []\nfor i in range (0, capacity):\n for elements in self.table[i]:\n x.append(elements)\nt = tuple(x)\n\n" ]
[ -1 ]
[ "python", "store", "tuples" ]
stackoverflow_0005086714_python_store_tuples.txt
Q: ViewDoesNotExist Error i am trying to do a simple Django application where employee list is read from database and displayed. for that i defined the models and entered the values to database through Django admin. But while trying to display data from database i am stuck with an error, "ViewDoesNotExist at /employe...
ViewDoesNotExist Error
i am trying to do a simple Django application where employee list is read from database and displayed. for that i defined the models and entered the values to database through Django admin. But while trying to display data from database i am stuck with an error, "ViewDoesNotExist at /employeeProfile/ : Could not import...
[ "def employeeProfile(request):\n profile = EmployeeDetails.objects.all()\n return render_to_response('employeeProfile.html',{'emp_profile':emp_profile})\n\nYou named it profile on line 2, and then you tried to put it in the dictionary as emp_profile on line 3.\n", "from task.employeeDetails import emp_profi...
[ 3, 1, 1 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005086949_django_django_models_django_templates_django_views_python.txt
Q: Is it possible to generate an executable for Windows using bbfreeze (python) on a Linux platform? If so, how? There is a related question. The answer there suggests using PyInstaller. I'm looking at PyInstaller documentation. In the meanwhile, if somebody could specify how this could be done using bbfreeze that wo...
Is it possible to generate an executable for Windows using bbfreeze (python) on a Linux platform? If so, how?
There is a related question. The answer there suggests using PyInstaller. I'm looking at PyInstaller documentation. In the meanwhile, if somebody could specify how this could be done using bbfreeze that would be great, since we already have a deployment system in place that uses bbfreeze.
[ "It is not terribly likely. If I were you I would try to use the Windows PY2EXE inside WINE. If it works, you are golden, if not head to your local used laptops flea market and get an old Windows XP machine to do the job.\n" ]
[ 2 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0005075335_linux_python.txt
Q: Is this the preferred way to detect if the unicode or non-unicode version of cx_oracle was installed? I have a custom module that's basically a thin wrapper around a database connection with cx_Oracle. I'd like to re-use this module on computers with both the unicode version of cx_Oracle installed, and with the n...
Is this the preferred way to detect if the unicode or non-unicode version of cx_oracle was installed?
I have a custom module that's basically a thin wrapper around a database connection with cx_Oracle. I'd like to re-use this module on computers with both the unicode version of cx_Oracle installed, and with the non-unicode version. To do this, I need to "detect" the version installed. I could "try" making a connect...
[ "Using try ... except is a perfectly suitable way to do this kind of detection. The same technique is used to write portable apps using SQLITE that will work on newer 2.7 Python with SQLITE in the library and older 2.4 where SQLITE was an addon module with a more cryptic name.\n" ]
[ 1 ]
[]
[]
[ "cx_oracle", "python" ]
stackoverflow_0004961707_cx_oracle_python.txt
Q: InterfaceError: Error binding parameter 0 - probably unsupported type i have the following: class Tag( models.Model ): name = models.CharField( max_length=64 ) class Tag2Node( models.Model ): ip = models.IPAddressField( db_index=True ) tag = models.ForeignKey( Tag ) last_update = models.DateTimeF...
InterfaceError: Error binding parameter 0 - probably unsupported type
i have the following: class Tag( models.Model ): name = models.CharField( max_length=64 ) class Tag2Node( models.Model ): ip = models.IPAddressField( db_index=True ) tag = models.ForeignKey( Tag ) last_update = models.DateTimeField( auto_now=True ) class Node( models.Model ): id = models.CharFiel...
[ "The error comes from you passing a dictionary to get\nI'm not sure why this error doesn't throw something else instead...\nfound_ips = Tag2Node.objects.filter( tag__name=include ).values('ip').distinct()\n# values returns a dictionary\nq = Q( ip__exact=found_ips[0]['ip'] ) \nnodes = Node.objects.get( q )\n\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005086730_django_python.txt
Q: For functions that take in an indeterminate number of arguments in python, how to pass in an indeterminate number of arguments For example, say I have an indterminate number of sets I want to union: bigSet = bigSet.union(<listOfSets>) I could simply fold across each set, i.e. : bigSet = reduce(lambda x,y: x.union...
For functions that take in an indeterminate number of arguments in python, how to pass in an indeterminate number of arguments
For example, say I have an indterminate number of sets I want to union: bigSet = bigSet.union(<listOfSets>) I could simply fold across each set, i.e. : bigSet = reduce(lambda x,y: x.union(y), listOfSets) Another alternative is to use the eval function: stringTuple = str(listOfSets) stringTuple = stringTuple.strip("["...
[ "union accepts an arbitrary number of sets as arguments:\nIn [28]: x.union(set([1,2]),set([2,3]),set([3,4]))\nOut[28]: set([1, 2, 3, 4])\n\nTherefore, you can union a list of sets with\nbigSet = bigSet.union(*listOfSets)\n\nNote the asterisk.\n", "Looks like you want to expand a list of sets into argument list of...
[ 5, 0 ]
[]
[]
[ "functional_programming", "python", "set", "variables" ]
stackoverflow_0005087123_functional_programming_python_set_variables.txt
Q: Python and FIFOs I was trying to understand FIFOs using Python under linux and I found a strange behavior i don't understand. The following is fifoserver.py import sys import time def readline(f): s = f.readline() while s == "": time.sleep(0.0001) s = f.readline() return s while True:...
Python and FIFOs
I was trying to understand FIFOs using Python under linux and I found a strange behavior i don't understand. The following is fifoserver.py import sys import time def readline(f): s = f.readline() while s == "": time.sleep(0.0001) s = f.readline() return s while True: f = open(sys.argv...
[ "As other comments have alluded to, you have a race condition.\nI suspect that in the failing case, the server gets suspended after one of these lines:\ng.write(str(x**2) + \"\\n\")\ng.close()\n\nThe client is then able to read the result, print it to the screen, and loop back. It then reopens f - which succeeds, ...
[ 5, 0 ]
[]
[]
[ "broken_pipe", "fifo", "linux", "mkfifo", "python" ]
stackoverflow_0005084210_broken_pipe_fifo_linux_mkfifo_python.txt
Q: Difference between using ' and "? Possible Duplicates: Difference between the use of double quote and quotes in python Single quotes vs. double quotes in Python So I am now learning python, and was creating a function. What is the difference between using ' and ". I will create a sample function below to exempli...
Difference between using ' and "?
Possible Duplicates: Difference between the use of double quote and quotes in python Single quotes vs. double quotes in Python So I am now learning python, and was creating a function. What is the difference between using ' and ". I will create a sample function below to exemplify my question. def question(variable)...
[ "Both are equal and what you use is entirely your preference.\nAs far as the char vs string thing is concerned, refer to the Zen of Python, (PEP 20 or import this)\nSpecial cases aren't special enough to break the rules.\n\nA string of length 1 is not special enough to have a dedicated char type. \nNote that you ca...
[ 57, 16, 5 ]
[]
[]
[ "python", "quotes" ]
stackoverflow_0005087425_python_quotes.txt
Q: To find the number of syllables in a word I need to find out the number of syllables in a word from the English language using NLTK. This is the code I have so far: import curses from curses.ascii import isdigit import nltk from nltk.corpus import cmudict d = cmudict.dict() def nsyl(word): return [len(list...
To find the number of syllables in a word
I need to find out the number of syllables in a word from the English language using NLTK. This is the code I have so far: import curses from curses.ascii import isdigit import nltk from nltk.corpus import cmudict d = cmudict.dict() def nsyl(word): return [len(list(y for y in x if isdigit(y[-1]))) for x in d[wo...
[ "you need to put quotes around the word 'arithmetic'\n" ]
[ 17 ]
[]
[]
[ "nltk", "python" ]
stackoverflow_0005087493_nltk_python.txt
Q: Running three commands in the same process with Python I need to run those three commands for profiling/code coverage reporting on Win32. vsperfcmd /start:coverage /output:run.coverage helloclass vsperfcmd /shutdown I can't run one command by one because the helloclass executable should be profiled in the same pr...
Running three commands in the same process with Python
I need to run those three commands for profiling/code coverage reporting on Win32. vsperfcmd /start:coverage /output:run.coverage helloclass vsperfcmd /shutdown I can't run one command by one because the helloclass executable should be profiled in the same process of vsperfcmd. What I think of is to make a batch file...
[ "Interesting question.\nOne approach that works is to run a command shell and then pipe commands to it via stdin (example uses Python 3, for Python 2 you can skip the decode() call). Note that the command shell invocation is set up to suppress everything except explicit output written to stdout.\n>>> import subproc...
[ 7, 2 ]
[]
[]
[ "launch", "process", "python" ]
stackoverflow_0005087302_launch_process_python.txt
Q: Editor for use with GoogleAppEngineLauncher on Mac What editors are best for use with the "Edit" button in GoogleAppEngineLauncher for Mac? A good editor would preferably be able to edit Python and YAML and be able to open directories. A: Why not use your favorite editor? Textmate or gvim or emacs anything shoul...
Editor for use with GoogleAppEngineLauncher on Mac
What editors are best for use with the "Edit" button in GoogleAppEngineLauncher for Mac? A good editor would preferably be able to edit Python and YAML and be able to open directories.
[ "Why not use your favorite editor? Textmate or gvim or emacs anything should do here. All them support Python and YAML syntax.\n", "Aptana Studio 3 is really good. It's a little heavyweight, but does Python syntax highlighting and code completion, and YAML syntax highlighting.\n", "Have you tried TextWrangler ...
[ 4, 1, 0 ]
[]
[]
[ "directory", "editor", "google_app_engine", "python", "yaml" ]
stackoverflow_0005086239_directory_editor_google_app_engine_python_yaml.txt
Q: What's an elegant algorithm for fitting differently sized rectangles into a circle? I have a bunch of rectangles of variable size which I need to fit together roughly into a circle, presumably with the largest ones at the center. NB. The circle is not of a fixed size - that's just the overall shape I'm after. Thi...
What's an elegant algorithm for fitting differently sized rectangles into a circle?
I have a bunch of rectangles of variable size which I need to fit together roughly into a circle, presumably with the largest ones at the center. NB. The circle is not of a fixed size - that's just the overall shape I'm after. This is more like how I'd imagine a lazy human packs (once a piece is in place, it stays.) T...
[ "What do you mean \"ordered by size\" - length or area? I suppose it must be sorted by max length. \nHow do you \"find the edge closest to the origin which has space for rectangle\"? As far as I understand the task, you have rectangles sorted by the length of their longer side. You place the longest one at the orig...
[ 2, 0 ]
[]
[]
[ "algorithm", "packing", "python" ]
stackoverflow_0005087605_algorithm_packing_python.txt
Q: Python Tuple to JSON output How do I turn this: data = ((1, '2011-01-01'), (2, '2011-01-02'), (1, '2011-01-15'), (3, '2011-02-01')) into this: { "item": [ "1", "2", "1", "3", ], "settings": { "axisx": [ "2011-01-01", "2011-01-02", "2011-01-15", "2011-02...
Python Tuple to JSON output
How do I turn this: data = ((1, '2011-01-01'), (2, '2011-01-02'), (1, '2011-01-15'), (3, '2011-02-01')) into this: { "item": [ "1", "2", "1", "3", ], "settings": { "axisx": [ "2011-01-01", "2011-01-02", "2011-01-15", "2011-02-01" ], "axisy": [ ...
[ "Use the json library.\nThen convert your data using something like this:\nsomedict = { \"item\" : [ x[0] for x in data ],\n \"settings\" : { \"axisx\" : [ x[1] for x in data ],\n \"axisy\" : [ 0, 100],\n \"colour\" : \"ff9900\" }\n }\n...
[ 37, 13 ]
[]
[]
[ "json", "python" ]
stackoverflow_0005087903_json_python.txt
Q: startup script to check if external monitor is attached My first question here; normally I can find answers with a couple searches, but not this time. I want to write a script that will run on start up to check if an external monitor is attached to a laptop. I would like write the script in python. I'm using 32-...
startup script to check if external monitor is attached
My first question here; normally I can find answers with a couple searches, but not this time. I want to write a script that will run on start up to check if an external monitor is attached to a laptop. I would like write the script in python. I'm using 32-bit Ubuntu 10.04. I've searched around but can't really find ...
[ "The command xrandr should do the trick:\n$ xrandr -q\n...\nVGA-0 connected 1280x1024+0+26 ...\n ...\nLVDS connected 1400x1050+1280+0 ...\n ...\nDVI-0 disconnected ...\n\nInside your python script, run this command using the subprocess module, then search the output string for the screen identifier you're looki...
[ 4 ]
[]
[]
[ "detection", "hardware", "python" ]
stackoverflow_0005059337_detection_hardware_python.txt
Q: python error : 'module' object has no attribute 'AF_UNIX' this is my python code : if __name__ == '__main__': import socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(('0.0.0.0', 4000)) import time time.sleep(2) #sock.send('1') print sock.recv(1024...
python error : 'module' object has no attribute 'AF_UNIX'
this is my python code : if __name__ == '__main__': import socket sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(('0.0.0.0', 4000)) import time time.sleep(2) #sock.send('1') print sock.recv(1024) sock.close() it show : Traceback (most recent call l...
[ "While creating a socket object on Windows you should do:\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nAF_INET for Internet addresses, and AF_UNIX for UNIX inter-process communication. The latter is obviously only available on UNIX platforms.\nAlso, follow this example to find how to implement a simple...
[ 10 ]
[]
[]
[ "python", "sockets" ]
stackoverflow_0005088087_python_sockets.txt
Q: Using Python for a Wacom tablet on Mac & Linux I am shortly going to buy a Wacom Bamboo Pen&Touch, and I'd like to be able to access it from Python, preferably using PyQt. I've found a Python module for accessing it under windows (cgkit/wintab) and I've seen Python code for accessing it using GTK (GnomeTabletApps)...
Using Python for a Wacom tablet on Mac & Linux
I am shortly going to buy a Wacom Bamboo Pen&Touch, and I'd like to be able to access it from Python, preferably using PyQt. I've found a Python module for accessing it under windows (cgkit/wintab) and I've seen Python code for accessing it using GTK (GnomeTabletApps). Is there an equivalent for Mac? The Cocoa document...
[ "PySide's QTabletEvent works on Mac. I have also used it on Ubuntu.\nhttp://www.pyside.org/docs/pyside/PySide/QtGui/QTabletEvent.html#PySide.QtGui.QTabletEvent\n" ]
[ 0 ]
[]
[]
[ "macos", "python", "wacom" ]
stackoverflow_0002749514_macos_python_wacom.txt
Q: Variable updating one step behind in list searcher in Tkinter I'm trying to build a search engine that will check a list and then remove all list items that do not meet the search parameters. I know there is several problems with my program such as it will not add things back to the list when you backspace and in ...
Variable updating one step behind in list searcher in Tkinter
I'm trying to build a search engine that will check a list and then remove all list items that do not meet the search parameters. I know there is several problems with my program such as it will not add things back to the list when you backspace and in my updating for loop I simply tack on a '*' thinking that it will s...
[ "I believe I have run into this same problem you describe before, when attempting to make an actively searching ctrl-F feature in one of my programs.\nWhat I found to work is not bind on Key but instead KeyRelease. I'm not entirely sure why this works (probably just a quirk with Tkinter). However, it works. \nSnipp...
[ 0 ]
[]
[]
[ "listbox", "python", "tkinter", "user_interface" ]
stackoverflow_0005045546_listbox_python_tkinter_user_interface.txt
Q: Setting a property inside a Python method I want to set a read-only attribute inside a class method. I have already tried this: class Foo(object): def __init__(self, v): self._set('_v', v) def _set(self, attr, v): setattr(self, attr, v) setattr(Foo, attr[1:], property(lambda self: ...
Setting a property inside a Python method
I want to set a read-only attribute inside a class method. I have already tried this: class Foo(object): def __init__(self, v): self._set('_v', v) def _set(self, attr, v): setattr(self, attr, v) setattr(Foo, attr[1:], property(lambda self: getattr(self, attr))) but it is horrible. Is t...
[ "I think you're looking for python descriptors.\nclass MyDescriptor(object):\n def __init__(self, protected_attr_name):\n self.attr = protected_attr_name\n\n def __get__(self, obj, objtype):\n return getattr(obj, self.attr)\n\n def __set__(self, obj, value):\n #setattr(obj, self.attr, ...
[ 3, 2, 1, 1 ]
[]
[]
[ "class", "methods", "properties", "python" ]
stackoverflow_0005078726_class_methods_properties_python.txt
Q: How do I create a non-ascii dendrogram with Python? Trying to create a dendrogram with this found code block, and it works up until the call: r('mt_dist <- dist(t(mt))') then spouts the error: RPy_RException: Error in dist(t(mt)) : (list) object cannot be coerced to type 'double' up until that point it was look...
How do I create a non-ascii dendrogram with Python?
Trying to create a dendrogram with this found code block, and it works up until the call: r('mt_dist <- dist(t(mt))') then spouts the error: RPy_RException: Error in dist(t(mt)) : (list) object cannot be coerced to type 'double' up until that point it was looking good ... I'm probably missing something really simple...
[ "This is not answer to your RPy_... exception problem. Rather providing answer to your title How do I create a non-ascii dendrogram with Python?. You may try this to plot dendrogram.\n" ]
[ 1 ]
[]
[]
[ "dendrogram", "numpy", "python", "r", "rpy2" ]
stackoverflow_0005088498_dendrogram_numpy_python_r_rpy2.txt
Q: Special case of exception handling in Python I am trying to do some parsing on some text. I have the binary version of the parser to in my program'd body,I use call to run this parser and pass my sentences one by one. However, for some reasons sometimes the parser is not able to parse the sentence and generates an...
Special case of exception handling in Python
I am trying to do some parsing on some text. I have the binary version of the parser to in my program'd body,I use call to run this parser and pass my sentences one by one. However, for some reasons sometimes the parser is not able to parse the sentence and generates an error.It might be a bit difficult to put it into ...
[ "Check the return code of call. Is it any different when you get the exception compared to normal/correct execution? If you want to get an exception you could use check_call.\nAnother solution could be the usage of check_output to call the parser-program and examine the output.\nDocumentation for all functions: Pyt...
[ 0 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0005088924_exception_handling_python.txt
Q: how to match lines between pattern using re module in python I have a string (with multiple lines) which contains the following: "Name=My name Address=...... \##### To extract from here #### line 1 line 2 line 3 \##### To extract till here #### close" How do I extract the lines between "##### To extract *" string...
how to match lines between pattern using re module in python
I have a string (with multiple lines) which contains the following: "Name=My name Address=...... \##### To extract from here #### line 1 line 2 line 3 \##### To extract till here #### close" How do I extract the lines between "##### To extract *" string including the pattern as well? Output should be the following: \#...
[ "Ofir is right. Here's a corresponding example:\n>>> s = \"\"\"... your example string ...\"\"\"\n>>> marker1 = \"\\##### To extract from here ####\"\n>>> marker2 = \"\\##### To extract till here ####\"\n>>> a = s.find(marker1)\n>>> b = s.find(marker2, a + len(marker1))\n>>> print s[a:b]\n\\##### To extract from he...
[ 3, 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005088821_python_regex.txt
Q: Obtaining void template passing from django development server to apache server I've a django app that works perfectly under the django development server. Now I'm trying to run it under apache2.2 using the mod_wsgi. In the httpd.conf file of apache I've added: <IfModule wsgi_module> WSGIScriptAlias /index my_...
Obtaining void template passing from django development server to apache server
I've a django app that works perfectly under the django development server. Now I'm trying to run it under apache2.2 using the mod_wsgi. In the httpd.conf file of apache I've added: <IfModule wsgi_module> WSGIScriptAlias /index my_path_to_wsgi_modules/django.wsgi </IfModule> and the django.wsgi module contains all...
[ "Finally I found the error. It was not connected to httpd.conf file but to how URLs are specified both to django urls.py file and to templates. As I mounted myapp in this way:\nWSGIScriptAlias /myapp my_path_to_wsgi_module/django.wsgi\n\nI was believing that URLs specified in django template files should carry an i...
[ 0 ]
[]
[]
[ "apache", "django", "django_urls", "mod_wsgi", "python" ]
stackoverflow_0005041583_apache_django_django_urls_mod_wsgi_python.txt
Q: Is there any way of assigning vars inside an if condition in python Is there any way of assigning vars inside an if condition in python like: if (i=variable)!='literal' : A: No. i = variable if i != 'literal': whatever A: In the python grammar, assignment is a statement, and a statement can never appear in...
Is there any way of assigning vars inside an if condition in python
Is there any way of assigning vars inside an if condition in python like: if (i=variable)!='literal' :
[ "No.\ni = variable\nif i != 'literal':\n whatever\n\n", "In the python grammar, assignment is a statement, and a statement can never appear inside an expression, so no.\nExcept, if you were truly, truly evil, you could do something like this:\nif (var.i = value) != 'literal': pass\n\nWhere var was an object wi...
[ 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005089311_python.txt
Q: Python string processing, Unicode & Beautiful Soup I've been searching for solutions to a bug that I have but haven't found/understood one that will work. Essentially, if I use the string functions (translate, strip, etc.) I get Unicode errors (ascii' codec can't encode character 'x' in position y: ordinal not in ...
Python string processing, Unicode & Beautiful Soup
I've been searching for solutions to a bug that I have but haven't found/understood one that will work. Essentially, if I use the string functions (translate, strip, etc.) I get Unicode errors (ascii' codec can't encode character 'x' in position y: ordinal not in range(128) . But when I try Beautiful Soup to process te...
[ "You are mixing str objects with unicode objects, which leads the Python interpreter to coerce one into the other. String/Unicode coercion requires an encoding, which is assumed to be ascii by default. When this assumption doesn't hold, you get this kind of errors.\nThe general solution is not to mix str with unico...
[ 5 ]
[]
[]
[ "beautifulsoup", "python", "string", "unicode" ]
stackoverflow_0005088511_beautifulsoup_python_string_unicode.txt
Q: Converting a Python script to Objective-C I recently asked this question to create a function for optimal word-wrapping and got the response I was looking for in this Python script. Unfortunately, I don't speak Python. :D Can someone help me convert this to Objective-C? _ Code. I took the liberty of modifying t...
Converting a Python script to Objective-C
I recently asked this question to create a function for optimal word-wrapping and got the response I was looking for in this Python script. Unfortunately, I don't speak Python. :D Can someone help me convert this to Objective-C? _ Code. I took the liberty of modifying the DP always to return exactly n lines, at the ...
[ "Here's the function translated to Objective-C. It's been updated to compile but only barely tested for correctness (on the example given in your previous question: [... minragged:@\"Just testing to see how this works.\" lineCount:3]). Nothing regarding efficiency or Objective-C idioms has been taken in to account....
[ 1 ]
[]
[]
[ "iphone", "objective_c", "python" ]
stackoverflow_0005075203_iphone_objective_c_python.txt
Q: AppEngine - Writes are limited to 1 per second I'm looking into using the AppEngine DataStore for a database system, but I'm confused by this quote in the documentation: "This allows queries on a single guestbook to be strongly consistent, but also limits changes to the guestbook to 1 write per second (the support...
AppEngine - Writes are limited to 1 per second
I'm looking into using the AppEngine DataStore for a database system, but I'm confused by this quote in the documentation: "This allows queries on a single guestbook to be strongly consistent, but also limits changes to the guestbook to 1 write per second (the supported limit for entity groups)." Source: http://code.go...
[ "Hey, nope, having a reference to another entity and belonging to the same entity group as another entity are two independent things.\nEntities belong to the same entity group only if you explicitly supply a parent argument when you instantiate either of them. Modeling an entity class so that it has a reference to...
[ 7 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005089485_google_app_engine_python.txt
Q: python & lxml: adding empty element into an etree How can I add an empty element like <br/> to an ElementTree in Python? Thanks! A: The same way you would add a non-empty element. >>> from lxml import etree >>> f = etree.fromstring('<document></document>') >>> ele = etree.Element('br') # the element to be inse...
python & lxml: adding empty element into an etree
How can I add an empty element like <br/> to an ElementTree in Python? Thanks!
[ "The same way you would add a non-empty element.\n>>> from lxml import etree\n>>> f = etree.fromstring('<document></document>')\n>>> ele = etree.Element('br') # the element to be inserted\n>>> f.insert(0, ele)\n>>> print etree.tostring(f, pretty_print=True)\n<document>\n <br/>\n</document>\n\n" ]
[ 5 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0005089616_lxml_python.txt
Q: mysqldb not installing Hi i am using python 2.7 working on windows 7. I have changed registry_key = SOFTWARE\MySQL AB\MySQL Server 5.1 in site.cfg, and i apended the ld_args.append(‘/MANIFEST’) in msvc9compiler.py. But still i got this error please help what i have to do ... Traceback (most recent call last): Fi...
mysqldb not installing
Hi i am using python 2.7 working on windows 7. I have changed registry_key = SOFTWARE\MySQL AB\MySQL Server 5.1 in site.cfg, and i apended the ld_args.append(‘/MANIFEST’) in msvc9compiler.py. But still i got this error please help what i have to do ... Traceback (most recent call last): File "C:\MySQL-python-1.2.3\se...
[ "Why not just use a precompiled binaries. You can get them for example here : https://www.lfd.uci.edu/~gohlke/pythonlibs/\n" ]
[ 2 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0005089697_django_mysql_python.txt
Q: How to update version of Python? I had Python2.6 on my Windows 7 and I just installed Python2.7. As a result I have "C:\Python26" and "C:\Python27". My problem is that system still tries to use the old version. For example if I type Python --version I get "Python 2.6.4". Or, if I try to install "numpy" it find the...
How to update version of Python?
I had Python2.6 on my Windows 7 and I just installed Python2.7. As a result I have "C:\Python26" and "C:\Python27". My problem is that system still tries to use the old version. For example if I type Python --version I get "Python 2.6.4". Or, if I try to install "numpy" it find the old version and does not allow me to ...
[ "You need to change Python path to the new version.\nhttp://docs.python.org/using/windows.html#excursus-setting-environment-variables\n" ]
[ 6 ]
[]
[]
[ "installation", "python", "version", "windows" ]
stackoverflow_0005089939_installation_python_version_windows.txt
Q: Changing wallpapers in python I'm running a Maverick on my machine, and I'm trying to write a script to change wallpapers in python. Heres my progress so far. import gconf client = gconf.client_get_default() current_bg = client.get_string("/desktop/gnome/background/picture_filename") client.set_string("/desktop/...
Changing wallpapers in python
I'm running a Maverick on my machine, and I'm trying to write a script to change wallpapers in python. Heres my progress so far. import gconf client = gconf.client_get_default() current_bg = client.get_string("/desktop/gnome/background/picture_filename") client.set_string("/desktop/gnome/background/picture_filename",...
[ "The problem is probably that you're missing a / at the beginning of home/tsudot/Pictures/zombie.jpg so the file isn't found. To avoid this problem happening in the future, you could perhaps change your code to keep the filename in a variable and check before trying to set the config option that that file exists w...
[ 6 ]
[]
[]
[ "gconf", "python" ]
stackoverflow_0005090009_gconf_python.txt
Q: Handling default parameters in cython I am wrapping some c++ code using cython, and I am not sure what is the best best way to deal with parameters with default values. In my c++ code I have function for which the parameters have default values. I would like to wrap these in such a way that these default values g...
Handling default parameters in cython
I am wrapping some c++ code using cython, and I am not sure what is the best best way to deal with parameters with default values. In my c++ code I have function for which the parameters have default values. I would like to wrap these in such a way that these default values get used if the parameters are not given. I...
[ "You could declare the function with different parameters (\"cppcode.pxd\"):\ncdef extern from \"cppcode.hpp\":\n int init(char *address, int port, bint en_msg, int error)\n int init(char *address, int port, bint en_msg)\n int init(char *address, int port)\n int init(char *address)\n int init()\...
[ 17 ]
[]
[]
[ "c++", "cython", "python" ]
stackoverflow_0005081678_c++_cython_python.txt
Q: plotting with matplotlib from a module It's the first time I'm using python to plot and I guess I don't quite understand the interactions between objects in matplotlib. I'm having the following module: import numpy as np import matplotlib.pyplot as plt def plotSomething(x,y): fig = plt.figure() ax = fig.a...
plotting with matplotlib from a module
It's the first time I'm using python to plot and I guess I don't quite understand the interactions between objects in matplotlib. I'm having the following module: import numpy as np import matplotlib.pyplot as plt def plotSomething(x,y): fig = plt.figure() ax = fig.add_subplot(111) ax.set_xscale("log", non...
[ "What is happening is likely related to Python's garbage collection. I can't tell you exactly what is going on because the provided code sample never renders the plot. I'm guessing that you are rendering it outside the function, in which case, you are effectively doing a del fig before rendering (drawing).\nThis ...
[ 2, 1 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0005089994_matplotlib_python.txt
Q: applying a filter on a string in python I have a user typing in his username and I only want valid strings to pass through, meaning only characters in [a-zA-Z0-9]. I am pretty new to python and unsure of the syntax. Here's an example of what I want in code, which is to check through the username and return false u...
applying a filter on a string in python
I have a user typing in his username and I only want valid strings to pass through, meaning only characters in [a-zA-Z0-9]. I am pretty new to python and unsure of the syntax. Here's an example of what I want in code, which is to check through the username and return false upon a illegal character.: def _checkInput(inp...
[ "There is a method in string called isalnum. It does what you are trying to achieve.\nIn [7]: 'ab123fd'.isalnum()\nOut[7]: True\n\nIn [8]: 'ab123fd **'.isalnum()\nOut[8]: False\n\n", "You need isalnum:\n>>> name = raw_input('Enter your name: ')\nEnter your name: foo_bar\n>>> name.isalnum()\nFalse\n>>> name = raw_...
[ 5, 4, 4, 0, 0, 0, 0 ]
[]
[]
[ "alphanumeric", "input", "python", "string" ]
stackoverflow_0005089770_alphanumeric_input_python_string.txt
Q: how to import mysqldb I have installed MySqldb through .exe(precompiled). Its is stored in site-packages. But now i don't know how to test, that it is accessable or not. And major problem how to import in my application like import MySqldb. Help me i am very new techie in python i just want to work with my existin...
how to import mysqldb
I have installed MySqldb through .exe(precompiled). Its is stored in site-packages. But now i don't know how to test, that it is accessable or not. And major problem how to import in my application like import MySqldb. Help me i am very new techie in python i just want to work with my existing Mysql. Thanks in advance....
[ "Just open your CMD/Console, type python, press Enter, type import MySQLdb and then press Enter again.\nIf no error is shown, you're ok!\n" ]
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005090870_mysql_python.txt
Q: NameError - global name not defined I am trying to read some data from html forms and insert it into database. Doing so i am stuck with this error "NameError at /createEmployee/ : global name 'get_post_param' is not defined" ; i will paste my code here. Can somebody help me to solve this. VIEWS.PY def createEmplo...
NameError - global name not defined
I am trying to read some data from html forms and insert it into database. Doing so i am stuck with this error "NameError at /createEmployee/ : global name 'get_post_param' is not defined" ; i will paste my code here. Can somebody help me to solve this. VIEWS.PY def createEmployee(request): if request.method == "P...
[ "This is a very simple problem. You have not defined get_post_param.\nWhere did you get this get_post_param idea?\nSimply define a function called get_post_param to fix it..\nHere's a python shell session\n>>> get_post_param(request, 'userName')\nNameError: not defined\n\n>>> def get_post_param(request, param):\n.....
[ 5 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0005090349_django_django_models_django_templates_django_views_python.txt
Q: UnicodeDecodeError when sending mail using AppEngine I'm using App Engine's mail.EmailMessage where my subject param is a Unicode object including non-ASCII chars (åäö). I get the following error: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/log...
UnicodeDecodeError when sending mail using AppEngine
I'm using App Engine's mail.EmailMessage where my subject param is a Unicode object including non-ASCII chars (åäö). I get the following error: Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/logging/__init__.py", line 765, in emit self.stream.write...
[ "I was running App Engine using Python 2.6 instead of 2.5. In 2.5, it works as expected.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python", "unicode" ]
stackoverflow_0005066027_google_app_engine_python_unicode.txt
Q: blocking sockets and select i'm playing around with sockets, and I'm having some doubts about using blocking sockets with select.Let's assume i'm only tracking potential readers. Am I right in thinking that select will go through the first socket in the list and if some data is available it will return and if not...
blocking sockets and select
i'm playing around with sockets, and I'm having some doubts about using blocking sockets with select.Let's assume i'm only tracking potential readers. Am I right in thinking that select will go through the first socket in the list and if some data is available it will return and if not it will block until select's tim...
[ "The select() C API returns a list of all sockets that are currently readable. Assuming python's wrapper does the same, sread will contain multiple elements if multiple sockets are readable.\nA blocking socket will only block if there is no data present, so after a select() call indicated there is data, you can ass...
[ 5, 2 ]
[]
[]
[ "ipc", "linux", "network_programming", "python", "sockets" ]
stackoverflow_0005091441_ipc_linux_network_programming_python_sockets.txt
Q: how to replace regular expression based on the match results (e.g. a special function)? i have a search expression with 1-2 groups. i need to substitute each result with something that depends on the result value. e.g. in the following string, replace each matched digit with it's value * 3. s = 'a4cd5cd782cd' reg ...
how to replace regular expression based on the match results (e.g. a special function)?
i have a search expression with 1-2 groups. i need to substitute each result with something that depends on the result value. e.g. in the following string, replace each matched digit with it's value * 3. s = 'a4cd5cd782cd' reg = '([1-9])cd' def f(x): return str(int(x)*3) expected result: 'a12cd15cd786cd' how can i s...
[ ">>> import re\n>>> s = 'a4cd5cd782cd'\n>>> reg = r'([1-9])cd'\n>>> def f(x): return str(int(x.group(1))*3)+\"cd\"\n...\n>>> re.sub(reg, f, s)\n'a12cd15cd786cd'\n\nRead the docs here.\n", "Look at the re.sub() method:\nhttp://docs.python.org/library/re.html\n(including an example on calling callback method for ea...
[ 3, 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005091603_python_regex.txt
Q: In Python, partial function application (currying) versus explicit function definition In Python, is it considered better style to: explicitly define useful functions in terms of more general, possibly internal use, functions; or, use partial function application to explicitly describe function currying? I will ...
In Python, partial function application (currying) versus explicit function definition
In Python, is it considered better style to: explicitly define useful functions in terms of more general, possibly internal use, functions; or, use partial function application to explicitly describe function currying? I will explain my question by way of a contrived example. Suppose one writes a function, _sort_by_s...
[ "If you want to have the curried functions as part of a public interface, use explicit function definitions. This has the following additional advantages:\n\nIt is easier to assign a docstring to an explicit function definition. For partial() functions, you would have to assign to the __doc__ attribute, which is ...
[ 13, 2 ]
[]
[]
[ "currying", "functional_programming", "partial_application", "python" ]
stackoverflow_0005091528_currying_functional_programming_partial_application_python.txt
Q: How to make django messages StackOverflow style? I'd like to use Django's Messages module, however, I would like my messages to persist until the user clicks an X next to the message as opposed to having messages disappear as soon as the user reloads the page. I am stumped with two issues: How do I make the messag...
How to make django messages StackOverflow style?
I'd like to use Django's Messages module, however, I would like my messages to persist until the user clicks an X next to the message as opposed to having messages disappear as soon as the user reloads the page. I am stumped with two issues: How do I make the messages' context processor not delete the messages once the...
[ "In your case django.contrib.messages won't bring you anywhere good. It's a message system inspired by RoR flash system, where messages aren't supposed to stay around\nYou should create your own messaging system (django-persistent-messages maybe?) that would save messages for registered users in database.\n\nIt's a...
[ 8, 7, 4, 2 ]
[]
[]
[ "ajax", "django", "django_users", "python" ]
stackoverflow_0003076365_ajax_django_django_users_python.txt
Q: Adding an element (vector) to a list in rpy2 In R, I can add elements to a list easily: mylist = list() mylist[[1]] = c(1,2) mylist[[2]] = c(2,3) mylist[[length(mylist)+1]] = c(3,4) How do I do this in rpy2? I am using rpy2 2.1.9. I tried the following but it doesn't work import rpy2.robjects as robjects a = robj...
Adding an element (vector) to a list in rpy2
In R, I can add elements to a list easily: mylist = list() mylist[[1]] = c(1,2) mylist[[2]] = c(2,3) mylist[[length(mylist)+1]] = c(3,4) How do I do this in rpy2? I am using rpy2 2.1.9. I tried the following but it doesn't work import rpy2.robjects as robjects a = robjects.r('list()') b = robjects.IntVector([1,2]) a[0...
[ "If you want to use R's \"[[<-\" operator, you'll have to call the method rx2()\n(see [assigning, R-style][1]).\nIn rpy2-2.2.0dev, you can do a.rx2[1] = b.\n[1]: http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html#assigning-r-style assigning, R-style\n", "I'm not sure that you can do this with the current ve...
[ 5, 1 ]
[]
[]
[ "list", "python", "r", "rpy2", "vector" ]
stackoverflow_0005085439_list_python_r_rpy2_vector.txt
Q: send form values to mysql database I have installed MySQLdb in python2.7(64bit), I want to know how I can send form values to MySQL database. A: Start with reading. http://docs.djangoproject.com/en/1.2/intro/tutorial01/ http://docs.djangoproject.com/en/1.2/intro/tutorial02/ http://docs.djangoproject.com/en/1.2/...
send form values to mysql database
I have installed MySQLdb in python2.7(64bit), I want to know how I can send form values to MySQL database.
[ "Start with reading.\nhttp://docs.djangoproject.com/en/1.2/intro/tutorial01/\nhttp://docs.djangoproject.com/en/1.2/intro/tutorial02/\nhttp://docs.djangoproject.com/en/1.2/intro/tutorial03/\nhttp://docs.djangoproject.com/en/1.2/intro/tutorial04/\nOnce you've understood that then you can look at the forms documentati...
[ 3 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0005091914_django_mysql_python.txt
Q: A better way than eval() when translating keyword arguments in QuerySets (Python/Django) I'm using django-transmeta (couldn't get anything else working better with django 1.2.5) which creates several columns in a table like: content_en, content_es, content_it Before implementing i18n I had: items = Items.objects.f...
A better way than eval() when translating keyword arguments in QuerySets (Python/Django)
I'm using django-transmeta (couldn't get anything else working better with django 1.2.5) which creates several columns in a table like: content_en, content_es, content_it Before implementing i18n I had: items = Items.objects.filter(categories__slug=slug) now category.slug is internationalized therefore I have "categor...
[ "Try\nq = Q(**{\"categories__slug_\" + current_lang + \"__contains\": slug})\nitems = Items.objects.filter(q)\n\n" ]
[ 11 ]
[]
[]
[ "django", "eval", "python" ]
stackoverflow_0005092336_django_eval_python.txt
Q: Expanding a path from a graph I know there are modules for this type of structure, but I like and prefer to learn how things really works by myself. So... I've being trying to expand a path from a graph, such as for example: g = dict( s=['a','d','s'], a=['s','d','b'], d=['s','a','e'], b=['a','e','...
Expanding a path from a graph
I know there are modules for this type of structure, but I like and prefer to learn how things really works by myself. So... I've being trying to expand a path from a graph, such as for example: g = dict( s=['a','d','s'], a=['s','d','b'], d=['s','a','e'], b=['a','e','c'], e=['d','b','f'], f=['e...
[ "Here's a modification of @tangentstorm's answer that avoids raising explicit exception by using a generator:\ndef pathiter(adjacent_vertexes, start, end, path=None):\n if path is None: path = (start,)\n\n for vertex in adjacent_vertexes[start]:\n if vertex == end:\n yield path + (vertex,)\n...
[ 4, 1, 1 ]
[]
[]
[ "graph", "python" ]
stackoverflow_0005086062_graph_python.txt