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: Upload a potentially huge textfile to a plain WSGI-server in Python I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible. A: wsg...
Upload a potentially huge textfile to a plain WSGI-server in Python
I need to upload a potentially huge plain-text file to a very simple wsgi-app without eating up all available memory on the server. How do I accomplish that? I want to use standard python modules and avoid third-party modules if possible.
[ "wsgi.input should be a file like stream object. You can read from that in blocks, and write those blocks directly to disk. That shouldn't use up any significant memory.\nOr maybe I misunderstood the question?\n", "If you use the cgi module to parse the input (which most frameworks use, e.g., Pylons, WebOb, Cherr...
[ 3, 2, 0 ]
[]
[]
[ "file", "python", "upload", "wsgi" ]
stackoverflow_0001103940_file_python_upload_wsgi.txt
Q: python web programming I started learning Python through some books and online tutorials. I understand the basic syntax and operations, but I realize that the correct way to understand the language would be to actually do a project on it. Now when i say a project, I mean something useful, maybe some web app. I sta...
python web programming
I started learning Python through some books and online tutorials. I understand the basic syntax and operations, but I realize that the correct way to understand the language would be to actually do a project on it. Now when i say a project, I mean something useful, maybe some web app. I started searching for web progr...
[ "+1 for django, though the \"django book\" is a little simpler to understand (especially if you're just getting start with python): http://www.djangobook.com/en/2.0/\n", "If you want to create a powerful web application with Python, Django is the way to go. You can start with the documentation at http://docs.djan...
[ 6, 4, 2, 2, 2, 2, 0, 0 ]
[]
[]
[ "python", "web_applications" ]
stackoverflow_0001209092_python_web_applications.txt
Q: Dictionary with classes? In Python is it possible to instantiate a class through a dictionary? shapes = {'1':Square(), '2':Circle(), '3':Triangle()} x = shapes[raw_input()] I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then ...
Dictionary with classes?
In Python is it possible to instantiate a class through a dictionary? shapes = {'1':Square(), '2':Circle(), '3':Triangle()} x = shapes[raw_input()] I want to let the user pick from a menu and not code huge if else statements on the input. For example if the user entered 2, x would then be a new instance of Circle. ...
[ "Almost. What you want is\nshapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict\n\nx = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.\n\n", "I'd recommend a chooser function:\ndef choose(optiondict, prompt='Choose one:'):\n print prompt\n ...
[ 30, 2 ]
[]
[]
[ "class", "dictionary", "python" ]
stackoverflow_0001208322_class_dictionary_python.txt
Q: How to find number of users, number of users with a profile object, and monthly logins in Django Is there an easy way in Django to find the number of Users, Number of Users with profile objects, and ideally number of logins per month (but could do this with Google Analytics). I can see all the data is there in the...
How to find number of users, number of users with a profile object, and monthly logins in Django
Is there an easy way in Django to find the number of Users, Number of Users with profile objects, and ideally number of logins per month (but could do this with Google Analytics). I can see all the data is there in the admin interface, but I'm unsure of how to get to it in Python land. Has anyone seen any examples of ...
[ "Count the number of users:\nimport django.contrib.auth\ndjango.contrib.auth.models.User.objects.all().count()\n\nYou can use the same to count the number of profile objects (assuming every user has at most 1 profile), e.g. if Profile is the profile model:\nProfile.objects.all().count()\n\nTo count the number of lo...
[ 1 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0001210099_admin_django_python.txt
Q: Formatting text into boxes in the Python Shell I've created a basic menu class that looks like this: class Menu: def __init__(self, title, body): self.title = title self.body = body def display(self): #print the menu to the screen What I want to do is format the title and the body ...
Formatting text into boxes in the Python Shell
I've created a basic menu class that looks like this: class Menu: def __init__(self, title, body): self.title = title self.body = body def display(self): #print the menu to the screen What I want to do is format the title and the body so they fit inside premade boxes almost. Where no m...
[ "#!/usr/bin/env python\n\ndef format_box(title, body, width=80):\n box_line = lambda text: \"* \" + text + (\" \" * (width - 6 - len(text))) + \" *\"\n\n print \"*\" * width\n print box_line(title)\n print \"*\" * width\n print box_line(\"\")\n\n for line in body.split(\"\\n\"):\n print b...
[ 4, 0 ]
[]
[]
[ "formatting", "python", "shell" ]
stackoverflow_0001203036_formatting_python_shell.txt
Q: outer join modelisation in django I have a many to many relationship table whith some datas in the jointing base a basic version of my model look like: class FooLine(models.Model): name = models.CharField(max_length=255) class FooCol(models.Model): name = models.CharField(max_length=255) class FooVal(mod...
outer join modelisation in django
I have a many to many relationship table whith some datas in the jointing base a basic version of my model look like: class FooLine(models.Model): name = models.CharField(max_length=255) class FooCol(models.Model): name = models.CharField(max_length=255) class FooVal(models.Model): value = models.CharFiel...
[ "Outer joins can be viewed as a hack because SQL lacks \"navigation\". \nWhat you have is a simple if-statement situation.\nfor line in someRangeOfLines:\n for col in someRangeOfCols:\n try:\n cell= FooVal.objects().get( col = col, line = line )\n except FooVal.DoesNotExist:\n ...
[ 0 ]
[]
[]
[ "django", "outer_join", "python", "request" ]
stackoverflow_0001209947_django_outer_join_python_request.txt
Q: help me eliminate a for-loop in python There has to be a faster way of doing this. There is a lot going on here, but it's fairly straightforward to unpack. Here is the relevant python code (from scipy import *) for i in arange(len(wav)): result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) ) There are a...
help me eliminate a for-loop in python
There has to be a faster way of doing this. There is a lot going on here, but it's fairly straightforward to unpack. Here is the relevant python code (from scipy import *) for i in arange(len(wav)): result[i] = sum(laser_flux * exp(-(wav[i] - laser_wav)**2) ) There are a bunch of arrays. result -- array of length...
[ "You're going to want to use Numpy arrays (if you're not already) to store your data. Then, you can take advantage of array broadcasting with np.newaxis. For each value in wav, you're going to want to compute a difference between that value and each value in laser_wav. That suggests that you'll want a two-dimen...
[ 13, 2, 1, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0001210509_for_loop_python.txt
Q: usage of generators as a progression notifier I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant... Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction...
usage of generators as a progression notifier
I am currently using generators as a quick way to get the progress of long processes and I'm wondering how is it done usually as I find it not very elegant... Let me explain first, I have a engine.py module that do some video processing (segmentation, bg/fg subtraction, etc) which takes a lot of time (from seconds to s...
[ "Using a generator is fine for this, but the whole point of using generators is so you can builtin syntax:\nfor f in self.engine.processMovie():\n c, s = dlg.Update(f, \"Processing frame %d\"%f)\n if not c: break\n\nIf you don't care about that, then you can either say:\nfor f in self.engine.processMovie(): p...
[ 2, 1, 0 ]
[]
[]
[ "generator", "progress_bar", "python" ]
stackoverflow_0001211035_generator_progress_bar_python.txt
Q: downloading files to users machine? I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it so...
downloading files to users machine?
I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really d...
[ "You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be.\nYou can do one of two things:\n\ncount on the browser to cache the media file\nserve the media via some 3rd party plugin (Flash, for example)\n\n", "Don't do this...
[ 4, 2, 0 ]
[]
[]
[ "django", "python", "web_applications" ]
stackoverflow_0001211363_django_python_web_applications.txt
Q: Django .."join" query? guys, how or where is the "join" query in Django? i think that Django dont have "join"..but how ill make join? Thanks A: If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model. A: Look ...
Django .."join" query?
guys, how or where is the "join" query in Django? i think that Django dont have "join"..but how ill make join? Thanks
[ "If you're using models, the select_related method will return the object for any foreign keys you have set up (up to a limit you specify) within that model.\n", "Look into model relationships and accessing related objects.\n" ]
[ 4, 1 ]
[ "SQL Join queries are a hack because SQL doesn't have objects or navigation among objects.\nObjects don't need \"joins\". Just access the related objects.\n" ]
[ -10 ]
[ "django", "python" ]
stackoverflow_0001210711_django_python.txt
Q: Moving values but preserving order in a Python list I have a list a=[1,2,3,4,5] and want to 'move' its values so it changes into a=[2,3,4,5,1] and the next step a=[3,4,5,1,2] Is there a built-in function in Python to do that? Or is there a shorter or nicer way than b=[a[-1]]; b.extend(a[:-1]); a=b A: >>> a =...
Moving values but preserving order in a Python list
I have a list a=[1,2,3,4,5] and want to 'move' its values so it changes into a=[2,3,4,5,1] and the next step a=[3,4,5,1,2] Is there a built-in function in Python to do that? Or is there a shorter or nicer way than b=[a[-1]]; b.extend(a[:-1]); a=b
[ ">>> a = [1,2,3,4,5]\n>>> a.append(a.pop(0))\n>>> a\n[2, 3, 4, 5, 1]\n\nThis is expensive, though, as it has to shift the contents of the entire list, which is O(n). A better choice may be to use collections.deque if it is available in your version of Python, which allow objects to be inserted and removed from eit...
[ 25 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001212025_list_python.txt
Q: m2crypto throws "TypeError: in method 'x509_req_set_pubkey'" My little code snippet throws the following Traceback: Traceback (most recent call last): File "csr.py", line 48, in <module> csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_reque...
m2crypto throws "TypeError: in method 'x509_req_set_pubkey'"
My little code snippet throws the following Traceback: Traceback (most recent call last): File "csr.py", line 48, in <module> csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_request.set_pubkey(EVP.PKey(keypair)) File "/usr/lib64/python2.6/site...
[ "If I change \"cert_request.set_pubkey(EVP.PKey(keypair))\" to \"cert_request.set_pubkey(keypair)\" I receive the following Traceback instead. This confuses me even more... \nTraceback (most recent call last):\n File \"csr.py\", line 48, in <module>\n csr.create_cert_signing_request(pubkey, cert_name)\n File \...
[ 0 ]
[]
[]
[ "m2crypto", "python" ]
stackoverflow_0001211843_m2crypto_python.txt
Q: How to create a property with its name in a string? Using Python I want to create a property in a class, but having the name of it in a string. Normally you do: blah = property(get_blah, set_blah, del_blah, "bleh blih") where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with th...
How to create a property with its name in a string?
Using Python I want to create a property in a class, but having the name of it in a string. Normally you do: blah = property(get_blah, set_blah, del_blah, "bleh blih") where get_, set_ and del_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this: setattr(...
[ "As much I would say, the difference is, that in the first version, you change the classes attribute blah to the result of property and in the second you set it at the instance (which is different!).\nHow about this version:\nsetattr(MyClass, \"blah\", property(self.get_blah, self.set_blah,\n self.del_blah, ...
[ 2, 1, 1 ]
[]
[]
[ "properties", "python", "setattr" ]
stackoverflow_0001212434_properties_python_setattr.txt
Q: How to get information about a function and call it I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :( A: Try hasattr >>> help(hasattr) Help on ...
How to get information about a function and call it
I want to make a function that detects if a method exists for given instance, what are the parameters that can be passed in and then call the method with proper parameters. I am novice and I have no idea how to do it :(
[ "Try hasattr\n>>> help(hasattr)\nHelp on built-in function hasattr in module __builtin__:\n\nhasattr(...)\n hasattr(object, name) -> bool\n\n Return whether the object has an attribute with the given name.\n (This is done by calling getattr(object, name) and catching exceptions.)\n\nFor more advanced intro...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001212649_python.txt
Q: Threaded application + IntegrityError I have python threaded application + Postgres. I am using Django's ORM to save to Postgres.. I have concurrent save calls. Occasionally 2 threads save with the same primary key which leads to an issue. Postgres log: ERROR: duplicate key value violates unique constraint "sto...
Threaded application + IntegrityError
I have python threaded application + Postgres. I am using Django's ORM to save to Postgres.. I have concurrent save calls. Occasionally 2 threads save with the same primary key which leads to an issue. Postgres log: ERROR: duplicate key value violates unique constraint "store_pkey" STATEMENT: INSERT INTO "store" ("...
[ "Just to make sure, you're using strings for primary keys if I understand correctly?\n\nAttributeError: 'NoneType' object has no attribute 'cursor'\n\nThis means there's an error in some Python code. Have you tried using another version or revision of Django or searching the Django trac for your bug? It isn't so un...
[ 2 ]
[]
[]
[ "django", "postgresql", "python", "thread_safety" ]
stackoverflow_0001212864_django_postgresql_python_thread_safety.txt
Q: Django transaction.commit_on_success not rolling back transaction I'm trying to use Django transactions on MySQL with the commit_on_success decorator. According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, this doesn't seem to work for me: >...
Django transaction.commit_on_success not rolling back transaction
I'm trying to use Django transactions on MySQL with the commit_on_success decorator. According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, this doesn't seem to work for me: >>> @transaction.commit_on_success ... def fails(): ... Site.objects...
[ "From http://docs.djangoproject.com/en/dev/ref/databases/:\n\"The default engine is MyISAM [1]. The main drawback of MyISAM is that it doesn't currently support transactions or foreign keys. On the plus side, it's currently the only engine that supports full-text indexing and searching.\n\"The InnoDB engine is full...
[ 8, 3 ]
[]
[]
[ "django", "mysql", "python", "transactions" ]
stackoverflow_0001214143_django_mysql_python_transactions.txt
Q: Making tabulation look different than just whitespace How to make tabulation look different than whitespace in vim (highlighted for example). That would be useful for code in Python. A: I use something like this: set list listchars=tab:»·,trail:·,precedes:…,extends:…,nbsp:‗ Requires Vim7 and I'm not sure how we...
Making tabulation look different than just whitespace
How to make tabulation look different than whitespace in vim (highlighted for example). That would be useful for code in Python.
[ "I use something like this:\nset list listchars=tab:»·,trail:·,precedes:…,extends:…,nbsp:‗\n\nRequires Vim7 and I'm not sure how well this is going to show up in a browser, because it uses some funky Unicode characters. It's good to use some oddball characters so that you can distinguish a tab from something you m...
[ 16, 7, 5, 3, 2, 2 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0001192480_python_vim.txt
Q: Basic Python dictionary question I have a dictionary with one key and two values and I want to set each value to a separate variable. d= {'key' : ('value1, value2'), 'key2' : ('value3, value4'), 'key3' : ('value5, value6')} I tried d[key][0] in the hope it would return "value1" but instead it return ...
Basic Python dictionary question
I have a dictionary with one key and two values and I want to set each value to a separate variable. d= {'key' : ('value1, value2'), 'key2' : ('value3, value4'), 'key3' : ('value5, value6')} I tried d[key][0] in the hope it would return "value1" but instead it return "v" Any suggestions?
[ "A better solution is to store your value as a two-tuple:\nd = {'key' : ('value1', 'value2')}\n\nThat way you don't have to split every time you want to access the values.\n", "Try something like this:\nd = {'key' : 'value1, value2'}\n\nlist = d['key'].split(', ')\n\nlist[0] will be \"value1\" and list[1] will be...
[ 17, 4, 2, 2, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0001214422_dictionary_python.txt
Q: Allowing the " - " character in usernames in the Django Admin interface In our webapp we needed to allow dashes "-" in our usernames. I've enabled that for the consumer signup process just fine with this regex r'^[\w-]+$' How can I tell the admin app so that I can edit usernames in auth > users to allows the "-...
Allowing the " - " character in usernames in the Django Admin interface
In our webapp we needed to allow dashes "-" in our usernames. I've enabled that for the consumer signup process just fine with this regex r'^[\w-]+$' How can I tell the admin app so that I can edit usernames in auth > users to allows the "-" character in usernames? Currently I am unable to edit any usernames with da...
[ "This should be as simple as overriding the behavior of the User ModelAdmin class. In one of your apps, in admin.py include the following code.\nfrom django.contrib import admin\nfrom django import forms\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.admin import UserAdmin\nfrom django.contr...
[ 19 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0001214453_django_django_admin_python.txt
Q: Changing palette's of 8-bit .png images using python PIL I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so) What I have tried (edited): import Image, ImagePalette output = StringIO.StringIO() ...
Changing palette's of 8-bit .png images using python PIL
I'm looking for a fast way to apply a new palette to an existing 8-bit .png image. How can I do that? Is the .png re-encoded when I save the image? (Own answer: it seems so) What I have tried (edited): import Image, ImagePalette output = StringIO.StringIO() palette = (.....) #long palette of 768 items im = Image.open('...
[ "If you want to change just the palette, then PIL will just get in your way. Luckily, the PNG file format was designed to be easy to deal with when you only are interested in some of the data chunks. The format of the PLTE chunk is just an array of RGB triples, with a CRC at the end. To change the palette on a file...
[ 8, 1, 0 ]
[]
[]
[ "image_processing", "python", "python_imaging_library" ]
stackoverflow_0001158736_image_processing_python_python_imaging_library.txt
Q: Counting and filtering objects in a database with Django I'm struggling a little to work out how to follow the relation and count fields of objects. In my Django site, I have a profile model: user = models.ForeignKey(User, unique=True) name = models.CharField(_('name'), null=True, blank=True) about = models.TextFi...
Counting and filtering objects in a database with Django
I'm struggling a little to work out how to follow the relation and count fields of objects. In my Django site, I have a profile model: user = models.ForeignKey(User, unique=True) name = models.CharField(_('name'), null=True, blank=True) about = models.TextField(_('about'), null=True, blank=True) location = models.CharF...
[ "You should be able to get them using:\nProfile.objects.filter(name__isnull=False)\n\n" ]
[ 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001214740_django_django_models_python.txt
Q: Text formatting in different versions of Python I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another. In python < 2.6, it's done like this: n = 3 print "%s * %s = %s" % (n, n, n*n...
Text formatting in different versions of Python
I've got a problem with executing a python script in different environments with different versions of the interpreter, because the way text is formatted differ from one version to another. In python < 2.6, it's done like this: n = 3 print "%s * %s = %s" % (n, n, n*n) whereas in python >= 2.6 the best way to do it is:...
[ "str.format() was introduced in Python 2.6, but its only become the preferred method of string formatting in Python 3.0.\nIn Python 2.6 both methods will still work, of course. \nIt all depends on who the consumers of your code will be. If you expect the majority of your users will not be using Python 3.0, then sti...
[ 3, 1, 0 ]
[]
[]
[ "formatting", "python" ]
stackoverflow_0001212108_formatting_python.txt
Q: Does clause preventing exposure of PyQt in an application's script API close loophole in license? I am currently evaluating using PyQt in a commercial application, and I was surprised to learn that the PyQt Commercial License does not permit you to expose any of the PyQt library in the application's script API. Fr...
Does clause preventing exposure of PyQt in an application's script API close loophole in license?
I am currently evaluating using PyQt in a commercial application, and I was surprised to learn that the PyQt Commercial License does not permit you to expose any of the PyQt library in the application's script API. From the PyQt site: The right to distribute the required PyQt modules and QScintilla library with your a...
[ "\"commercial software\" means a software you can sell, including a free GPL'd software. The way the pyqt guys use \"commercial\" is misleading.\nYou can use the library under the GPL and charge for it, as long as you provide the code of the program under a GPL compatible license. I don't know what they have that c...
[ 0, 0 ]
[ "First of all: Lawyers rule the world and never you forget it.\nSecondly, IANAL.\nGPL does just the same thing: If you write some code and publish it under the GPL, all derived work must be GPL, too. This is known as the \"viral nature\" of the GPL. R. Stallman specifically added this to protect the work of the GPL...
[ -1 ]
[ "gpl", "licensing", "open_source", "pyqt", "python" ]
stackoverflow_0001152777_gpl_licensing_open_source_pyqt_python.txt
Q: Looking for a pure Python library for the SyncML protocol I'm looking for an open source, pure Python library that supports the SyncML protocol, at least enough to implement a SyncML client. A: There's https://sourceforge.net/projects/pysyncml/: "The pysyncml library is a pure-python implementation of the SyncML...
Looking for a pure Python library for the SyncML protocol
I'm looking for an open source, pure Python library that supports the SyncML protocol, at least enough to implement a SyncML client.
[ "There's https://sourceforge.net/projects/pysyncml/: \"The pysyncml library is a pure-python implementation of the SyncML adapter framework and protocol.\" Haven't tried it yet.\n", "I don't know of any pure Python implementations, but there are python bindings for C libraries:\n\npysyncml (google for it, can onl...
[ 1, 0, 0 ]
[]
[]
[ "python", "syncml" ]
stackoverflow_0000831162_python_syncml.txt
Q: XSLT Transform of Unicode source In my application I am using the 4Suite.org XSLT library to perform transformations of source XML. The syntax is like this: from Ft.Xml.Xslt import Transform transformed_xml = Transform(raw_xml, stylesheet) where raw_xml and stylesheet have been defined elsewhere in my applicatio...
XSLT Transform of Unicode source
In my application I am using the 4Suite.org XSLT library to perform transformations of source XML. The syntax is like this: from Ft.Xml.Xslt import Transform transformed_xml = Transform(raw_xml, stylesheet) where raw_xml and stylesheet have been defined elsewhere in my application. raw_xml will be the xml resulting ...
[ "You are likely better off using the more modern and actively maintained lxml.\n", "I'm not sure Transform actually needs ascii -- looks to me like it should support any encoded Python str. What happens if you call Transform(raw_xml.encode('utf8'), stylesheet) (and then decode the resulting utf8-encoded string ba...
[ 2, 2 ]
[]
[]
[ "python", "unicode", "xslt" ]
stackoverflow_0001214733_python_unicode_xslt.txt
Q: How to get lxml working under IronPython? I need to port some code that relies heavily on lxml from a CPython application to IronPython. lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions. Does anyone know of a workaround to allow...
How to get lxml working under IronPython?
I need to port some code that relies heavily on lxml from a CPython application to IronPython. lxml is very Pythonic and I would like to keep using it under IronPython, but it depends on libxslt and libxml2, which are C extensions. Does anyone know of a workaround to allow lxml under IronPython or a version of lxml tha...
[ "You might check out IronClad, which is an open source project intended to make C Extensions for Python available in IronPython.\n", "Something which you might have already considered: \nAn alternative is to first port the lxml library to IPy and then your code (depending on the code size). You might have to writ...
[ 2, 1 ]
[]
[]
[ ".net", "ironpython", "lxml", "python", "xml" ]
stackoverflow_0001200726_.net_ironpython_lxml_python_xml.txt
Q: Can a Python function take a generator and return generators to subsets of its generated output? Let's say I have a generator function like this: import random def big_gen(): i = 0 group = 'a' while group != 'd': i += 1 yield (group, i) if random.random() < 0.20: group = chr(ord(group) + 1)...
Can a Python function take a generator and return generators to subsets of its generated output?
Let's say I have a generator function like this: import random def big_gen(): i = 0 group = 'a' while group != 'd': i += 1 yield (group, i) if random.random() < 0.20: group = chr(ord(group) + 1) Example output might be: ('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('a', 6), ('a', 7), ('a',...
[ "Sure, this does what you want:\nimport itertools\nimport operator\n\ndef main():\n for let, gen in itertools.groupby(big_gen(), key=operator.itemgetter(0)):\n secgen = itertools.imap(operator.itemgetter(1), gen)\n printer(let, secgen)\n\ngroupby does the bulk of the work here -- the key= just tells it what ...
[ 8, 0 ]
[]
[]
[ "generator", "python" ]
stackoverflow_0001215464_generator_python.txt
Q: How to list all class properties I have class SomeClass with properties. For example id and name: class SomeClass(object): def __init__(self): self.__id = None self.__name = None def get_id(self): return self.__id def set_id(self, value): self.__id = value def get...
How to list all class properties
I have class SomeClass with properties. For example id and name: class SomeClass(object): def __init__(self): self.__id = None self.__name = None def get_id(self): return self.__id def set_id(self, value): self.__id = value def get_name(self): return self.__nam...
[ "property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)]\n\n", "import inspect\n\ndef isprop(v):\n return isinstance(v, property)\n\npropnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)]\n\ninspect.getmembers gets inherited members as well (and selects memb...
[ 55, 36 ]
[]
[]
[ "properties", "python", "serialization" ]
stackoverflow_0001215408_properties_python_serialization.txt
Q: Multiple periodic timers Is there any standard python module for creating multiple periodic timers. I want to design a system which supports creating multiple periodic timers of different periodicity running in just one thread. The system should be able to cancel a specific timer at any point of time. Thanks in ad...
Multiple periodic timers
Is there any standard python module for creating multiple periodic timers. I want to design a system which supports creating multiple periodic timers of different periodicity running in just one thread. The system should be able to cancel a specific timer at any point of time. Thanks in advance for any input!
[ "Check out the sched module in Python's standard library -- per se, it doesn't directly support periodic timers, only one-off \"events\", but the standard trick to turn a one-off event into a periodic timer applies (the callable handling the one-off event just reschedules itself for the next repetition, before movi...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001214164_python.txt
Q: Search engine woes I have been trying to make this search engine for a MySQL database. Taking in user input is no problem, database querying is also fine. One thing I need to figure out is this: I am a string in the database How do I match the input "AM", but keep the same case? There are PHP functions like str_...
Search engine woes
I have been trying to make this search engine for a MySQL database. Taking in user input is no problem, database querying is also fine. One thing I need to figure out is this: I am a string in the database How do I match the input "AM", but keep the same case? There are PHP functions like str_ireplace or preg_replace...
[ "I suggest you read this\nhttp://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html\nIt may help you build a better search engine and probably answer some part of your question\nHere is a good example of what you could do :\nmysql> SELECT id, body, MATCH (title,body) AGAINST\n -> ('Security implications of ru...
[ 4 ]
[]
[]
[ "javascript", "mysql", "php", "python", "search" ]
stackoverflow_0001215661_javascript_mysql_php_python_search.txt
Q: lxml retrieving odd items with cssselector In my test document I have a few classes labeled "item", currently I'm using the following to parse everything in the html file with this class with Selection = html.cssselect(".item") I'd like it to select all the odd items, like this in javascript using JQuery Selectio...
lxml retrieving odd items with cssselector
In my test document I have a few classes labeled "item", currently I'm using the following to parse everything in the html file with this class with Selection = html.cssselect(".item") I'd like it to select all the odd items, like this in javascript using JQuery Selection = $(".item:odd"); Trying that verbatim I get ...
[ "The \"odd\" and \"even\" features are part of a selector named \"nth-child()\"; take a look at the CSS selector specification for more details:\nhttp://www.w3.org/TR/2001/CR-css3-selectors-20011113/#nth-child-pseudo\n\nTherefore, you should be able to get exactly the behavior you want (and it works for me with CSS...
[ 1 ]
[]
[]
[ "css", "html_parsing", "lxml", "python" ]
stackoverflow_0001162580_css_html_parsing_lxml_python.txt
Q: import serial error occured in Python I wrote import serial There message are occured. Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.4/site-packages/serial/__init__.py", line 20, in ? from serialposix import * File "/usr/lib/python2.4/site-packages/serial/serialp...
import serial error occured in Python
I wrote import serial There message are occured. Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.4/site-packages/serial/__init__.py", line 20, in ? from serialposix import * File "/usr/lib/python2.4/site-packages/serial/serialposix.py", line 13, in ? import sys, os,...
[ "termios has been in the Python standard library since 2.0 at least (I'm not very familiar with older Python versions), but it's always been a Unix-only module. Your 2.4 should be fine, IF you're running under any Unix flavor -- i.e., anything but Windows, more or less. The problem you're seeing suggests either a ...
[ 3 ]
[]
[]
[ "debian", "python", "serial_port" ]
stackoverflow_0001215889_debian_python_serial_port.txt
Q: comparing two strings with 'is' -- not performing as expected I'm attempting to compare two strings with is. One string is returned by a function, and the other is just declared in the comparison. is tests for object identity, but according to this page, it also works with two identical strings because of Python's...
comparing two strings with 'is' -- not performing as expected
I'm attempting to compare two strings with is. One string is returned by a function, and the other is just declared in the comparison. is tests for object identity, but according to this page, it also works with two identical strings because of Python's memory optimization. But, the following doesn't work: def uSplit(u...
[ "That page you quoted says \"If two string literals are equal, they have been put to same memory location\" (emphasis mine). Python interns literal strings, but strings that are returned from some arbitrary function are separate objects. The is operator can be thought of as a pointer comparison, so two different ob...
[ 4, 3, 0 ]
[]
[]
[ "python", "string_comparison", "string_literals" ]
stackoverflow_0001216259_python_string_comparison_string_literals.txt
Q: Remap keyboard navigation with Jython / Swing I'm trying to remap several navigation keys: ENTER: to work like standard TAB behavior (focus to next control) SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control) UP / DOWN arrows: previous /next control etc I tried with a couple of options but w...
Remap keyboard navigation with Jython / Swing
I'm trying to remap several navigation keys: ENTER: to work like standard TAB behavior (focus to next control) SHIFT+ENTER: to work like SHIFT+TAB behavior (focus to previous control) UP / DOWN arrows: previous /next control etc I tried with a couple of options but without luck: from javax.swing import * from java.aw...
[ "I made a new post for readability.\nself.textfield1 = JTextField('Type something here',15,focusGained=self.myOnFocus,keyPressed=self.myOnKey)\n\n#create textfield2...must be created before can be referenced below.\n\nself.textfield1.setNextFocusableComponent(self.textfield2)\n\nthen in your event handler:\ndef myO...
[ 1, 1, 0 ]
[]
[]
[ "jython", "python", "swing" ]
stackoverflow_0001213730_jython_python_swing.txt
Q: google appengine/python: Can I depend on Task queue retry on failure to keep insertions to a minimum? Say my app has a page on which people can add comments. Say after each comment is added a taskqueue worker is added. So if a 100 comments are added a 100 taskqueue insertions are made. (note: the above is a hyp...
google appengine/python: Can I depend on Task queue retry on failure to keep insertions to a minimum?
Say my app has a page on which people can add comments. Say after each comment is added a taskqueue worker is added. So if a 100 comments are added a 100 taskqueue insertions are made. (note: the above is a hypothetical example to illustrate my question) Say I wanted to ensure that the number of insertions are kept ...
[ "There's no reason to fake a failure (and incur backoff &c) -- that's a hacky and fragile arrangement. If you fear that simply scheduling a task per new comment might exceed the task queues' currently strict limits, then \"batch up\" as-yet-unprocessed comments in the store (and possibly also in memcache, I guess, ...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001216947_google_app_engine_python.txt
Q: Newbie to python conventions, is my code on the right track? I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little...
Newbie to python conventions, is my code on the right track?
I've been reading about python for a week now and just thought I'd try my hand at it by creating a tax bracket calculator. I'm not finished but I wanted to know if I'm on the right track or not as far as python programming goes. I've only done a little C++ programming before, and it feels like it shows (good/bad?) #T...
[ "There's probably a more efficient way to do this using lists and pairs instead of separate variables for each bracket's limit and rate. For instance, consider the following:\n# List of (upper-limit, rate) pairs for brackets.\nbrackets = [ (8350, .10), (33950, .15), (82250, .25), (171550, .28), (372950, .33) ]\n\ni...
[ 13, 5, 2, 2, 1, 1, 0 ]
[]
[]
[ "conventions", "python" ]
stackoverflow_0001216395_conventions_python.txt
Q: is it possible to add an element to a list and preserve the order I would like to add an element to a list that preserve the order of the list. Let's assume the list of object is [a, b, c, d] I have a function cmp that compares two elements of the list. if I add f object which is the bigger I would like it to be ...
is it possible to add an element to a list and preserve the order
I would like to add an element to a list that preserve the order of the list. Let's assume the list of object is [a, b, c, d] I have a function cmp that compares two elements of the list. if I add f object which is the bigger I would like it to be at the last position. maybe it's better to sort the complete list...
[ "Yes, this is what bisect.insort is for, however it doesn't take a comparison function. If the objects are custom objects, you can override one or more of the rich comparison methods to establish your desired sort order. Or you could store a 2-tuple with the sort key as the first item, and sort that instead.\n", ...
[ 5, 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001217780_python.txt
Q: Reverting a Python/Cocoa project to use the default OSX 10.5 Python (2.5) I have installed the latest MacPython (2.6.2) on my Leopard OS X and started an XCode PyObjC project. When I finalized the app, I built the release version and sent it to a friend of mine to try if it runs with out of the box. It did not, b...
Reverting a Python/Cocoa project to use the default OSX 10.5 Python (2.5)
I have installed the latest MacPython (2.6.2) on my Leopard OS X and started an XCode PyObjC project. When I finalized the app, I built the release version and sent it to a friend of mine to try if it runs with out of the box. It did not, because it expects the latest Python, as on my computer. No matter what I tried,...
[ "Uninstalling what you now have in /Library/Frameworks (so XCode falls back to the Python in /System/Library/Frameworks) would work but may be considered a bit drastic. This post and its followups have other potentially useful recommendations, the best one being in the followup at the very end -- you can edit the c...
[ 1 ]
[]
[]
[ "cocoa", "pyobjc", "python", "xcode", "xcodebuild" ]
stackoverflow_0001217781_cocoa_pyobjc_python_xcode_xcodebuild.txt
Q: SQLAlchemy: Scan huge tables using ORM? I am currently playing around with SQLAlchemy a bit, which is really quite neat. For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast... For fun I did the equivalent of a select * ov...
SQLAlchemy: Scan huge tables using ORM?
I am currently playing around with SQLAlchemy a bit, which is really quite neat. For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast... For fun I did the equivalent of a select * over the resulting SQLite database: session = S...
[ "Okay, I just found a way to do this myself. Changing the code to\nsession = Session()\nfor p in session.query(Picture).yield_per(5):\n print(p)\n\nloads only 5 pictures at a time. It seems like the query will load all rows at a time by default. However, I don't yet understand the disclaimer on that method. Quot...
[ 61, 37, 9 ]
[]
[]
[ "orm", "performance", "python", "sqlalchemy" ]
stackoverflow_0001145905_orm_performance_python_sqlalchemy.txt
Q: Is LINQ (or linq) a niche tool, or is it on the path to becoming foundational? After reading "What is the Java equivalent of LINQ?", I'd like to know, is (lowercase) language-integrated query - in other words the ability to use a concise syntax for performing queries over object collections or external stores - go...
Is LINQ (or linq) a niche tool, or is it on the path to becoming foundational?
After reading "What is the Java equivalent of LINQ?", I'd like to know, is (lowercase) language-integrated query - in other words the ability to use a concise syntax for performing queries over object collections or external stores - going to be the path of the future for most general purpose languages? Or is LINQ an ...
[ "Before LinQ, Python had Generator Expressions which are specific syntax for performing queries over collections. Python's syntax is more reduced than Linq's, but let you basically perform the same queries as easy as in linq. Months ago, I wrote a blog post comparing queries in C# and Python, here is a small examp...
[ 9, 4, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ ".net", "java", "linq", "python" ]
stackoverflow_0001217274_.net_java_linq_python.txt
Q: PyOpenGL + Pygame capped to 60 FPS in Fullscreen I'm currently working on a game engine written in pygame and I wanted to add OpenGL support. I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I ...
PyOpenGL + Pygame capped to 60 FPS in Fullscreen
I'm currently working on a game engine written in pygame and I wanted to add OpenGL support. I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the wind...
[ "As frou pointed out, this would be due to Pygame waiting for the vertical retrace when you update the screen by calling display.flip(). As the Pygame display documentation notes, if you set the display mode using the HWSURFACE or the DOUBLEBUF flags, display.flip() will wait for the vertical retrace before swappin...
[ 8, 1, 0 ]
[]
[]
[ "fullscreen", "pygame", "pyopengl", "python" ]
stackoverflow_0001217939_fullscreen_pygame_pyopengl_python.txt
Q: The wrong python interpreter is called I updated my python interpreter, but I think the old one is still called. When I check for the version I get: $ python -V Python 3.0.1 But I believe the old interpreter is still being called. When I run the command: python myProg.py The script runs properly. But when I invo...
The wrong python interpreter is called
I updated my python interpreter, but I think the old one is still called. When I check for the version I get: $ python -V Python 3.0.1 But I believe the old interpreter is still being called. When I run the command: python myProg.py The script runs properly. But when I invoke it with the command ./myProg.py I get th...
[ "According to the first line of the script, #!/usr/bin/python, you are calling the Python interpreter at /usr/bin/python (which is most likely the one that ships with Mac OS X). You have to change that path to the path where you installed your Python 3 interpreter (likely /usr/local/bin/python or /opt/local/bin/pyt...
[ 16, 6, 3, 3, 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0000904170_python_python_3.x.txt
Q: In erlang: How do I expand wxNotebook in a panel? (I have tagged this question as Python as well since I understand Python code so examples in Python are also welcome!). I want to create a simple window in wxWidgets: I create a main panel which I add to a form I associate a boxsizer to the main panel (splitting it...
In erlang: How do I expand wxNotebook in a panel?
(I have tagged this question as Python as well since I understand Python code so examples in Python are also welcome!). I want to create a simple window in wxWidgets: I create a main panel which I add to a form I associate a boxsizer to the main panel (splitting it in two, horizontally). I add LeftPanel to the boxsizer...
[ "I'm closing this question (as soon as I can) after I figured out what I needed to do.\nBasically I changed the proportion to 1 of the add command to the main panel (this will expand the whole thing)\nNew code:\n %% Main Sizer\n wxSizer:add(MainSizer, LeftPanel, [{proportion,0},{border, 2}, {flag,?wxEXPAND bor ?w...
[ 4 ]
[]
[]
[ "erlang", "layout", "python", "wxwidgets" ]
stackoverflow_0001218433_erlang_layout_python_wxwidgets.txt
Q: Segment a list in Python I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have: >>> def split_list(list, seg_length): ... inlist = list[:] ... outlist = [] ... ... while inlist: ...
Segment a list in Python
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have: >>> def split_list(list, seg_length): ... inlist = list[:] ... outlist = [] ... ... while inlist: ... outlist.append(inl...
[ "You can use list comprehension:\n>>> seg_length = 3\n>>> a = range(10)\n>>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)]\n[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n", "How do you need to use the output? If you only need to iterate over it, you are better off creating an iterable, one that yields your ...
[ 23, 5, 2 ]
[]
[]
[ "list", "python", "segments" ]
stackoverflow_0001218793_list_python_segments.txt
Q: How to get the biggest numbers out from huge amount of numbers? I'd like to get the largest 100 elements out from a list of at least 100000000 numbers. I could sort the entire list and just take the last 100 elements from the sorted list, but that would be very expensive in terms of both memory and time. Is there ...
How to get the biggest numbers out from huge amount of numbers?
I'd like to get the largest 100 elements out from a list of at least 100000000 numbers. I could sort the entire list and just take the last 100 elements from the sorted list, but that would be very expensive in terms of both memory and time. Is there any existing easy, pythonic way of doing this? What I want is followi...
[ "The heapq module in the standard library offers the nlargest() function to do this:\ntop100 = heapq.nlargest(100, iterable [,key])\n\nIt won't sort the entire list, so you won't waste time on the elements you don't need.\n", "Selection algorithms should help here. \nA very easy solution is to find the 100th bigg...
[ 27, 6, 5, 3, 2, 1 ]
[]
[]
[ "max", "minimum", "python", "sorting" ]
stackoverflow_0001218922_max_minimum_python_sorting.txt
Q: Trappings MySQL Warnings on Calls Wrapped in Classes -- Python I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes. I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries thr...
Trappings MySQL Warnings on Calls Wrapped in Classes -- Python
I can't get Python's try/else blocks to catch MySQL warnings when the execution statements are wrapped in classes. I have a class that has as a MySQL connection object as an attribute, a MySQL cursor object as another, and a method that run queries through that cursor object. The cursor is itself wrapped in a class. ...
[ "On first glance at least one problem:\n if dict_flag:\n dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)\n\nshouldn't that be\n if dict_flag:\n self.dbMySQL_Cursor = conn.cursor(MySQLdb.cursors.DictCursor)\n\nYou're mixing your self/not self. Also I would wrap the \nself.conn ...
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0000651358_mysql_python.txt
Q: Multiprocessing Debugging error Hey everyone, I am having a little trouble debugging my code. Please look below: import globalFunc from globalFunc import systemPrint from globalFunc import out from globalFunc import debug import math import time import multiprocessing """ Somehow this is not working well """ cl...
Multiprocessing Debugging error
Hey everyone, I am having a little trouble debugging my code. Please look below: import globalFunc from globalFunc import systemPrint from globalFunc import out from globalFunc import debug import math import time import multiprocessing """ Somehow this is not working well """ class urlServerM( multiprocessing.Proce...
[ "You're using multiprocessing, so the memory is not shared between main execution and your urlserver.\nI.e. I think this is effectively a Noop: {us.store('http://www.google.com')} because when it's executed in the main thread, it modifies only the main threads representation of {us}. You can confirm that the url is...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0001218757_python.txt
Q: Workarounds when a string is too long for a .join. OverflowError occurs I'm working through some python problems on pythonchallenge.com to teach myself python and I've hit a roadblock, since the string I am to be using is too large for python to handle. I receive this error: my-macbook:python owner1$ python singl...
Workarounds when a string is too long for a .join. OverflowError occurs
I'm working through some python problems on pythonchallenge.com to teach myself python and I've hit a roadblock, since the string I am to be using is too large for python to handle. I receive this error: my-macbook:python owner1$ python singleoccurrence.py Traceback (most recent call last): File "singleoccurrence.py...
[ "string.join doesn't do what you think. join is used to combine a list of words into a single string with the given seperator. Ie:\n>>> \",\".join(('foo', 'bar', 'baz'))\n'foo,bar,baz'\n\nThe code snippet you posted will attempt to insert myString between every character in the variable line. You can see how that w...
[ 10 ]
[]
[]
[ "overflow", "python" ]
stackoverflow_0001219733_overflow_python.txt
Q: Python: prefer several small modules or one larger module? I'm working on a Python web application in which I have some small modules that serve very specific functions: session.py, logger.py, database.py, etc. And by "small" I really do mean small; each of these files currently includes around 3-5 lines of code, ...
Python: prefer several small modules or one larger module?
I'm working on a Python web application in which I have some small modules that serve very specific functions: session.py, logger.py, database.py, etc. And by "small" I really do mean small; each of these files currently includes around 3-5 lines of code, or maybe up to 10 at most. I might have a few imports and a clas...
[ "\nMy thoughts are that having separate\n modules helps with code clarity, and\n later on, if by some chance these\n modules grow to more than 10 lines, I\n won't feel so bad about having them\n separated.\n\nThis. Keep it the way you have it. \n", "As a user of modules, I greatly prefer when I can include t...
[ 9, 7, 3, 3, 2 ]
[ "Small. \n" ]
[ -2 ]
[ "module", "python", "refactoring" ]
stackoverflow_0001219815_module_python_refactoring.txt
Q: Filter and sort music info on Google App Engine I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another. Let's assume the...
Filter and sort music info on Google App Engine
I've enjoyed building out a couple simple applications on the GAE, but now I'm stumped about how to architect a music collection organizer on the app engine. In brief, I can't figure out how to filter on multiple properties while sorting on another. Let's assume the core model is an Album that contains several propert...
[ "There's a couple of options here: You can filter as best as possible, then sort the results in memory, as Alex suggests, or you can rework your data structures for equality filters instead of inequality filters.\nFor example, assuming you only want to filter by decade, you can add a field encoding the decade in wh...
[ 1, 1, 0 ]
[]
[]
[ "django_models", "google_app_engine", "model", "python" ]
stackoverflow_0001213959_django_models_google_app_engine_model_python.txt
Q: Storing data and searching by metadata? Let's say I have a set of data where each row is a pair of coordinates: (X, Y). Associated with each point I have arbitrary metadata, such as {color: yellow} or {age: 2 years}. I'd like to be able to store the data and metadata in such a way that I can query the metadata (eg...
Storing data and searching by metadata?
Let's say I have a set of data where each row is a pair of coordinates: (X, Y). Associated with each point I have arbitrary metadata, such as {color: yellow} or {age: 2 years}. I'd like to be able to store the data and metadata in such a way that I can query the metadata (eg: [rows where {age: 2 years, color: yellow}])...
[ "Any relational database should be able to handle something like that (you'd basically just being doing a join between a couple of tables, one for the data and one for the metadata). SQLite should work fine.\nYour first table would have the data itself with a unique IDs for each entry. Then your second table would ...
[ 2, 1, 0 ]
[]
[]
[ "metadata", "python" ]
stackoverflow_0001220440_metadata_python.txt
Q: How to make authkit session cookie HttpOnly in pylons? I use authkit module with Pylons and I see that session cookie it sets (aptly named authkit) is not set to be HttpOnly. Is there a simple way to make it HttpOnly? (By "simple" I mean the one that does not involve hacking authkit's code.) A: This is not docum...
How to make authkit session cookie HttpOnly in pylons?
I use authkit module with Pylons and I see that session cookie it sets (aptly named authkit) is not set to be HttpOnly. Is there a simple way to make it HttpOnly? (By "simple" I mean the one that does not involve hacking authkit's code.)
[ "This is not documented in authkit, because it only started working in Python 2.6 (see here), but if you do have Python 2.6 then \nauthkit.cookie.params.httponly = true\n\nin the config should work and do what you desire.\nauthkit internally uses a Cookie.SimpleCookie, and that's what limits the keys you can have f...
[ 2 ]
[]
[]
[ "authkit", "cookies", "pylons", "python" ]
stackoverflow_0001220555_authkit_cookies_pylons_python.txt
Q: Creating Date Intervals in Python I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output. So, how can I change this: sum = 0 for i in range(1,11): print sum sum += i To this? InputD...
Creating Date Intervals in Python
I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output. So, how can I change this: sum = 0 for i in range(1,11): print sum sum += i To this? InputDate = '2009-01-01' for i in range('2009...
[ "This will work:\nimport datetime\n\na = datetime.date(2009, 1, 1)\nb = datetime.date(2009, 7, 1)\none_day = datetime.timedelta(1)\n\nday = a\n\nwhile day <= b:\n # do important stuff\n day += one_day\n\n", "Try this:\nimport datetime\ndt1 = datetime.date(2009, 1, 1)\ndt2 = datetime.date(2009, 7, 1)\ndt = d...
[ 7, 2, 2 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0001220872_mysql_python.txt
Q: returning a value to a c# program through python script I have a C# program which executes a python scrip How can I retrieve the python returning value in my C# program ? thanks! A: As far as I know, you should use ScriptScope object which you create from the ScriptEngine object using CreateScope method ScriptEn...
returning a value to a c# program through python script
I have a C# program which executes a python scrip How can I retrieve the python returning value in my C# program ? thanks!
[ "As far as I know, you should use ScriptScope object which you create from the ScriptEngine object using CreateScope method\nScriptEngine engine = ScriptRuntime.Create().GetEngine(\"py\");\nScriptScope scope = engine.CreateScope();\n\nThen you can share variables between the C# program and the python script by doin...
[ 2, 1 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0001221135_c#_python.txt
Q: java and python equivalent of php's foreach($array as $key => $value) In php, one can handle a list of state names and their abbreviations with an associative array like this: <?php $stateArray = array( "ALABAMA"=>"AL", "ALASKA"=>"AK", // etc... "WYOMING"=>"WY" ); forea...
java and python equivalent of php's foreach($array as $key => $value)
In php, one can handle a list of state names and their abbreviations with an associative array like this: <?php $stateArray = array( "ALABAMA"=>"AL", "ALASKA"=>"AK", // etc... "WYOMING"=>"WY" ); foreach ($stateArray as $stateName => $stateAbbreviation){ print "The ab...
[ "in Python:\nfor key, value in stateDict.items(): # .iteritems() in Python 2.x\n print \"The abbreviation for %s is %s.\" % (key, value)\n\nin Java:\nMap<String,String> stateDict;\n\nfor (Map.Entry<String,String> e : stateDict.entrySet())\n System.out.println(\"The abbreviation for \" + e.getKey() + \" is \" ...
[ 34, 6, 2, 2, 2, 1, 1, 0 ]
[]
[]
[ "associative_array", "java", "php", "python" ]
stackoverflow_0001219548_associative_array_java_php_python.txt
Q: Need to get the rest of an iterator in python Say I have an iterator. After iterating over a few items of the iterator, I will have to get rid of these first few items and return an iterator(preferably the same) with the rest of the items. How do I go about? Also, Do iterators support remove or pop operations (lik...
Need to get the rest of an iterator in python
Say I have an iterator. After iterating over a few items of the iterator, I will have to get rid of these first few items and return an iterator(preferably the same) with the rest of the items. How do I go about? Also, Do iterators support remove or pop operations (like lists)?
[ "Yes, just use iter.next()\nExample\niter = xrange(3).__iter__()\n\niter.next() # this pops 0\n\nfor i in iter:\n print i\n\n1\n2\n\nYou can pop off the front of an iterator with .next(). You cannot do any other fancy operations.\n", "The itertools.dropwhile() function might be helpful, too:\ndropwhile(lambda x:...
[ 7, 7 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0001220640_iterator_python.txt
Q: need to put a nested Dict into a text file I have a nested dict like this d={ time1 : column1 : {data1,data2,data3} column2 : {data1,data2,data3} column3 : {data1,data2,data3} #So on. time2 : {column1: } #Same as Above } data1,data2,data3 represent the type of data ...
need to put a nested Dict into a text file
I have a nested dict like this d={ time1 : column1 : {data1,data2,data3} column2 : {data1,data2,data3} column3 : {data1,data2,data3} #So on. time2 : {column1: } #Same as Above } data1,data2,data3 represent the type of data and not the data itself I need to put this dict ...
[ "I would use JSON.\nIn Python 2.6 it's directly available, in earlier Python's you have to download and install it.\ntry:\n import json\nexception ImportError:\n import simplejson as json\n\nout= open( \"myFile.json\", \"w\" )\njson.dump( { 'timestamp': time.time(), 'data': d }, indent=2 )\nout.close()\n\nWor...
[ 3, 1 ]
[]
[]
[ "dictionary", "file", "python" ]
stackoverflow_0001221202_dictionary_file_python.txt
Q: Find unique elements in tuples in a python list Is there a better way to do this in python, or rather: Is this a good way to do it? x = ('a', 'b', 'c') y = ('d', 'e', 'f') z = ('g', 'e', 'i') l = [x, y, z] s = set([e for (_, e, _) in l]) I looks somewhat ugly but does what i need without writing a complex "get_...
Find unique elements in tuples in a python list
Is there a better way to do this in python, or rather: Is this a good way to do it? x = ('a', 'b', 'c') y = ('d', 'e', 'f') z = ('g', 'e', 'i') l = [x, y, z] s = set([e for (_, e, _) in l]) I looks somewhat ugly but does what i need without writing a complex "get_unique_elements_from_tuple_list" function... ;) edit:...
[ "That's fine, that's what sets are for. One thing I would change is this:\ns = set(e[1] for e in l)\n\nas it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.\n" ]
[ 24 ]
[]
[]
[ "list", "python", "set", "tuples" ]
stackoverflow_0001221775_list_python_set_tuples.txt
Q: Screen Scrape Form Results I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could ge...
Screen Scrape Form Results
I was recently requested by a client to build a website for their insurance business. As part of this, they want to do some screen scraping of the quote site for one of their providers. They asked if their was an API to do this, and were told there wasn't one, but that if they could get the data from their engine the...
[ "A really nice library for screen-scraping is mechanize, which I believe is a clone of an original library written in Perl. Anyway, that in combination with the ClientForm module, and some additional help from either BeautifulSoup and you should be away.\nI've written loads of screen-scraping code in Python and th...
[ 5, 2, 0, 0 ]
[]
[]
[ "forms", "python", "screen_scraping" ]
stackoverflow_0001222373_forms_python_screen_scraping.txt
Q: Is there a good html parser like HtmlAgilityPack (.NET) for Python? I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: http://www.codeplex.com/htmlagilitypack), but for using with Python. Anyone knows? A: Use Beautiful Soup like everyone does. A: Others have recommended Beautifu...
Is there a good html parser like HtmlAgilityPack (.NET) for Python?
I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: http://www.codeplex.com/htmlagilitypack), but for using with Python. Anyone knows?
[ "Use Beautiful Soup like everyone does.\n", "Others have recommended BeautifulSoup, but it's much better to use lxml. Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles \"broken\" HTML better than BeautifulSoup (their claim to fame). It has a...
[ 8, 8, 0 ]
[]
[]
[ "html", "parsing", "python" ]
stackoverflow_0001222222_html_parsing_python.txt
Q: URL tree walker in Python? For URLs that show file trees, such as Pypi packages, is there a small solid module to walk the URL tree and list it like ls -lR? I gather (correct me) that there's no standard encoding of file attributes, link types, size, date ... in html <A attributes so building a solid URLtree modul...
URL tree walker in Python?
For URLs that show file trees, such as Pypi packages, is there a small solid module to walk the URL tree and list it like ls -lR? I gather (correct me) that there's no standard encoding of file attributes, link types, size, date ... in html <A attributes so building a solid URLtree module on shifting sands is tough. Bu...
[ "Apache servers are very common, and they have a relatively standard way of listing file directories.\nHere's a simple enough script that does what you want, you should be able to make it do what you want.\nUsage: python list_apache_dir.py \nimport sys\nimport urllib\nimport re\n\nparse_re = re.compile('href=\"([^\...
[ 3, 1, 0 ]
[]
[]
[ "beautifulsoup", "directory_walk", "python", "tree" ]
stackoverflow_0000686147_beautifulsoup_directory_walk_python_tree.txt
Q: Is there a way to modify a class in a class method in Python? I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get: NameError: global name 'ClassName' is not defined Is there a way for a class method to modify the class? Something like this but...
Is there a way to modify a class in a class method in Python?
I wanted to do something like setattr to a class in class method in Python, but the class doesn't exist so I basically get: NameError: global name 'ClassName' is not defined Is there a way for a class method to modify the class? Something like this but that actually works: class ClassName(object): def HocusPocus(n...
[ "Class methods get the class passed as the first argument:\nclass Bla(object):\n @classmethod\n def cm(cls,value):\n cls.storedValue = value\n\nBla.cm(\"Hello\")\n\nprint Bla.storedValue # prints \"Hello\"\n\n\nEdit: I think I understand your problem now. If I get it correctly, all you want to do is th...
[ 5, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001222311_python.txt
Q: BeautifulSoup 3.1 parser breaks far too easily I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously. Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borkin...
BeautifulSoup 3.1 parser breaks far too easily
I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously. Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby websi...
[ "Having problems with Beautiful Soup 3.1.0? recommends to use html5lib's parser as one of workarounds.\n#!/usr/bin/env python\nfrom html5lib import HTMLParser, treebuilders\n\nparser = HTMLParser(tree=treebuilders.getTreeBuilder(\"beautifulsoup\"))\n\nc = \"\"\"<HTML>\n <HEAD>\n <TITLE>Title</TITLE>\n ...
[ 6, 3, 2 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0000459552_beautifulsoup_html_parsing_python.txt
Q: Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string? I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring...
Are there any cleverly efficient algorithms to perform a calculation over the space of partitionings of a string?
I'm working on a statistical project that involves iterating over every possible way to partition a collection of strings and running a simple calculation on each. Specifically, each possible substring has a probability associated with it, and I'm trying to get the sum across all partitions of the product of the substr...
[ "A Dynamic Programming solution (if I understood the question right):\ndef dynProgSolution(text, probs):\n probUpTo = [1]\n for i in range(1, len(text)+1):\n cur = sum(v*probs[text[k:i]] for k, v in enumerate(probUpTo))\n probUpTo.append(cur)\n return probUpTo[-1]\n\nprint dynProgSolution(\n 'abc',\n {'a...
[ 5, 3, 1, 1, 0 ]
[]
[]
[ "partitioning", "python", "string" ]
stackoverflow_0001223007_partitioning_python_string.txt
Q: How to write native newline character to a file descriptor in Python? The os.write function can be used to writes bytes into a file descriptor (not file object). If I execute os.write(fd, '\n'), only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows a...
How to write native newline character to a file descriptor in Python?
The os.write function can be used to writes bytes into a file descriptor (not file object). If I execute os.write(fd, '\n'), only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux. What is the best way to achieve this? I'm using Python...
[ "Use this\nimport os\nos.write(fd, os.linesep)\n\n", "How about os.write(<file descriptor>, os.linesep)? (import os is unnecessary because you seem to have already imported it, otherwise you'd be getting errors using os.write to begin with.)\n" ]
[ 85, 8 ]
[]
[]
[ "python" ]
stackoverflow_0001223289_python.txt
Q: How to agnostically link any object/Model from another Django Model? I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work ...
How to agnostically link any object/Model from another Django Model?
I'm writing a simple CMS based on Django. Most content management systems rely on having a fixed page, on a fixed URL, using a template that has one or many editable regions. To have an editable region, you require a Page. For the system to work out which page, you require the URL. The problem comes when you're no long...
[ "django-tagging uses Django's contenttypes framework. The docs do a much better job of explaining it than I can, but the simplest description of it would be \"generic foreign key that can point to any other model.\"\nThis may be what you are looking for, but from your description it also sounds like you want to do...
[ 6, 2, 2 ]
[]
[]
[ "content_management_system", "django", "django_models", "python" ]
stackoverflow_0000969211_content_management_system_django_django_models_python.txt
Q: Python string templater I'm using this REST web service, which returns various templated strings as urls, for example: "http://api.app.com/{foo}" In Ruby, I can then use url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar') to get "http://api.app.com/bar" Is there any way to do thi...
Python string templater
I'm using this REST web service, which returns various templated strings as urls, for example: "http://api.app.com/{foo}" In Ruby, I can then use url = Addressable::Template.new("http://api.app.com/{foo}").expand('foo' => 'bar') to get "http://api.app.com/bar" Is there any way to do this in Python? I know about %()...
[ "In python 2.6 you can do this if you need exactly that syntax\nfrom string import Formatter\nf = Formatter()\nf.format(\"http://api.app.com/{foo}\", foo=\"bar\")\n\nIf you need to use an earlier python version then you can either copy the 2.6 formatter class or hand roll a parser/regex to do it.\n", "Don't use a...
[ 4, 2, 0 ]
[]
[]
[ "python", "ruby", "string", "templates" ]
stackoverflow_0001218457_python_ruby_string_templates.txt
Q: Python TypeError unsupported operand type(s) for %: 'file' and 'unicode' I'm working on a django field validation and I can't figure out why I'm getting a type error for this section: def clean_tid(self): data = self.cleaned_data['tid'] stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /v...
Python TypeError unsupported operand type(s) for %: 'file' and 'unicode'
I'm working on a django field validation and I can't figure out why I'm getting a type error for this section: def clean_tid(self): data = self.cleaned_data['tid'] stdout_handel = os.popen("/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN") % data result = stdout_handel.r...
[ "Check your parenthesis.\nWrong\nstdout_handel = os.popen(\"/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN\") % data\n\nMight be right.\nstdout_handel = os.popen(\"/var/www/nsmweb/jre1.6.0_14/bin/java -jar /var/www/nsmweb/sla.jar -t %s grep -v DAN\" % data )\n\n", "Just a sm...
[ 1, 1 ]
[]
[]
[ "django", "python", "typeerror", "unicode" ]
stackoverflow_0001223563_django_python_typeerror_unicode.txt
Q: "Watching" program being processed line-by-line? I'm looking for a debugging tool that will run my Python app, but display which line is currently being processed -- like an automatically stepping debugger. Basically I want to see what is going on, but be able to jump in if a traceback occurs. A: Winpdb is a go...
"Watching" program being processed line-by-line?
I'm looking for a debugging tool that will run my Python app, but display which line is currently being processed -- like an automatically stepping debugger. Basically I want to see what is going on, but be able to jump in if a traceback occurs.
[ "Winpdb is a good python debugger. It is written in Python under the GPL, so adding the automatic stepping functionality you want should not be too complicated. \n", "I think you're looking for the pdb module.\n", "\"Basically I want to see what is going on, but be able to jump in if a traceback occurs.\"\nHere...
[ 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0001220465_debugging_python.txt
Q: Lightweight markup language for Python Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to ente...
Lightweight markup language for Python
Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text: my_text = cgidata.getvalu...
[ "Use the python markdown implementation\nimport markdown\nmode = \"remove\" # or \"replace\" or \"escape\"\nmd = markdown.Markdown(safe_mode=mode)\nhtml = md.convert(text)\n\nIt is very flexible, you can use various extensions, create your own etc.\n", "You could use restructured text . I'm not sure if it has a ...
[ 8, 2, 1 ]
[]
[]
[ "html", "markup", "python" ]
stackoverflow_0001223741_html_markup_python.txt
Q: How can I display updating output of a slow script using Pylons? I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once. I foun...
How can I display updating output of a slow script using Pylons?
I am writing an application in Pylons that relies on the output of some system commands such as traceroute. I would like to display the output of the command as it is generated rather than wait for it to complete and then display all at once. I found how to access the output of the command in Python with the answer to...
[ "pexpect will let you get the output as it comes, with no buffering.\nTo update info promptly on the user's browser, you need javascript on that browser sending appropriate AJAX requests to your server (dojo or jquery will make that easier, though they're not strictly required) and updating the page as new response...
[ 1, 1, 0 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0001175748_pylons_python.txt
Q: Sending an email from Pylons I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email? A: What you want is turbomail. In documentation you have an entry where is explains how to integrate it with Pylons...
Sending an email from Pylons
I am using Pylons to develop an application and I want my controller actions to send emails to certain addresses. Is there a built in Pylons feature for sending email?
[ "What you want is turbomail. In documentation you have an entry where is explains how to integrate it with Pylons.\n", "Can't you just use standard Python library modules, email to prepare the mail and smtp to send it? What extra value beyond that are you looking for from the \"built-in feature\"?\n", "Try this...
[ 5, 2, 2 ]
[]
[]
[ "pylons", "python" ]
stackoverflow_0001089576_pylons_python.txt
Q: Trying to import module with the same name as a built-in module causes an import error I have a module that conflicts with a built-in module. For example, a myapp.email module defined in myapp/email.py. I can reference myapp.email anywhere in my code without issue. However, I need to reference the built-in email...
Trying to import module with the same name as a built-in module causes an import error
I have a module that conflicts with a built-in module. For example, a myapp.email module defined in myapp/email.py. I can reference myapp.email anywhere in my code without issue. However, I need to reference the built-in email module from my email module. # myapp/email.py from email import message_from_string It onl...
[ "You will want to read about Absolute and Relative Imports which addresses this very problem. Use:\nfrom __future__ import absolute_import\n\nUsing that, any unadorned package name will always refer to the top level package. You will then need to use relative imports (from .email import ...) to access your own pack...
[ 101 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0001224741_python_python_import.txt
Q: How do I associate input to a Form with a Model in Django? In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table? For example: class PhoneNumber(models.Model): Fi...
How do I associate input to a Form with a Model in Django?
In Django, how do I associate a Form with a Model so that data entered into the form are inserted into the database table associated with the Model? How do I save that user input to that database table? For example: class PhoneNumber(models.Model): FirstName = models.CharField(max_length=30) LastName = models....
[ "Back when I first used Forms and Models (without using ModelForm), what I remember doing was checking if the form was valid, which would set your cleaned data, manually moving the data from the form to the model (or whatever other processing you want to do), and then saving the model. As you can tell, this was ex...
[ 3, 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001223763_django_python.txt
Q: Check for a module in Python without using exceptions I can check for a module in Python doing something like: try: import some_module except ImportError: print "No some_module!" But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.) Note: The reason for no us...
Check for a module in Python without using exceptions
I can check for a module in Python doing something like: try: import some_module except ImportError: print "No some_module!" But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.) Note: The reason for no using try/except is arbitrary, it is just because I want to k...
[ "It takes trickery to perform the request (and one raise statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say \"I don't deal with this path item\"!), but the following would avoid any try/except:\nimport sys\n\nsentinel = object()\n\nclass FakeLoader(o...
[ 7, 1, 0 ]
[ "sys.modules dictionary seems to contain the info you need.\n" ]
[ -1 ]
[ "module", "python", "python_module" ]
stackoverflow_0001224585_module_python_python_module.txt
Q: limit downloaded page size Is there a way to limit amount of data downloaded by python's urllib2 module ? Sometimes I encounter with broken sites with sort of /dev/random as a page and it turns out that they use up all memory on a server. A: urllib2.urlopen returns a file-like object, and you can (at least in th...
limit downloaded page size
Is there a way to limit amount of data downloaded by python's urllib2 module ? Sometimes I encounter with broken sites with sort of /dev/random as a page and it turns out that they use up all memory on a server.
[ "urllib2.urlopen returns a file-like object, and you can (at least in theory) .read(N) from such an object to limit the amount of data returned to N bytes at most.\nThis approach is not entirely fool-proof, because an actively-hostile site may go to quite some lengths to fool a reasonably trusty received, like urll...
[ 3 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0001224910_python_urllib2.txt
Q: Query strange behaviour. Google App Engine datastore I have a model like this: class Group(db.Model): name = db.StringProperty() description = db.TextProperty() Sometimes when executing queries like: groups = Group.all().order("name").fetch(20) or groups = Group.all() I'm getting error massages like this: T...
Query strange behaviour. Google App Engine datastore
I have a model like this: class Group(db.Model): name = db.StringProperty() description = db.TextProperty() Sometimes when executing queries like: groups = Group.all().order("name").fetch(20) or groups = Group.all() I'm getting error massages like this: Traceback (most recent call last): File "/opt/google_appeng...
[ "all is indeed an attribute (specifically an executable one, a method) but as Group inherits from Model it should have that attribute; clearly something strange is going on, for example the name Group at the point does not refer to the object you think it does. I suggest putting a try / except AttributeError, e: ar...
[ 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001224939_google_app_engine_google_cloud_datastore_python.txt
Q: What's the state-of-the-art in Python programming in Windows? I'm looking to set up my development environment at home for writing Windows applications in Python. For my first piece, I'm writing a simple, forms-based application that stores data input as XML (and can read that information back.) I do want to set u...
What's the state-of-the-art in Python programming in Windows?
I'm looking to set up my development environment at home for writing Windows applications in Python. For my first piece, I'm writing a simple, forms-based application that stores data input as XML (and can read that information back.) I do want to set up the tools I'd use professionally, though, having already done a r...
[ "I like Eclipse + PyDev (with extensions).\nIt is available on Windows, and it works very well well. However, there are many other IDEs, with strengths and weakness.\nAs for the interpreter (Python is interpreted, not compiled!), you have three main choices: CPython, IronPython and Jython.\nWhen people say \"Python...
[ 7, 2, 2, 1, 1, 1, 1 ]
[]
[]
[ "ide", "python", "windows", "wxpython", "xml" ]
stackoverflow_0001224567_ide_python_windows_wxpython_xml.txt
Q: How to stop WSGI from hanging apache I have django running through WSGI like this : <VirtualHost *:80> WSGIScriptAlias / /home/ptarjan/django/django.wsgi WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup ptarjan Alias /media /home/ptarjan/django/mysite/media/ <...
How to stop WSGI from hanging apache
I have django running through WSGI like this : <VirtualHost *:80> WSGIScriptAlias / /home/ptarjan/django/django.wsgi WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup ptarjan Alias /media /home/ptarjan/django/mysite/media/ </VirtualHost> But if in python I do : def...
[ "It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case.\nAs far as trying to use mod_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive.\nEven then, this is not a complete solution. This is beca...
[ 13, 3 ]
[]
[]
[ "apache", "django", "mod_wsgi", "python" ]
stackoverflow_0001223927_apache_django_mod_wsgi_python.txt
Q: wxPython menu doesn't display image I am creating a menu and assigning images to menu items, sometime first item in menu doesn't display any image, I am not able to find the reason. I have tried to make a simple stand alone example and below is the code which does demonstrates the problem on my machine. I am using...
wxPython menu doesn't display image
I am creating a menu and assigning images to menu items, sometime first item in menu doesn't display any image, I am not able to find the reason. I have tried to make a simple stand alone example and below is the code which does demonstrates the problem on my machine. I am using windows XP, wx 2.8.7.1 (msw-unicode)' im...
[ "This hack does not appear to be necessary if you create each menu item with wx.MenuItem(), set its bitmap, and only then append it to the menu. This causes the bitmaps to show up correctly. I'm testing with wxPython 2.8.10.1 on Windows.\n", "This is a confirmed bug which appearently has been open for quite a whi...
[ 4, 2 ]
[]
[]
[ "menu", "python", "wxpython" ]
stackoverflow_0001078661_menu_python_wxpython.txt
Q: How can I merge fields in a CSV string using Python? I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example: ,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo, Is there ...
How can I merge fields in a CSV string using Python?
I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example: ,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo, Is there a simple algorithm that could merge fields 7-9 for each li...
[ "Something like this?\nimport csv\nsource= csv.reader( open(\"some file\",\"rb\") )\ndest= csv.writer( open(\"another file\",\"wb\") )\nfor row in source:\n result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:]\n dest.writerow( result )\n\n\nExample\n>>> data=''',,Joe,Smith,New Haven,CT,\"Moved from Portland, ...
[ 10, 3, 1, 1 ]
[]
[]
[ "csv", "database", "python", "string" ]
stackoverflow_0001223967_csv_database_python_string.txt
Q: Python: How to import part of a namespace I have a structure such this works : import a.b.c a.b.c.foo() and this also works : from a.b import c c.foo() but this doesn't work : from a import b.c b.c.foo() nor does : from a import b b.c.foo() How can I do the import so that b.c.foo() works? A: Just rename it: ...
Python: How to import part of a namespace
I have a structure such this works : import a.b.c a.b.c.foo() and this also works : from a.b import c c.foo() but this doesn't work : from a import b.c b.c.foo() nor does : from a import b b.c.foo() How can I do the import so that b.c.foo() works?
[ "Just rename it:\n\nfrom a.b import c as BAR\n\nBAR.foo()\n\n", "In your 'b' package, you need to add 'import c' so that it is always accessible as part of b.\n", "from a import b\nfrom a.b import c\nb.c = c\n\n", "import a.b.c\nfrom a import b\nb.c.foo()\n\nThe order of the import statements doesn't matter.\...
[ 9, 2, 2, 0 ]
[]
[]
[ "import", "namespaces", "python" ]
stackoverflow_0001225481_import_namespaces_python.txt
Q: Error starting Django with Pinax Upon trying to start a Pinax app, I receive the following error: Error: No module named notification Below are the steps I took svn co http://svn.pinaxproject.com/pinax/trunk/ pinax cd pinax/pinax/projects/basic_project ./manage.py syncdb Any suggestions? UPDATE: Turns out the...
Error starting Django with Pinax
Upon trying to start a Pinax app, I receive the following error: Error: No module named notification Below are the steps I took svn co http://svn.pinaxproject.com/pinax/trunk/ pinax cd pinax/pinax/projects/basic_project ./manage.py syncdb Any suggestions? UPDATE: Turns out there are some bugs in the SVN version. D...
[ "I'd avoid the svn version all together. It's unmaintained and out of date. Instead, use the git version at http://github.com/pinax/pinax or (even better) the recently release 0.7b3 downloadable from http://pinaxproject.com\n", "Two thoughts:\n1. Check all of your imports to make sure that notification is getting...
[ 5, 0, 0 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0001223513_django_pinax_python.txt
Q: Problem running functions from a DLL file using ctypes in Object-oriented Python I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program. However I've encoutered some pro...
Problem running functions from a DLL file using ctypes in Object-oriented Python
I sure hope this won't be an already answered question or a stupid one. Recently I've been programming with several instruments. Trying to communicate between them in order to create a testing program. However I've encoutered some problems with one specific instrument when I'm trying to call functions that I've "masked...
[ "I'm not sure about your exact problem, but here's a couple general tips:\nFor those functions that you are calling outside of the constructor, I would strongly recommend setting their argtypes in the constructor as well. Once you've declared the argtypes, you shouldn't need to cast all the arguments as c_short, c...
[ 1, 0, 0 ]
[]
[]
[ "automation", "ctypes", "dll", "oop", "python" ]
stackoverflow_0001170372_automation_ctypes_dll_oop_python.txt
Q: Reading files in python Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly: import os.path filename = "A 180 mb large file.data" size = os.path.getsize(filename) f = open(filename, "r") contents = f.read() f.close() print "The real filesi...
Reading files in python
Trying to understand how you're supposed to read files in python. This is what I've done and it isn't working quite properly: import os.path filename = "A 180 mb large file.data" size = os.path.getsize(filename) f = open(filename, "r") contents = f.read() f.close() print "The real filesize is", size print "The read ...
[ "If your file confuses the C libraries, then your results are expected.\nThe OS thinks it's 180Mb.\nHowever, there are null bytes scattered around, which can confuse the C stdio libraries.\nTry opening the file with \"rb\" and see if you get different results.\n", "The first is the filesize in bytes, the other ti...
[ 5, 3, 0 ]
[]
[]
[ "file", "python" ]
stackoverflow_0001224391_file_python.txt
Q: Convolution of two functions in Python I will have to implement a convolution of two functions in Python, but SciPy/Numpy appear to have functions only for the convolution of two arrays. Before I try to implement this by using the the regular integration expression of convolution, I would like to ask if someone kn...
Convolution of two functions in Python
I will have to implement a convolution of two functions in Python, but SciPy/Numpy appear to have functions only for the convolution of two arrays. Before I try to implement this by using the the regular integration expression of convolution, I would like to ask if someone knows of an already available module that perf...
[ "You could try to implement the Discrete Convolution if you need it point by point.\n", "Yes, SciPy/Numpy is mostly concerned about arrays.\nIf you can tolerate an approximate solution, and your functions only operate over a range of value (not infinite) you can fill an array with the values and convolve the arra...
[ 2, 1 ]
[]
[]
[ "convolution", "python" ]
stackoverflow_0001222147_convolution_python.txt
Q: List Comprehensions in Python : efficient selection in a list Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element). I want to have as a result a list of tuple, with the distance and the element. So, I wrot...
List Comprehensions in Python : efficient selection in a list
Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a distance to an other element). I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code result = [ ( myFunction(C), C) for C in origin...
[ "Sure, the difference between the following two:\n[f(x) for x in list]\n\nand this:\n(f(x) for x in list)\n\nis that the first will generate the list in memory, whereas the second is a new generator, with lazy evaluation.\nSo, simply write the \"unfiltered\" list as a generator instead. Here's your code, with the g...
[ 9, 3, 3, 1, 1, 0, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0001222677_list_comprehension_python.txt
Q: How to setup mod_python configuration variables? I'm running a Python server with mod_python, and I've run into some issues with configuration variables. This is actually two questions rolled into one, because I think they are highly related: I need a way to configure variables that will be available in Python w...
How to setup mod_python configuration variables?
I'm running a Python server with mod_python, and I've run into some issues with configuration variables. This is actually two questions rolled into one, because I think they are highly related: I need a way to configure variables that will be available in Python while running. I currently just have a module that set...
[ "\nUsing PythonOption lets you configure stuff that may need to change from server to server. I wouldn't use it too much, though, because messing with the Apache configuration directives is kind of a pain (plus it requires reloading the server). You might consider something like using PythonOption to specify the n...
[ 1, 0 ]
[]
[]
[ "configuration", "mod_python", "python" ]
stackoverflow_0001224978_configuration_mod_python_python.txt
Q: Convincing others of Ruby over Python and PHP G'day folks. I'm trying to introduce Ruby at work, and a few people are interested. However, I've been asked to present the benefits of Ruby over Python and PHP. I've broken this down into 2 parts: 1) show Python and Ruby's advantages over PHP; 2) show Ruby's advantage...
Convincing others of Ruby over Python and PHP
G'day folks. I'm trying to introduce Ruby at work, and a few people are interested. However, I've been asked to present the benefits of Ruby over Python and PHP. I've broken this down into 2 parts: 1) show Python and Ruby's advantages over PHP; 2) show Ruby's advantages over Python. The first is easy. I'll explain thin...
[ "If your goal is to show why language X is better than language Y, you're stuck in subjective-land where there are no right answers.\nNo, Ruby is not better than PHP or Python. It might be more suited for a given purpose, and for that you can give specific examples. PHP is a poor choice for writing an SMTP server; ...
[ 29, 16, 12, 5, 5, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0000784584_python_ruby.txt
Q: can someone help me understand this short .py I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/. Basically what I d...
can someone help me understand this short .py
I'm trying to understand basic threading in python, I'm having trouble understanding how pooling works with the queue module. Heres the example server used in the howto I'm reading from: http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/2/. Basically what I don't understand is how the variable pickledList end...
[ "The pickledList variable is available as a global variable in the ClientThread class. See Short Description of Python Scoping Rules.\n" ]
[ 4 ]
[ "Threads don't have their own namespace. pickledList is defined as a global, so it is accessible to the object. Technically it should have had a global pickledList at the top of the function to make that clear, but it's not always needed.\nEDIT\nBy make it clear, I mean \"make it clear to a human.\" \n" ]
[ -2 ]
[ "multithreading", "python" ]
stackoverflow_0001227448_multithreading_python.txt
Q: What is a good configuration file library for c thats not xml (preferably has python bindings)? I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What...
What is a good configuration file library for c thats not xml (preferably has python bindings)?
I am looking for a good config file library for c that is not xml. Optimally I would really like one that also has python bindings. The best option I have come up with is to use a JSON library in both c and python. What would you recommend, or what method of reading/writing configuration settings do you prefer?
[ "YaML :)\n", "If you're not married to Python, try Lua. It was originally designed for configuration.\n", "You could use a pure python solution like ConfigObj and then simply use the CPython API to query for settings. This assumes that your application embeds Python. If it doesn't, and if you are shipping Pyt...
[ 5, 1, 0, 0 ]
[]
[]
[ "c", "configuration_management", "python" ]
stackoverflow_0001227031_c_configuration_management_python.txt
Q: How can I order objects according to some attribute of the child in sqlalchemy? Here is the situation: I have a parent model say BlogPost. It has many Comments. What I want is the list of BlogPosts ordered by the creation date of its' Comments. I.e. the blog post which has the most newest comment should be on top ...
How can I order objects according to some attribute of the child in sqlalchemy?
Here is the situation: I have a parent model say BlogPost. It has many Comments. What I want is the list of BlogPosts ordered by the creation date of its' Comments. I.e. the blog post which has the most newest comment should be on top of the list. Is this possible with SQLAlchemy?
[ "http://www.sqlalchemy.org/docs/05/mappers.html#controlling-ordering\n\nAs of version 0.5, the ORM does not\n generate ordering for any query unless\n explicitly configured.\nThe “default” ordering for a\n collection, which applies to\n list-based collections, can be\n configured using the order_by keyword\n ...
[ 4, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000492223_python_sqlalchemy.txt
Q: Retrieving the return value of a Python script I have an external C# program which executes a Python script using the Process class. My script returns a numerical code and I want to retrieve it from my C# program. Is this possible? The problem is, I'm getting the return code of python.exe instead of the code retur...
Retrieving the return value of a Python script
I have an external C# program which executes a Python script using the Process class. My script returns a numerical code and I want to retrieve it from my C# program. Is this possible? The problem is, I'm getting the return code of python.exe instead of the code returned from my script. (For example, 3.)
[ "The interpreter does not return the value at the top of Python's stack, unless you do this:\nif __name__ == \"__main__\":\n sys.exit(main())\n\nor if you make a call to sys.exit elsewhere.\nHere's a lot more documentation on this issue.\n" ]
[ 8 ]
[]
[]
[ "c#", "python" ]
stackoverflow_0001228550_c#_python.txt
Q: Cython and numpy speed I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop c...
Cython and numpy speed
I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at tha...
[ "Edit:\nThere's now scipy.signal.fftconvolve which would be the preferred approach to doing the FFT based convolution approach that I describe below. I'll leave the original answer to explain the speed issue, but in practice use scipy.signal.fftconvolve.\nOriginal answer:\nUsing FFTs and the convolution theorem wi...
[ 37, 2, 2 ]
[]
[]
[ "cython", "numpy", "python" ]
stackoverflow_0001199972_cython_numpy_python.txt
Q: Problem with Twisted python - sending binary data What I'm trying to do is fairly simple: send a file from client to server. First, the client sends information about the file - the size of it that is. Then it sends the actual file. This is what I've done so far: Server.py from twisted.internet import reactor, pro...
Problem with Twisted python - sending binary data
What I'm trying to do is fairly simple: send a file from client to server. First, the client sends information about the file - the size of it that is. Then it sends the actual file. This is what I've done so far: Server.py from twisted.internet import reactor, protocol from twisted.protocols.basic import LineReceiver ...
[ "You've set your server to raw mode with setRawMode(), so the callback rawDataReceived is being called with the incoming data (not lineReceived). If you print the data you receive in rawDataReceived, you see everything including the file content, but as you call pickle to deserialize the data, it's being ignored.\...
[ 9 ]
[]
[]
[ "file", "python", "send", "twisted" ]
stackoverflow_0001228722_file_python_send_twisted.txt
Q: Problem with hash function: hash(1) == hash(1.0) I have an instance of dict with ints, floats, strings as keys, but the problem is when there are a as int and b as float, and float(a) == b, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in o...
Problem with hash function: hash(1) == hash(1.0)
I have an instance of dict with ints, floats, strings as keys, but the problem is when there are a as int and b as float, and float(a) == b, then their hash values are the same, and thats what I do NOT want to get because I need unique hash vales for this cases in order to get corresponding values. Example: d = {1:'1',...
[ "Since 1 == 1.0, it would horribly break the semantics of hashing (and therefore dicts and sets) if it were the case that hash(1) != hash(1.0). More generally, it must ALWAYS be the case that x == y implies hash(x) == hash(y), for ALL x and y (there is of course no condition requiring the reverse implication to hol...
[ 7, 6, 2, 1 ]
[]
[]
[ "dictionary", "hash", "python" ]
stackoverflow_0001228475_dictionary_hash_python.txt
Q: Globally-scoped variable: can its value change before it is picked up by the thread? In the following code, you see that pickledList is being used by the thread and is set in the global scope. If the variable that the thread was using was set dynamically somewhere down below in that final while loop, is it possib...
Globally-scoped variable: can its value change before it is picked up by the thread?
In the following code, you see that pickledList is being used by the thread and is set in the global scope. If the variable that the thread was using was set dynamically somewhere down below in that final while loop, is it possible that its value could change before the thread got to use it? How can I set a value dyna...
[ "Option 1: you can pass arguments into each Thread when it is instantiated:\nClientThread(arg1, arg2, kwarg1=\"three times!\").start()\n\nin which case your run method will be called:\nrun(arg1, arg2, kwarg1=\"three times!\")\n\nby the Thread instance when you call start(). If you need to pass mutable objects (dict...
[ 3 ]
[]
[]
[ "multithreading", "python", "scope" ]
stackoverflow_0001228655_multithreading_python_scope.txt
Q: Convert list of floats into buffer in Python? I am playing around with PortAudio and Python. data = getData() stream.write( data ) I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function: def getData(): data = [] for i in range( 0, 1024 ): ...
Convert list of floats into buffer in Python?
I am playing around with PortAudio and Python. data = getData() stream.write( data ) I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function: def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ...
[ "import struct\n\ndef getData():\n data = []\n for i in range( 0, 1024 ):\n data.append( 0.25 * math.sin( math.radians( i ) ) )\n return struct.pack('f'*len(data), *data)\n\n", "Actually, the easiest way is to use the struct module. It is designed to convert from python objects to C-like \"native...
[ 9, 2, 0 ]
[]
[]
[ "buffer", "floating_point", "list", "python" ]
stackoverflow_0001229202_buffer_floating_point_list_python.txt
Q: Opening a wx.Frame in Python via a new thread I have a frame that exists as a start up screen for the user to make a selection before the main program starts. After the user makes a selection I need the screen to stay up as a sort of splash screen until the main program finishes loading in back. I've done this by...
Opening a wx.Frame in Python via a new thread
I have a frame that exists as a start up screen for the user to make a selection before the main program starts. After the user makes a selection I need the screen to stay up as a sort of splash screen until the main program finishes loading in back. I've done this by creating an application and starting a thread: cla...
[ "You don't need threads for this. The drawback is that the splash window will block while loading but that is an issue only if you want to update it's contents (animate it) or if you want to be able to drag it. An issue that can be solved by periodically calling wx.SafeYield for example.\nimport time\nimport wx\n\n...
[ 0 ]
[]
[]
[ "multithreading", "python", "wxpython" ]
stackoverflow_0001229525_multithreading_python_wxpython.txt
Q: How to read/copy ctype pointers into python class? This is a kind of follow-up from my last question if this can help you. I'm defining a few ctype structures class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("pack...
How to read/copy ctype pointers into python class?
This is a kind of follow-up from my last question if this can help you. I'm defining a few ctype structures class EthercatDatagram(Structure): _fields_ = [("header", EthercatDatagramHeader), ("packet_data_length", c_int), ("packet_data", POINTER(c_ubyte)), ("work_coun...
[ "The square-bracket notation is indeed correct. For reference, here's a snippet from some ctypes code I recently made:\nclass Message(Structure):\n _fields_ = [ (\"id\", BYTE), (\"data\", POINTER(BYTE)), (\"data_length\", DWORD) ]\n def __repr__(self):\n d = ' '.join([\"0x%02X\" % self.data[i] for i i...
[ 1, 0 ]
[]
[]
[ "ctypes", "pointers", "python", "variables" ]
stackoverflow_0001229318_ctypes_pointers_python_variables.txt