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: A class subclass of itself. Why mutual subclassing is forbidden? Complex question I assume, but studying OWL opened a new perspective to live, the universe and everything. I'm going philosophical here. I am trying to achieve a class C which is subclass of B which in turn is subclass of C. Just for fun, you know......
A class subclass of itself. Why mutual subclassing is forbidden?
Complex question I assume, but studying OWL opened a new perspective to live, the universe and everything. I'm going philosophical here. I am trying to achieve a class C which is subclass of B which in turn is subclass of C. Just for fun, you know... So here it is >>> class A(object): pass ... >>> class B(A): pass ......
[ "Python doesn't allow it because there is no sensible way to do it. You could invent arbitrary rules about how to handle such a case (and perhaps some languages do), but since there is no actual gain in doing so, Python refuses to guess. Classes are required to have a stable, predictable method resolution order for...
[ 10, 2, 2, 1, 1, 0 ]
[]
[]
[ "class", "owl", "python" ]
stackoverflow_0002223300_class_owl_python.txt
Q: How do I use gstreamer to make an audio clip from a segment of a longer source? I would like to use gstreamer to save an arbitrary clip from one audio file to a new file. For example, a segment from 1 minute to 2 minutes in the original. How do I do it? A: You need gnonlin. See http://www.jonobacon.org/2006/12/2...
How do I use gstreamer to make an audio clip from a segment of a longer source?
I would like to use gstreamer to save an arbitrary clip from one audio file to a new file. For example, a segment from 1 minute to 2 minutes in the original. How do I do it?
[ "You need gnonlin. See http://www.jonobacon.org/2006/12/27/using-gnonlin-with-gstreamer-and-python/\nYou won't need a gnlcomposition because you only want one segment. Use a gnlfilesource with its start and duration set to 0, 1 minute, and media-start and media-duration set to 1 minute, 1 minute. All times and dura...
[ 6 ]
[]
[]
[ "audio", "audio_streaming", "gstreamer", "python", "segment" ]
stackoverflow_0002215683_audio_audio_streaming_gstreamer_python_segment.txt
Q: Convert dict to array in NumPy I'd like to take a dictionary of a dictionary containing floats, indexed by ints and convert it into a numpy.array for use with the numpy library. Currently I'm manually converting the values into two arrays, one for the original indexes and the other for the values. While I've loo...
Convert dict to array in NumPy
I'd like to take a dictionary of a dictionary containing floats, indexed by ints and convert it into a numpy.array for use with the numpy library. Currently I'm manually converting the values into two arrays, one for the original indexes and the other for the values. While I've looked at numpy.asarray my conclusion h...
[ "You can calculate N and M like this\nN=max(foo)+1\nM=max(max(x) for x in foo.values())+1\nfooarray = numpy.zeros((N, M))\nfor key1, row in foo.iteritems():\n for key2, value in row.iteritems():\n fooarray[key1, key2] = value \n\nThere are various options for sparse arrays. Eg,\nimport scipy.sparse\nfoospar...
[ 4, 1 ]
[]
[]
[ "arrays", "dictionary", "numpy", "python" ]
stackoverflow_0002224620_arrays_dictionary_numpy_python.txt
Q: python equivalent of GNU 'cat' that shows unique lines Has anyone written the GNU cat command in python and would be willing to share? GNU cat actually does quite a bit & I don't really feel like re-inventing the wheel today. Yes, I did do a google search & and after reading too many sad stories of kittens vs sn...
python equivalent of GNU 'cat' that shows unique lines
Has anyone written the GNU cat command in python and would be willing to share? GNU cat actually does quite a bit & I don't really feel like re-inventing the wheel today. Yes, I did do a google search & and after reading too many sad stories of kittens vs snakes I decided to try SO. Edit: I'd like to modify it so tha...
[ "Latest:\nThank's Ned for the fileinput tip! Here's the latest:\n#!/usr/bin/python\n\n\"\"\"cat the file, but only the unique lines\n\"\"\"\nimport fileinput\n\nif __name__ == \"__main__\":\n lines=set()\n for line in fileinput.input():\n if not line in lines:\n print line,\n lin...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002224554_python.txt
Q: Is_prime function via regex in python (from perl) I've read this article where the /^1?$|^(11+?)\1+$/ Perl regex is used to test if a number is prime or not. Process: s = '1' * your_number If s matchs the regex, then it's not prime. If it doesn't, it's prime. How would you translate that regex to Python's re mod...
Is_prime function via regex in python (from perl)
I've read this article where the /^1?$|^(11+?)\1+$/ Perl regex is used to test if a number is prime or not. Process: s = '1' * your_number If s matchs the regex, then it's not prime. If it doesn't, it's prime. How would you translate that regex to Python's re module?
[ "It works as is (except without the slashes at the edges, which aren't needed in Python):\npattern = r'^1?$|^(11+?)\\1+$'\nre.match(pattern, '1'*10) #matches\nre.match(pattern, '1'*11) #doesn't match\n\nThe only nonstandard regex feature needed here is backreferences (\\1), and these are supported in both Per...
[ 6 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0002225027_perl_python_regex.txt
Q: Design pattern for ongoing survey anayisis I'm doing an ongoing survey, every quarter. We get people to sign up (where they give extensive demographic info). Then we get them to answer six short questions with 5 possible values much worse, worse, same, better, much better. Of course over time we will not get the...
Design pattern for ongoing survey anayisis
I'm doing an ongoing survey, every quarter. We get people to sign up (where they give extensive demographic info). Then we get them to answer six short questions with 5 possible values much worse, worse, same, better, much better. Of course over time we will not get the same participants,, some will drop out and some...
[ "Regarding the survey analysis portion of your question, I would strongly recommend looking at the survey package in R (which includes a number of useful vignettes, including \"A survey analysis example\"). You can read about it in detail on the webpage \"survey analysis in R\". In particular, you may want to hav...
[ 2, 1, 0 ]
[]
[]
[ "design_patterns", "matrix", "python", "statistics", "survey" ]
stackoverflow_0002223576_design_patterns_matrix_python_statistics_survey.txt
Q: Is there a way for me to get detailed formatted information on a Python class? So, I know I can use dir() to get information about class members etc. What I'm looking for is a way to get a nicely formatted report on everything related to a class (the members, docstrings, inheritance hierarchy, etc.). I want to be ...
Is there a way for me to get detailed formatted information on a Python class?
So, I know I can use dir() to get information about class members etc. What I'm looking for is a way to get a nicely formatted report on everything related to a class (the members, docstrings, inheritance hierarchy, etc.). I want to be able to run this on the command-line so I can explore code and debug better.
[ "Try calling help on your class.\n", "Try this from the command line:\npydoc modulename\n\n", "Try the help() facility that is built into the interpreter. E.g.\nclass X(object):\n \"\"\"Docstring for an example class.\"\"\"\n def __init__(self):\n \"\"\"Docstring for X.__init__().\"\"\"\n pa...
[ 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002225456_python.txt
Q: Django Piston: How can I exclude nested fields from handler results? Is it even possible? I am putting the finishing touches on an API I have written for a Django app utilizing django-piston. The API is able to search by request or IP address which are Request or IPAddress instances respectively. Each request can...
Django Piston: How can I exclude nested fields from handler results? Is it even possible?
I am putting the finishing touches on an API I have written for a Django app utilizing django-piston. The API is able to search by request or IP address which are Request or IPAddress instances respectively. Each request can have 1 or more IPAddress associated with it. So, for example I have an API call that will show...
[ "Can you try using include instead of exclude? E.g.\ninclude = (('request', ('inputter', ('username', 'therestofthefields'))))\n\nI don't remember if I wrote exclude to be as versatile as include.\nAlso, the django-piston Google group is where we discuss most things, you may have more success asking this question t...
[ 3, 3 ]
[]
[]
[ "django", "django_models", "django_piston", "python" ]
stackoverflow_0002215352_django_django_models_django_piston_python.txt
Q: Python subprocess get child's output Possible Duplicates: How to get output from subprocess.Popen() Retrieving the output of subprocess.call() Here is my question. I have an executable called device_console. The device_console provides a command line interface to a device. In device_console, four commands can be...
Python subprocess get child's output
Possible Duplicates: How to get output from subprocess.Popen() Retrieving the output of subprocess.call() Here is my question. I have an executable called device_console. The device_console provides a command line interface to a device. In device_console, four commands can be run: status, list, clear and exit. Each ...
[ "it sounds like you want something more like 'Expect'.\ncheck out Pexpect\n\n\"Pexpect is a pure Python module that\n makes Python a better tool for\n controlling and automating other\n programs. Pexpect is similar to the\n Don Libes Expect system, but Pexpect\n as a different interface that is\n easier to un...
[ 2, 2 ]
[]
[]
[ "multithreading", "parent", "python", "subprocess" ]
stackoverflow_0002226162_multithreading_parent_python_subprocess.txt
Q: Python: defining functions on the fly I have the following code: funcs = [] for i in range(10): def func(): print i funcs.append(func) for f in funcs: f() The problem is that func is being overriden. Ie the output of the code is: 9 9 9 ... How would you solve this without defining new function...
Python: defining functions on the fly
I have the following code: funcs = [] for i in range(10): def func(): print i funcs.append(func) for f in funcs: f() The problem is that func is being overriden. Ie the output of the code is: 9 9 9 ... How would you solve this without defining new functions? The optimal solution would be to change ...
[ "The problem is not that func is being overwritten, it's that the value of i is being evaluated when the function is called, not when it is defined. If you want to evaluate i at definition time, put it in the function declaration, as a default argument to func. \nfuncs = []\nfor i in range(10):\n def func(valu...
[ 13, 0, 0 ]
[]
[]
[ "lambda", "python" ]
stackoverflow_0002222466_lambda_python.txt
Q: Python vars() global name error I'm having a bit of trouble understanding what's going wrong with the following function: def ness(): pie='yum' vars()[pie]=4 print vars()[pie] print yum So When I run that I get this result: >>> ness() 4 Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
Python vars() global name error
I'm having a bit of trouble understanding what's going wrong with the following function: def ness(): pie='yum' vars()[pie]=4 print vars()[pie] print yum So When I run that I get this result: >>> ness() 4 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in ness Nam...
[ "vars() within a function gives you the local namespace, just like locals() -- see the docs. Outside of a function (e.g. at the prompt) locals() (and vars() of course) gives you the module's global namespace, just like globals(). As the docs say, trying to assign to a function's local variable through locals() (o...
[ 4, 2, 1, 0, 0 ]
[]
[]
[ "global", "python" ]
stackoverflow_0002226386_global_python.txt
Q: parsing table with BeautifulSoup and write in text file I need data from table in text file (output.txt) in this format: data1;data2;data3;data4;..... Celkova podlahova plocha bytu;33m;Vytah;Ano;Nadzemne podlazie;Prizemne podlazie;.....;Forma vlastnictva;Osobne All in "one line", separator is ";" (later export in ...
parsing table with BeautifulSoup and write in text file
I need data from table in text file (output.txt) in this format: data1;data2;data3;data4;..... Celkova podlahova plocha bytu;33m;Vytah;Ano;Nadzemne podlazie;Prizemne podlazie;.....;Forma vlastnictva;Osobne All in "one line", separator is ";" (later export in csv-file). I´m beginner.. Help, thanks. from BeautifulSoup im...
[ "You are not keeping each record as you read it in. Try this, which stores the records in records:\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2\nimport codecs\n\nresponse = urllib2.urlopen('http://www.reality.sk/zakazka/0747-003578/predaj/1-izb-byt/kosice-mestska-cast-sever-sladkovicova-kosice-sever/art...
[ 15, 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002224602_beautifulsoup_python.txt
Q: PyObjC + Xcode 3.2 + Non-Apple Python I want to get started trying to develop a few simple applications with PyObjC. I installed PyObjC and the Xcode templates. I know that PyObjC itself works, since I've run this script successfully. When I tried to create a project from the Cocoa-Python Application template and ...
PyObjC + Xcode 3.2 + Non-Apple Python
I want to get started trying to develop a few simple applications with PyObjC. I installed PyObjC and the Xcode templates. I know that PyObjC itself works, since I've run this script successfully. When I tried to create a project from the Cocoa-Python Application template and ran it, I got this error: Traceback (most r...
[ "You have a 32-bit vs 64-bit problem. It appears you are using a Python 2.6 installed from MacPorts and apparently it was not a universal (32-bit/64-bit) build. Either your app is running as 64-bit and the Python is only 32-bit or the reverse. You can check by using file:\ncd /opt/local/Library/Frameworks/Python...
[ 3 ]
[]
[]
[ "pyobjc", "python", "python_itertools", "xcode" ]
stackoverflow_0002226902_pyobjc_python_python_itertools_xcode.txt
Q: formatting currencies with Python I would like to format integers as professional looking currency strings. For example: 1200000 -> $1.2 million 456 -> $456.00 Do you know a good library for this, ideally with localization to handle European formats. A: locale.currency() can handle the number bits, but I've not ...
formatting currencies with Python
I would like to format integers as professional looking currency strings. For example: 1200000 -> $1.2 million 456 -> $456.00 Do you know a good library for this, ideally with localization to handle European formats.
[ "locale.currency() can handle the number bits, but I've not seen a module for the word part.\n", "Such formatting seems reasonable in some limited uses. But, should 1200000 be formatted as 1.2 million or 1.20 million? And isn't 456 more friendly as $456 (without the cents)?\nAdding cents to large precise number...
[ 4, 1 ]
[]
[]
[ "currency", "format", "integer", "python", "string" ]
stackoverflow_0002226935_currency_format_integer_python_string.txt
Q: how does create a new app in pinax? thanks only need 'python manage.py startapp xx' ??? A: You don't create a new app in pinax, you create a new app in your project. And yes, that command will do it.
how does create a new app in pinax?
thanks only need 'python manage.py startapp xx' ???
[ "You don't create a new app in pinax, you create a new app in your project. And yes, that command will do it.\n" ]
[ 4 ]
[]
[]
[ "django", "pinax", "python" ]
stackoverflow_0002227246_django_pinax_python.txt
Q: Group and stack tuples I'm just starting with Python, and I can't figure out how to group tuples. For instance, I have tuple1=("A", "B", "C") and tuple2=("1","2","3"). I want to combine these into a list, grouped by the first tuple. I want it to appear stacked, as in A1 A2 A3 on one line, and B1 B2 B3 on the next ...
Group and stack tuples
I'm just starting with Python, and I can't figure out how to group tuples. For instance, I have tuple1=("A", "B", "C") and tuple2=("1","2","3"). I want to combine these into a list, grouped by the first tuple. I want it to appear stacked, as in A1 A2 A3 on one line, and B1 B2 B3 on the next line. I can make them print ...
[ ">>> t1 = (\"A\", \"B\", \"C\")\n>>> t2 = (\"1\", \"2\", \"3\")\n>>> [x + y for x in t1 for y in t2]\n['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']\n>>> [[x + y for y in t2] for x in t1]\n[['A1', 'A2', 'A3'], ['B1', 'B2', 'B3'], ['C1', 'C2', 'C3']]\n>>> x = _ # assign x to the last value\n>>> for row in x...
[ 3, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002227532_list_python.txt
Q: Python question - I have a List of Classes, how do I remove duplicates? Am writing an App Engine application (it's a simple quest system for a game): so I have a list class Quest(db.Model): name = db.StringProperty() # note: I made about 10 different quest entities ( quest1 to quest10) class User(db.Model): c...
Python question - I have a List of Classes, how do I remove duplicates?
Am writing an App Engine application (it's a simple quest system for a game): so I have a list class Quest(db.Model): name = db.StringProperty() # note: I made about 10 different quest entities ( quest1 to quest10) class User(db.Model): completed_quests = db.StringListProperty() # to store keys of completed quest...
[ "You can use difference:\nall = set(quest.key() for quest in all_quests)\ncomplete = set(completed_quests)\nincomplete = all.difference(complete)\n\n", "Try something like this:\nquests = [(x.key(), x) for x in Quest.all.fetch(1000)]\nincomplete_quests = [v for k, v in quests if k not in a_user.completed_quests]\...
[ 3, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002227297_google_app_engine_python.txt
Q: Silverlight databinding with IronPython and Datagrid We've been successfully using clrtype with IronPython 2.6 and Silverlight for databinding, based on the example provided by Lukás(: http://gui-at.blogspot.com/2009/11/inotifypropertychanged-and-databinding.html We create the binding when we create the datagrid ...
Silverlight databinding with IronPython and Datagrid
We've been successfully using clrtype with IronPython 2.6 and Silverlight for databinding, based on the example provided by Lukás(: http://gui-at.blogspot.com/2009/11/inotifypropertychanged-and-databinding.html We create the binding when we create the datagrid columns programatically. Because we are using IronPython s...
[ "I don't know anything about IronPython, but I know that you cannot bind to a Color in Silverlight, regardless of the language used. This has caused me many grievances. In Silverlight 3 you can only bind properties on a FrameworkElement, and since GradientStop is a DependencyObject, it will not work. The good news ...
[ 1 ]
[]
[]
[ "data_binding", "datagrid", "ironpython", "python", "silverlight" ]
stackoverflow_0002224805_data_binding_datagrid_ironpython_python_silverlight.txt
Q: How to retrieve attributes of xml tag in Python? I'm looking for a way to add attributes to xml tags in python. Or to create a new tag with a new attributes for example, I have the following xml file: <types name='character' shortName='chrs'> .... ... </types> and i want to add an attribute to make it look like...
How to retrieve attributes of xml tag in Python?
I'm looking for a way to add attributes to xml tags in python. Or to create a new tag with a new attributes for example, I have the following xml file: <types name='character' shortName='chrs'> .... ... </types> and i want to add an attribute to make it look like this: <types name='character' shortName='chrs' fullNa...
[ "You can use the attributes property of the respective Node object.\nFor example:\nfrom xml.dom.minidom import parseString\ndocumentNode = parseString(\"<types name='character' shortName='chrs'></types>\")\ntypesNode = documentNode.firstChild\n\n# Getting an attribute\nprint typesNode.attributes[\"name\"].value # w...
[ 5, 1, 0 ]
[]
[]
[ "python", "tags", "xml" ]
stackoverflow_0002228049_python_tags_xml.txt
Q: cross-platform html widget for pygtk I'm trying to write a small gui app in pygtk which needs an html-rendering widget. I'd like to be able to use it in a windows environment. Currently I'm using pywebkitgtk on my GNU/Linux system, and it works extremely well, but it seems it's not possible to use this on Windows...
cross-platform html widget for pygtk
I'm trying to write a small gui app in pygtk which needs an html-rendering widget. I'd like to be able to use it in a windows environment. Currently I'm using pywebkitgtk on my GNU/Linux system, and it works extremely well, but it seems it's not possible to use this on Windows at this time. Can anyone give me any sugg...
[ "In my experience, having developed cross-platform applications with both PyQt and PyGTK, you should consider moving to PyQt. It comes with a browser widget by default which runs fine on all platforms, and support for non-Linux platforms is outstanding compared to PyGTK. For PyGTK, you will have to be prepared buil...
[ 2, 0 ]
[]
[]
[ "cross_platform", "html_rendering", "pygtk", "pyqt", "python" ]
stackoverflow_0002227770_cross_platform_html_rendering_pygtk_pyqt_python.txt
Q: Is there a way to prevent detection by the website when a screenshot is taken using a Mac Os X Safari browser? There is a thread discussing Darwin notifications being sent after a screenshot is taken. Does this apply to websites viewed via Safari? Do the same restrictions apply to PC sytems? Would taking the pictu...
Is there a way to prevent detection by the website when a screenshot is taken using a Mac Os X Safari browser?
There is a thread discussing Darwin notifications being sent after a screenshot is taken. Does this apply to websites viewed via Safari? Do the same restrictions apply to PC sytems? Would taking the picture via a Python script in Linux or running Safari in a VM circumvent detection?
[ "if you are talking about this thread, please note that it seems to apply only to the iPhone. there is nothing similar in any decent web browser on any desktop platform (plus, anybody can put a proxy to filter this kind of notification, or create its own browser out of off-the-shelf components).\nnote that renderin...
[ 2 ]
[]
[]
[ "browser_detection", "python", "safari", "screenshot", "virtual_machine" ]
stackoverflow_0002227469_browser_detection_python_safari_screenshot_virtual_machine.txt
Q: A blackbox testing frame with testing management system Is there a testing framework (preferable python) that executes test, monitor the progress (failed/passed/timeout) and controls the vmware? Thanks I am trying to make some automation functional testing in Vmware using Autoit script, VMs are controlled by a lit...
A blackbox testing frame with testing management system
Is there a testing framework (preferable python) that executes test, monitor the progress (failed/passed/timeout) and controls the vmware? Thanks I am trying to make some automation functional testing in Vmware using Autoit script, VMs are controlled by a little python script on the host machine (deploy test files into...
[ "There are lots of continuous integration tools that may do what you want.\nOne implemented in Python that may fit your need is Buildbot - it can manage running builds and tests across multiple machines and consolidating the results.\n" ]
[ 2 ]
[]
[]
[ "frameworks", "python", "testing", "vmware" ]
stackoverflow_0002228349_frameworks_python_testing_vmware.txt
Q: Python Authentication to SAMBA share I'm able to map the drive without problems on network shares without authentication. But I'm missing something once I try to authenticate with a username and password. Here is the current working example of the code with the error message I keep receiving. #!/usr/bin/python # D...
Python Authentication to SAMBA share
I'm able to map the drive without problems on network shares without authentication. But I'm missing something once I try to authenticate with a username and password. Here is the current working example of the code with the error message I keep receiving. #!/usr/bin/python # Drive Map Script import pywintypes import w...
[ "You aren't passing user_name and user_pass to MapNetworkDrive.\nTry this instead:\ntestnetwork.MapNetworkDrive(drive_letter, network_path, True, user_name, user_pass)\n\nNote: the True passed there is a flag that indicates whether the mapping information is stored in the current user's profile.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002228846_python.txt
Q: How to find the source of increasing memory usage of a twisted server? I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see i...
How to find the source of increasing memory usage of a twisted server?
I have an audio broadcasting server written in Python and based on Twisted. It works fine, but its memory usage is increasing when there are more users on server, but the memory usage never goes down when those users get off line. As you see in following figure: You can see the curve of memory usage goes up where the...
[ "As my guessing, it is due to memory fragmentation problem. The original design is to keep audio data chunks in a list, all of them are not in fixed size. Once the total size of the buffering list exceeds the limit of buffer, it pops some chunks from the top of list for limiting the size. It might looks like thi...
[ 6, 2, 0 ]
[]
[]
[ "memory_leaks", "memory_management", "python", "twisted" ]
stackoverflow_0002100192_memory_leaks_memory_management_python_twisted.txt
Q: Python CDROM Production I have been using Macromedia / Adobe Director & Lingo since 1998. I am extremely familiar with using this software to create CDROMs and DVDs and also have a good knowledge of design elements and their integration such as flash videos, images & audio etc. I am always keen to explore other te...
Python CDROM Production
I have been using Macromedia / Adobe Director & Lingo since 1998. I am extremely familiar with using this software to create CDROMs and DVDs and also have a good knowledge of design elements and their integration such as flash videos, images & audio etc. I am always keen to explore other technologies and understand tha...
[ "sounds grim to me \nI presume you mean an auto-run executable for Windows that runs when a CDROM is inserted, to provide some sort of flashy popup experience thing.\nI would stick with flash. You can make Python executables, and you can use them for this, but flash or a similar tech seems like a better alternative...
[ 1, 1, 0 ]
[]
[]
[ "adobe", "cd_rom", "dvd", "media", "python" ]
stackoverflow_0002228988_adobe_cd_rom_dvd_media_python.txt
Q: How to transform tuple of string(object locations) to dictionary of objects in python I would like to transform a tuple: TEST_CLASSES = ( 'common.test.TestClass', ) to TEST_CLASSES = { 'test': common.test.TestClass, } How to make a dictionary is simple but I have a problem with conversion from string to ob...
How to transform tuple of string(object locations) to dictionary of objects in python
I would like to transform a tuple: TEST_CLASSES = ( 'common.test.TestClass', ) to TEST_CLASSES = { 'test': common.test.TestClass, } How to make a dictionary is simple but I have a problem with conversion from string to object. Could anybody help me please? thanks!
[ "You could use eval, which can be evil if your inputs are not safe:\n>>> import os\n>>> eval('os.path.join')\n<function join at 0x00BBA2B8>\n\nif the common.test.TestClass doesn't exist in the current namespace a NameError will be raised:\n>>> eval('math.isnan')\nTraceback (most recent call last):\n File \"<pyshel...
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002228750_python.txt
Q: Using unicode in Python I have csv file having some address data mostly in Finnish language. I need to read that file and getting some geocode information of these address. But It doesn't work for Finnish alphabet and says it cant read those! Can anybody please help me out of this? import urllib,urllib2,time addr...
Using unicode in Python
I have csv file having some address data mostly in Finnish language. I need to read that file and getting some geocode information of these address. But It doesn't work for Finnish alphabet and says it cant read those! Can anybody please help me out of this? import urllib,urllib2,time addr_file = 'address.csv' out_fil...
[ "The argument of urllib.url should be UTF-8 encoded beforehand:\naddr_file = addr_file.encode(\"utf-8\")\nvalues = {'q' : addr_file, 'output':out_fmt, 'key':gkey}\ndata = urllib.urlencode(values)\n\nAnd make sure you open the CSV file with the correct encoding (might be \"windows-1252\" or \"iso-8859-1\"):\ninf = c...
[ 1, 0, 0, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0002228953_python_unicode.txt
Q: Python MD5 not matching md5 in terminal I am getting MD5 of several files using python function: filehash = hashlib.md5(file) print "FILE HASH: " + filehash.hexdigest() though when I go to the terminal and do a md5 file the result I'm getting is not the same my python script is outputting (they don't match). Any...
Python MD5 not matching md5 in terminal
I am getting MD5 of several files using python function: filehash = hashlib.md5(file) print "FILE HASH: " + filehash.hexdigest() though when I go to the terminal and do a md5 file the result I'm getting is not the same my python script is outputting (they don't match). Any chance someone knows why?
[ "hashlib.md5() takes the contents of the file not its name.\nSee http://docs.python.org/library/hashlib.html\nYou need to open the file, and read its contents before hashing it.\nf = open(filename,'rb')\nm = hashlib.md5()\nwhile True:\n ## Don't read the entire file at once...\n data = f.read(10240)\n if l...
[ 22, 6, 3, 1 ]
[]
[]
[ "hash", "md5", "python" ]
stackoverflow_0002229298_hash_md5_python.txt
Q: Why does Pylint give error E0702, raising NoneType, on this raise statement? Say I have the following code. def foo(): foobar = None if foobar is not None: raise foobar When I run this code through pylint, I get the following error: E0702:4:foo: Raising NoneType while only classes, instances or st...
Why does Pylint give error E0702, raising NoneType, on this raise statement?
Say I have the following code. def foo(): foobar = None if foobar is not None: raise foobar When I run this code through pylint, I get the following error: E0702:4:foo: Raising NoneType while only classes, instances or string are allowed Is this a bug in pylint? Is my pylint too old? pylint 0.18.0, a...
[ "It's a known bug. Pylint doesn't do a lot of flow-control inferencing.\n", "Luckily you can tell pylint that you know better than it does:\ndef foo():\n foobar = None\n if foobar is not None:\n raise foobar # pylint: disable-msg=E0702\n\n" ]
[ 17, 12 ]
[]
[]
[ "exception", "pylint", "python" ]
stackoverflow_0002228790_exception_pylint_python.txt
Q: Python Django simple site I'm trying to create site using Django framework. I looked on tutorial on Django project site but contains much information which I don't need. I have python scripts which provides output and I need to have this output on the web. My question is how simply manage Django to have link which...
Python Django simple site
I'm trying to create site using Django framework. I looked on tutorial on Django project site but contains much information which I don't need. I have python scripts which provides output and I need to have this output on the web. My question is how simply manage Django to have link which start the script and provides ...
[ "\n\"I have python scripts which provides\n output and I need to have this output\n on the web.\"\n\nThat is not what Django is for. What you want to do can be achieved with something as simple as this:\nfrom BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer\n\nclass Handler(BaseHTTPRequestHandler):\n d...
[ 4, 1, 1, 0, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002228966_django_python.txt
Q: Giving 'hints' problem I have a simple word jumble game. I made the jumble already, but now I want to add a 'hint' system. I don't know how to have 1 item from tuples show up. I have 2 tuples, and I want to pull from the 2nd tuple based on the what the first tuple is. I have a WORD=("x", "y", "z") and HINT=("x", "...
Giving 'hints' problem
I have a simple word jumble game. I made the jumble already, but now I want to add a 'hint' system. I don't know how to have 1 item from tuples show up. I have 2 tuples, and I want to pull from the 2nd tuple based on the what the first tuple is. I have a WORD=("x", "y", "z") and HINT=("x", "y", "z"). When the user ente...
[ "Create a dictionary:\n hints = dict(zip(WORD, HINT))\n\nand then:\n if guess=='hint':\n print hints[current_word]\n\nSimple if is not enough?\nif guess != 'hint':\n print \"Sorry, that's not the answer.\"\n\n" ]
[ 3 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002229618_python_tuples.txt
Q: What are features considerd as advanced python? I do basic python programming and now I want to get deep into language features. I have collected/considered the following to be advanced python capabilities and learning them now. Decorator Iterator Generator Meta Class Anything else to be added/considered to the...
What are features considerd as advanced python?
I do basic python programming and now I want to get deep into language features. I have collected/considered the following to be advanced python capabilities and learning them now. Decorator Iterator Generator Meta Class Anything else to be added/considered to the above list?
[ "First, this thread should be community wiki.\nSecond, iterators and generators are pretty basic Python IMHO. I agree with you on decorators and metaclasses. But I'm not a very good programmer, so I probably find this more difficult to wrap my brain around than others.\nThird, I would add threading/multiprocessing ...
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002227537_python.txt
Q: Django: Setting one page as the main page I'm a newbie at Django and I want to do something that I'm not sure how to do. I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.) So I have a bunc...
Django: Setting one page as the main page
I'm a newbie at Django and I want to do something that I'm not sure how to do. I have a model SimplePage, which simply stands for a webpage that is visible on the website and whose contents can be edited in the admin. (I think this is similar to FlatPage.) So I have a bunch of SimplePages for my site, and I want one of...
[ "Create MAIN_PAGE setting inside settings.py with primary key. Then create view main_page nad retrieve the main_page object from the database using the setting.\nEDIT:\nYou can also do it like this: add a model, which will reference a SimplePage and point to the main page. In main page view, you will retrieve the w...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002229640_django_python.txt
Q: Python dictionary instead of switch/case I've recently learned that python doesn't have the switch/case statement. I've been reading about using dictionaries in its stead, like this for example: values = { value1: do_some_stuff1, value2: do_some_stuff2, valueN: do_some_stuffN, } values.get(var, d...
Python dictionary instead of switch/case
I've recently learned that python doesn't have the switch/case statement. I've been reading about using dictionaries in its stead, like this for example: values = { value1: do_some_stuff1, value2: do_some_stuff2, valueN: do_some_stuffN, } values.get(var, do_default_stuff)() What I can't figure out is...
[ "A dictionary is the wrong structure for this. The bisect examples show an example of this sort of range test.\n", "Whilst the dictionary approach works well for single values, if you want ranges, if ... else if ... else if is probably the simplest approach.\nIf you're looking for a single value this a good match...
[ 11, 5, 3, 3, 0, -2 ]
[]
[]
[ "dictionary", "python", "switch_statement" ]
stackoverflow_0002222859_dictionary_python_switch_statement.txt
Q: Dynamic form requirements in Django I am about to start a large Django project at work. And the key features are form handling. There is going to be a lot of forms that the users of the app is going to use. And one requirement is that it should be possible to edit the forms in the admin interface of the applicatio...
Dynamic form requirements in Django
I am about to start a large Django project at work. And the key features are form handling. There is going to be a lot of forms that the users of the app is going to use. And one requirement is that it should be possible to edit the forms in the admin interface of the application. That is, it is not a requirement to a...
[ "You should use certain models for this. For every form that might be customised this way, a new database entry must be created. I guess, it should look like this:\nclass FormSettings(Model):\n form = CharField(..)\n\nclass FormAttrib(Model):\n form_settings = ForeignKey(FormSettings)\n field = CharField(..)\n ...
[ 2, 2 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0002229427_django_forms_python.txt
Q: How to get the system library path on Unix (Linux, FreeBSD) I need a more-or-less portable programmatic way for querying the dynamic library path list. For Linux, I can concatenate the $LD_LIBRARY_PATH and the contents of /etc/ld.so.conf (processing the include directives as needed and possibly filtering by archit...
How to get the system library path on Unix (Linux, FreeBSD)
I need a more-or-less portable programmatic way for querying the dynamic library path list. For Linux, I can concatenate the $LD_LIBRARY_PATH and the contents of /etc/ld.so.conf (processing the include directives as needed and possibly filtering by architecture), but that doesn't work e.g. on FreeBSD. Ultimately, I nee...
[ "For both Linux and FreeBSD you can try working through the output of ldconfig(8). The options for listing the libraries are different though (-p on Linux, -r on FreeBSD.) Hope this helps.\nEdit:\nSolaris is different - see man crle.\nMac OSX is different yet again - see man dyld.\n" ]
[ 6 ]
[]
[]
[ "freebsd", "library_path", "linux", "python", "unix" ]
stackoverflow_0002230467_freebsd_library_path_linux_python_unix.txt
Q: Django urlsafe base64 decoding with decryption I'm writing my own captcha system for user registration. So I need to create a suitable URL for receiving generated captcha pictures. Generation looks like this: _cipher = cipher.new(settings.CAPTCHA_SECRET_KEY, cipher.MODE_ECB) _encrypt_block = lambda block: _cipher....
Django urlsafe base64 decoding with decryption
I'm writing my own captcha system for user registration. So I need to create a suitable URL for receiving generated captcha pictures. Generation looks like this: _cipher = cipher.new(settings.CAPTCHA_SECRET_KEY, cipher.MODE_ECB) _encrypt_block = lambda block: _cipher.encrypt(block + ' ' * (_cipher.block_size - len(bloc...
[ "The problem is that b64decode quite explicitly can only take bytes (a string), not unicode.\n>>> import base64\n>>> test = \"Hi, I'm a string\"\n>>> enc = base64.urlsafe_b64encode(test)\n>>> enc\n'SGksIEknbSBhIHN0cmluZw=='\n>>> uenc = unicode(enc)\n>>> base64.urlsafe_b64decode(enc)\n\"Hi, I'm a string\"\n>>> base6...
[ 41, 3 ]
[]
[]
[ "base64", "django", "encoding", "encryption", "python" ]
stackoverflow_0002229827_base64_django_encoding_encryption_python.txt
Q: how to get specific nodes in xml file with python im searching for a way to get a specific tags .. from a very big xml document with python dom built in module for example : <AssetType longname="characters" shortname="chr" shortnames="chrs"> <type> pub </type> <type> geo </type> <type> rig ...
how to get specific nodes in xml file with python
im searching for a way to get a specific tags .. from a very big xml document with python dom built in module for example : <AssetType longname="characters" shortname="chr" shortnames="chrs"> <type> pub </type> <type> geo </type> <type> rig </type> </AssetType> <AssetType longname="camera" sh...
[ "If you don't mind loading the whole document into memory:\nfrom lxml import etree\ndata = etree.parse(fname)\nresult = [node.text.strip() \n for node in data.xpath(\"//AssetType[@longname='characters']/type\")]\n\nYou may need to remove the spaces at the beginning of your tags to make this work.\n", "Assuming...
[ 8, 8, 3, 2, 1, 1 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0002230677_python_xml.txt
Q: Python, next iteration of the loop over a loop I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code) ok = 0 for x in range(0,10): if ok == 1: ok = 0 continue ...
Python, next iteration of the loop over a loop
I need to get the next item of the first loop given certain condition, but the condition is in the inner loop. Is there a shorter way to do it than this? (test code) ok = 0 for x in range(0,10): if ok == 1: ok = 0 continue for y in range(0,20): if y == 5: ...
[ "Replace the continue in the inner loop with a break. What you want to do is to actually break out of the inner loop, so a continue there does the opposite of what you want.\nok = 0\nfor x in range(0,10):\n print \"x=\",x\n if ok == 1:\n ok = 0\n continue\n for y in range(0,20): \n pri...
[ 15, 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002230244_python.txt
Q: Are there any downsides to upgrading Python on Snow Leopard? I want to use the newest version of Python on Snow Leopard using the installer package, but I've read some confusing articles about conflicts when upgrading. I plan on using PyDev in Eclipse, will there be any conflicts with Snow Leopard if I upgrade? A...
Are there any downsides to upgrading Python on Snow Leopard?
I want to use the newest version of Python on Snow Leopard using the installer package, but I've read some confusing articles about conflicts when upgrading. I plan on using PyDev in Eclipse, will there be any conflicts with Snow Leopard if I upgrade?
[ "To answer your question explicitly: Are there any downsides to upgrading Python on SL? Only if you upgrade the system installation. It can have strange repercussions on any system/CLI tools that use Python, and on any bundled applications (.app) that are utilizing PyObjC runtime libraries.\nI would not upgrade, t...
[ 3 ]
[]
[]
[ "macos", "osx_snow_leopard", "python" ]
stackoverflow_0002230968_macos_osx_snow_leopard_python.txt
Q: Is there an alternative to the threading.Condition variables in python that better support timeouts without polling? I'm using condition variables in threads that require a timeout. I didn't notice until I saw the CPU usage when having a lot of threads running, that the condition variable provided in the threading...
Is there an alternative to the threading.Condition variables in python that better support timeouts without polling?
I'm using condition variables in threads that require a timeout. I didn't notice until I saw the CPU usage when having a lot of threads running, that the condition variable provided in the threading module doesn't actually sleep, but polls when a timeout is provided as an argument. Is there an alternative to this that ...
[ "This seems tricky to do in Python, but here is a one solution. It relies on spawning additional threads but doesn't use polling AND ensures that the original thread is woken up as soon as the timeout expires or as soon as the original wait() returns.\nNote: The following code includes a test case which tests both...
[ 3, 1 ]
[]
[]
[ "condition_variable", "multithreading", "python" ]
stackoverflow_0002229086_condition_variable_multithreading_python.txt
Q: getting an attachment from a Outlook mail in linux I would like to get a file attached to an email I receive using Outlook. I need to run this python script in a Linux Box. I read about the win32com.client library. Do you know if it works also for Linux? If not do you know any alternative if there are? A: Coinc...
getting an attachment from a Outlook mail in linux
I would like to get a file attached to an email I receive using Outlook. I need to run this python script in a Linux Box. I read about the win32com.client library. Do you know if it works also for Linux? If not do you know any alternative if there are?
[ "Coincidentally, today I posted an example of retrieving attachments over IMAP here, it may be of some use to you.\nOutlook is an email client, it may use one or more of a variety of protocols (MAPI,POP,IMAP) to access your mailbox. Your mail may be stored on the server, or it may be stored on your computer (more l...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0002230958_python.txt
Q: Python comparison evaluation As per the python documentation,x<y<z comparison is translated to x<y and y<z and expression y is evaluated only once at most. Now my question is , does an expression y ( look at the code below) is evaluated only once here? if(x<y and y<z): A: Twice: >>> def f(): ... print "F call...
Python comparison evaluation
As per the python documentation,x<y<z comparison is translated to x<y and y<z and expression y is evaluated only once at most. Now my question is , does an expression y ( look at the code below) is evaluated only once here? if(x<y and y<z):
[ "Twice:\n>>> def f():\n... print \"F called\"\n... return 1\n...\n>>> 0 < f() < 100\nF called\nTrue\n>>> 0 < f() and f() < 100\nF called\nF called\nTrue\n>>> if (0 < f() and f() < 100):\n... print True\n...\nF called\nF called\nTrue\n>>>\n\n", "No:\n>>> dis.dis(lambda x, y, z: x < y() < z)\n 1 0 ...
[ 9, 3 ]
[]
[]
[ "comparison", "python", "syntax" ]
stackoverflow_0002231220_comparison_python_syntax.txt
Q: pyserial- sending in parameters at runtime- input vs. raw_input - security flaw? I am writing a program that opens and records data sent through a serial port into a text file. I am currently adding functionality to allow reconfiguring the serial port during run-time. I prompt the user to choose which variable to ...
pyserial- sending in parameters at runtime- input vs. raw_input - security flaw?
I am writing a program that opens and records data sent through a serial port into a text file. I am currently adding functionality to allow reconfiguring the serial port during run-time. I prompt the user to choose which variable to change one at a time, so as to keep it simple for myself (i would appreciate elegant s...
[ "The safest way is just to accept the user's input as a string and then parse it. I.e. let the user enter key=value pairs:\nbaudrate = 9600\nparity = N\n\nThen parse these pairs, by splitting on '=' and stripping both sides. Assign the variables with a string lookup table (the baudrate string maps to the baudrate v...
[ 0 ]
[]
[]
[ "pyserial", "python", "security", "user_input" ]
stackoverflow_0002231249_pyserial_python_security_user_input.txt
Q: Unexpected object assignment class TrafficData(object): def __init__(self): self.__data = {} def __getitem__(self, epoch): if not isinstance(epoch, int): raise TypeError() return self.__data.setdefault(epoch, ProcessTraffic()) def __iadd__(self, other): for e...
Unexpected object assignment
class TrafficData(object): def __init__(self): self.__data = {} def __getitem__(self, epoch): if not isinstance(epoch, int): raise TypeError() return self.__data.setdefault(epoch, ProcessTraffic()) def __iadd__(self, other): for epoch, traffic in other.iteritems()...
[ "What you are exactly doing in:\nself[epoch] += traffic\n\nis:\nself[epoch] = self[epoch] + traffic\n\nBut you haven't defined __setitem__ method, so you can do that on self.\nYou also need:\ndef __setitem__(self, epoch, value):\n self.__data[epoch] = value\n\nor something similar.\n", "\nIt's probably wor...
[ 6, 1, 0 ]
[]
[]
[ "dictionary", "python", "variable_assignment" ]
stackoverflow_0002230993_dictionary_python_variable_assignment.txt
Q: Mako thinks my template has a 'pass' after an if statement, even though the traceback shows there isn't one I have Mako taking a template from a preprocessor, and now thinks there is a 'pass' after my if statement. Here is the complete traceback Error ! SyntaxException: (SyntaxError) invalid syntax (, line 1) (u"i...
Mako thinks my template has a 'pass' after an if statement, even though the traceback shows there isn't one
I have Mako taking a template from a preprocessor, and now thinks there is a 'pass' after my if statement. Here is the complete traceback Error ! SyntaxException: (SyntaxError) invalid syntax (, line 1) (u"if ${session['anonymous']}:pass") in file '/.../site/templates/shpaml/views/index.html' at line: 3 char: 1 1 <p>yo...
[ "Well, this is one of those embarrassing cases that took days of agony to figure out something so simple:\nIt needed to be \nif session['anonymous']:\n\n" ]
[ 1 ]
[]
[]
[ "mako", "python", "syntax_error" ]
stackoverflow_0002230455_mako_python_syntax_error.txt
Q: how can i pass xml format data from flex to python i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python sh...
how can i pass xml format data from flex to python
i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python should convert all the data into xml format,and pass all t...
[ "See http://www.artima.com/weblogs/viewpost.jsp?thread=208528 for more details, here is a breif overview of what I think you are looking for.\nThe SimpleXMLRPCServer library allows you to easily create a server. Here's about the simplest server you can create, which provides two services to manipulate strings: \nim...
[ 1 ]
[]
[]
[ "flex3", "mysql", "python" ]
stackoverflow_0002228078_flex3_mysql_python.txt
Q: What's python complaining about here? I'm trying to run Adobe's sample python policy server script, linked to here: http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html I'm getting the following error: # python flashpolicyd.py --file=policy.xml File "flashpolicyd.py", line 40 with file(p...
What's python complaining about here?
I'm trying to run Adobe's sample python policy server script, linked to here: http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html I'm getting the following error: # python flashpolicyd.py --file=policy.xml File "flashpolicyd.py", line 40 with file(path, 'rb') as f: ^ SyntaxError:...
[ "with is only available in 2.6+, or in 2.5+ with from __future__ import with_statement.\n", "The with statement is new in Python 2.5. Perhaps you are using an older version?\n" ]
[ 6, 1 ]
[]
[]
[ "flash", "policyfiles", "python", "sockets" ]
stackoverflow_0002231954_flash_policyfiles_python_sockets.txt
Q: Assign a value equal only to itself I wish to assign to a variable (a "constant"), a value that will allow that variable to only ever return True in is and == comparisons against itself. I want to avoid assigning an arbitary value such as an int or some other type on the off chance that the value I choose clashes ...
Assign a value equal only to itself
I wish to assign to a variable (a "constant"), a value that will allow that variable to only ever return True in is and == comparisons against itself. I want to avoid assigning an arbitary value such as an int or some other type on the off chance that the value I choose clashes with some other. I'm considering generati...
[ "Yes. This is a good way to define unique constants. There is of course, the minimal risk of whatever object you are comparing it to being defined as equal to everything, but if everyone is playing reasonably nicely, this should work. Also, the garbage collection issue won't be a problem, because if that should ...
[ 1, 0 ]
[]
[]
[ "comparison", "constants", "cpython", "python", "unique" ]
stackoverflow_0002231781_comparison_constants_cpython_python_unique.txt
Q: check that a script is actually using a proxy from a ip list I have a list of proxy ip's that I want to use in one of my python scripts, but how do I verify that I am using one of the ip addresses from the list and not my own? I'm using mechanize, but any general explanation of how to do this would be helpful. ...
check that a script is actually using a proxy from a ip list
I have a list of proxy ip's that I want to use in one of my python scripts, but how do I verify that I am using one of the ip addresses from the list and not my own? I'm using mechanize, but any general explanation of how to do this would be helpful. This is the first time I have worked with proxies, so anything you...
[ "Running wireshark / tshark would be one way.\nMany proxies run on port 3128, but substitute this for the proxy you're using. Make you request and if you get traffic to the host and port of your configured proxy, it's probably \nworking. If it goes to the host for the website, then it's not.\nE.g. First without a p...
[ 1 ]
[]
[]
[ "proxy", "python" ]
stackoverflow_0002231887_proxy_python.txt
Q: Updating python variable from c I am having an intermittent error causing my Python module to crash, and I'm assuming it's because of a memory error occurring by not getting the refcounts correct in the c code. I have a bit of code that gets a response at a random time from a remote location. Based on the data rec...
Updating python variable from c
I am having an intermittent error causing my Python module to crash, and I'm assuming it's because of a memory error occurring by not getting the refcounts correct in the c code. I have a bit of code that gets a response at a random time from a remote location. Based on the data received, it needs to update a data vari...
[ "PyModule_AddObject() steals a reference. As such, you should not be decrefing list after.\n", "PyList_New() can return NULL to indicate an error, which you aren't checking for. Py_BuildValue() can return NULL to indicate an error, which you aren't checking for. PyList_Append() can return -1 to indicate an error,...
[ 1, 1 ]
[]
[]
[ "c", "python" ]
stackoverflow_0002231287_c_python.txt
Q: Python newbie having a problem using classes Im just beginning to mess around a bit with classes; however, I am running across a problem. class MyClass(object): def f(self): return 'hello world' print MyClass.f The previous script is returning <unbound method MyClass.f> instead of the intended value. ...
Python newbie having a problem using classes
Im just beginning to mess around a bit with classes; however, I am running across a problem. class MyClass(object): def f(self): return 'hello world' print MyClass.f The previous script is returning <unbound method MyClass.f> instead of the intended value. How do I fix this?
[ "MyClass.f refers to the function object f which is a property of MyClass. In your case, f is an instance method (has a self parameter) so its called on a particular instance. Its \"unbound\" because you're referring to f without specifying a specific class, kind of like referring to a steering wheel without a car....
[ 13, 6 ]
[]
[]
[ "class", "python" ]
stackoverflow_0002232740_class_python.txt
Q: How to include in code an unique ID related to a mercurial commit? I'd like to do the same thing that they're doing here in stackoverflow. <link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6274"> <script type="text/javascript" src="http://sstatic.net/so/js/master.js?v=6180"></script> <script src="http...
How to include in code an unique ID related to a mercurial commit?
I'd like to do the same thing that they're doing here in stackoverflow. <link rel="stylesheet" href="http://sstatic.net/so/all.css?v=6274"> <script type="text/javascript" src="http://sstatic.net/so/js/master.js?v=6180"></script> <script src="http://sstatic.net/so/js/question.js?v=6274" type="text/javascript"></script...
[ "KeywordExtension will let you put a keyword in a file whose results you can tear apart in order to get the hash.\n" ]
[ 4 ]
[]
[]
[ "caching", "django", "mercurial", "python" ]
stackoverflow_0002232852_caching_django_mercurial_python.txt
Q: Compiling Mysqldb for jython 2.5 on Solaris I have used python2.6 + MySQL on Windows and there are binaries available. I wanted to get the whole thing working on Solaris Hence got the Mysql-Python package from here I had to get the setuptools installed which is done. Exploded the MySQL-python-1.2.3c1 When I this ...
Compiling Mysqldb for jython 2.5 on Solaris
I have used python2.6 + MySQL on Windows and there are binaries available. I wanted to get the whole thing working on Solaris Hence got the Mysql-Python package from here I had to get the setuptools installed which is done. Exploded the MySQL-python-1.2.3c1 When I this /jython2.5.1/jython setup.py build Error - `File ...
[ "You should be using zxJDBC and JDBC instead of an external DB-API adapter.\n" ]
[ 1 ]
[]
[]
[ "driver", "jython", "mysql", "python", "solaris" ]
stackoverflow_0002233422_driver_jython_mysql_python_solaris.txt
Q: Python - letter frequency count and translation I am using Python 3.1, but I can downgrade if needed. I have an ASCII file containing a short story written in one of the languages the alphabet of which can be represented with upper and or lower ASCII. I wish to: 1) Detect an encoding to the best of my abilities, g...
Python - letter frequency count and translation
I am using Python 3.1, but I can downgrade if needed. I have an ASCII file containing a short story written in one of the languages the alphabet of which can be represented with upper and or lower ASCII. I wish to: 1) Detect an encoding to the best of my abilities, get some sort of confidence metric (would vary dependi...
[ "Essentially there are three main tasks to implement the described application:\n\n1a) Identify the character encoding of the input text\n1b) Identify the language of the input text\n2) Get the text translated the text, by way of one of the online services' API\n\nFor 1a, you may want to take a look at decodeh.py, ...
[ 3, 2, 2, 1 ]
[]
[]
[ "character_encoding", "nlp", "python", "translation" ]
stackoverflow_0002233355_character_encoding_nlp_python_translation.txt
Q: How to delete list elements while cycling the list itself without duplicate it I lost a little bit of time in this Python for statement: class MyListContainer: def __init__(self): self.list = [] def purge(self): for object in self.list: if (object.my_cond()): se...
How to delete list elements while cycling the list itself without duplicate it
I lost a little bit of time in this Python for statement: class MyListContainer: def __init__(self): self.list = [] def purge(self): for object in self.list: if (object.my_cond()): self.list.remove(object) return self.list container = MyListContainer() # no...
[ "Don't try. Just don't. Make a copy or generate a new list.\n", "Just make yourself a new list:\ndef purge(self):\n self.list = [object for object in self.list if not object.my_cond()]\n return self.list\n\nReserve any optimization until you've profiled and found that this method really is the bottleneck of...
[ 5, 3, 2, 2, 0, 0 ]
[ "indeces = []\nminus = 0\n\nfor i in range(self.list):\n if cond(self.list[i]):\n indeces.append(i)\n\nfor i in indeces:\n self.list = self.list[:(i-minus)].extend(self.list[i-minus+1:])\n\n" ]
[ -1 ]
[ "cycle", "list", "python" ]
stackoverflow_0002233388_cycle_list_python.txt
Q: Can I port my existing python apps on ASE? I learned that the Android Scripting Environment (ASE) supports python code. Can I take my existing python programs and run them on android? Apart from the GUI, what else will I need to adapt? How can I find the list of supported python libraries for ASE? A: As of yet,...
Can I port my existing python apps on ASE?
I learned that the Android Scripting Environment (ASE) supports python code. Can I take my existing python programs and run them on android? Apart from the GUI, what else will I need to adapt? How can I find the list of supported python libraries for ASE?
[ "As of yet, there is no support for a gui on ASE apart from some simple input and display dialogs. Look at /sdcard/ase/extras/python to find libraries already available. You can add new libraries by copying them there.\n" ]
[ 4 ]
[]
[]
[ "android", "android_scripting", "ase", "python" ]
stackoverflow_0002233631_android_android_scripting_ase_python.txt
Q: How do I prevent duplicating code with pylons html table updated via ajax? I have a pylons web-page with a table. I have created python functions in the template which help with the construction of the table html. One of these functions takes an 'item' and generates an html row while also adding css zebra stripi...
How do I prevent duplicating code with pylons html table updated via ajax?
I have a pylons web-page with a table. I have created python functions in the template which help with the construction of the table html. One of these functions takes an 'item' and generates an html row while also adding css zebra striping. The other def generates the header row's html. This works perfectly for lo...
[ "One possibility would be to actually generate the AJAX HTML server-side (instead of generating JSON), and insert it right into the DOM tree (instead of parsing the JSON and generating the HTML on the client). Then you could use the same functions on the server side to generate the AJAX rows before they are shipped...
[ 1 ]
[]
[]
[ "ajax", "html_table", "pylons", "python" ]
stackoverflow_0002234153_ajax_html_table_pylons_python.txt
Q: how do I iterate over a "gslist" in Python? Let's say I get a glib gpointer to a glib gslist and would like to iterate over the latter, how would I do it? I don't even know how to get to the gslist with the gpointer for starters! Update: I found a workaround - the python bindings in this instance wasn't complete s...
how do I iterate over a "gslist" in Python?
Let's say I get a glib gpointer to a glib gslist and would like to iterate over the latter, how would I do it? I don't even know how to get to the gslist with the gpointer for starters! Update: I found a workaround - the python bindings in this instance wasn't complete so I had to find another solution.
[ "How is glib exposed to Python in your application? Via SWIG, ctypes or something else? \nYou should basically use glib's own functions to iterate over a list. Something like g_slist_foreach. Just pass it the pointer and its other parameters to do the job. Again, this heavily depends on how you access glib in your ...
[ 0 ]
[]
[]
[ "glib", "python" ]
stackoverflow_0002234056_glib_python.txt
Q: building dynamic forms in django I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label. How do I build a form dynamically in my view from the data in the db? Thanks A: Here are the s...
building dynamic forms in django
I'm trying to build a form dynamically based on the field and its definitions stored in a database. In my db, I have defined 1 checkbox with some label and 1 textfield with some label. How do I build a form dynamically in my view from the data in the db? Thanks
[ "Here are the slides from a talk I gave at EuroDjangoCon about doing precisely this: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth\n", "Django does a great job auto-generating forms from your model definitions.\nThe first step might be to create a Django model that mirrors your existing datab...
[ 11, 5 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0002234117_django_django_forms_python.txt
Q: Can I catch error in a list comprehensions to be sure to loop all the list items I've got a list comprehensions which filter a list: l = [obj for obj in objlist if not obj.mycond()] but the object method mycond() can raise an Exception I must intercept. I need to collect all the errors at the end of the loop to s...
Can I catch error in a list comprehensions to be sure to loop all the list items
I've got a list comprehensions which filter a list: l = [obj for obj in objlist if not obj.mycond()] but the object method mycond() can raise an Exception I must intercept. I need to collect all the errors at the end of the loop to show which object has created any problems and at the same time I want to be sure to lo...
[ "I would use a little auxiliary function:\ndef f(obj, errs):\n try: return not obj.mycond()\n except MyException as err: errs.append((obj, err))\n\nerrs = []\nl = [obj for obj in objlist if f(obj, errs)]\nif errs:\n emiterrorinfo(errs)\n\nNote that this way you have in errs all the errant objects and the specifi...
[ 9, 1, 0, 0 ]
[]
[]
[ "cycle", "exception", "list", "python" ]
stackoverflow_0002233975_cycle_exception_list_python.txt
Q: Where do stdout and stderr go when in curses mode? Where do stdout and stderr go when curses is active? import curses, sys def test_streams(): print "stdout" print >>sys.stderr, "stderr" def curses_mode(stdscr): test_streams() test_streams() curses.wrapper(curses_mode) Actual output is stdout stder...
Where do stdout and stderr go when in curses mode?
Where do stdout and stderr go when curses is active? import curses, sys def test_streams(): print "stdout" print >>sys.stderr, "stderr" def curses_mode(stdscr): test_streams() test_streams() curses.wrapper(curses_mode) Actual output is stdout stderr Update0 Expected output is stdout stderr stdout stder...
[ "Activating curses saves the terminal text screen's current contents and clears said screen; exiting curses restores the screen's contents (tossing away whatever's been put on screen during the reign of curses itself). Try with this variant of your code and you'll see better what's happening:\nimport curses, sys, ...
[ 6 ]
[]
[]
[ "curses", "ncurses", "python" ]
stackoverflow_0002233006_curses_ncurses_python.txt
Q: Django Group By relation's data In Django, I can do value(), and then distinct() to group by. A { Foreign Key B } B { String name } However, is it possible to group using a related object's data? I.e. In the above relation, can I group A by B's name? A: I think you can order_by on the FKey model. A.o...
Django Group By relation's data
In Django, I can do value(), and then distinct() to group by. A { Foreign Key B } B { String name } However, is it possible to group using a related object's data? I.e. In the above relation, can I group A by B's name?
[ "I think you can order_by on the FKey model.\nA.objects.order_by('B__name')\n\nIff you can't, You need to use the Django ORM's Annotation API, to make a new field and you will be able to order it accordingly:\nA.objects.annotate(bname='B__name').order_by('bname')\n\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "group_by", "python" ]
stackoverflow_0002234181_django_django_models_group_by_python.txt
Q: Error message in python-mysql cursor: 1054 unknown column "x" in 'field list' This is my first post! I also just started programming, so please bear with me! I am trying to load a bunch of .csv files into a database, in order to later perform various reports on the data. I started off by creating a few tables in ...
Error message in python-mysql cursor: 1054 unknown column "x" in 'field list'
This is my first post! I also just started programming, so please bear with me! I am trying to load a bunch of .csv files into a database, in order to later perform various reports on the data. I started off by creating a few tables in mysql with matching field names and data types to what will be loaded into the tabl...
[ "Thomas is, as usual, absolutely correct: feel free to let MySQLdb handle the quoting issues.\nIn addition to that recommendation:\n\nThe csv module is your friend.\nMySQLdb uses the \"format\" parameter style as detailed in PEP 249.\nWhat does that mean for you?\nAll parameters, whatever type, should be passed to ...
[ 2, 1 ]
[]
[]
[ "mysql", "mysql_error_1054", "python" ]
stackoverflow_0002226258_mysql_mysql_error_1054_python.txt
Q: PyEval_CallObject failing in loop occasionally I am struggling a bit with the Python C API. I am calling a python method to do some game AI at about 60hz. It works most of the time but every second or so the call to PyEval_CallObject results in a NULL return value. If I correctly detect the error and continue lo...
PyEval_CallObject failing in loop occasionally
I am struggling a bit with the Python C API. I am calling a python method to do some game AI at about 60hz. It works most of the time but every second or so the call to PyEval_CallObject results in a NULL return value. If I correctly detect the error and continue looping, all is well for the next second or so, whereu...
[ "You can call PyImport_Import() as often as you like, but you'll just keep getting the same module object back. Python caches imports. Also, instead of creating a new Python string and leaking the reference (and thus the object), you should just use PyImport_ImportModule(), which takes a const char *.\nPyImport_Imp...
[ 5 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0002234539_c_python_python_c_api.txt
Q: Python design question I'm a C programmer and I'm getting quite good with Python. But I still have some problems getting my mind around the OO awesomeness of Python. Here is my current design problem: The end "product" is a JSON data structure created in Python (and passed to Javascript code) containing different...
Python design question
I'm a C programmer and I'm getting quite good with Python. But I still have some problems getting my mind around the OO awesomeness of Python. Here is my current design problem: The end "product" is a JSON data structure created in Python (and passed to Javascript code) containing different types of data like: { type:...
[ "In my mind, it basically goes like this: you should try to keep things the same where they are the same, and separate them where they're different.\nIf you're performing the exact same operations on and with the data, and it can all be represented in a common format, then there's no reason to have separate objects...
[ 5, 3, 2, 1, 1 ]
[]
[]
[ "json", "oop", "python" ]
stackoverflow_0002234531_json_oop_python.txt
Q: How to get path of Start Menu's Programs directory? ...for current user? for all users? I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more po...
How to get path of Start Menu's Programs directory?
...for current user? for all users? I'm working an a small program which needs to create links in the start menu. Currently I'm hardcoding like below, but it only works in english locales, for example it should be "Startmenü" in german. What are cleaner, more portable approaches? OUR_STARTMENU = os.environ['ALLUSERSPR...
[ "I've heard of 2 ways of doing this. First:\nfrom win32com.shell import shell\nshell.SHGetSpecialFolderPath(0,shellcon.CSIDL_COMMON_STARTMENU)\n\nSecond, using the WScript.Shell object (source : http://www.mail-archive.com/python-win32@python.org/msg00992.html):\nimport win32com.client\nobjShell = win32com.client.D...
[ 11, 2, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0002216173_python_windows.txt
Q: Drawing Hebrew text to and image using Image module (python) This is an issue I already asked about and several got answers but the problem remained. when I try to write in hebrew to an image using Image module I get instead of the hebrew lettring some other (ascii??) lettering. if I convert to unicode or ascii I ...
Drawing Hebrew text to and image using Image module (python)
This is an issue I already asked about and several got answers but the problem remained. when I try to write in hebrew to an image using Image module I get instead of the hebrew lettring some other (ascii??) lettering. if I convert to unicode or ascii I get an error that it doesn't support. I got here a reference to a ...
[ "Sounds like PIL was built without FreeType support. Install the FreeType dev files and rebuild PIL again.\n", "the problem was the PIL 1.1.7 doesn't work well with windows XP. the same code runs well under linux or with XP but with PIL 1.1.6\nmystory is solved\n" ]
[ 3, 1 ]
[]
[]
[ "bidirectional", "hebrew", "image", "python" ]
stackoverflow_0002182787_bidirectional_hebrew_image_python.txt
Q: Having "Exception Value: The _imaging C module is not installed" with my Buildout/Python/Django/PIL on Mac OSX SL? I'm using Buildout for my Django projects, with FeinCMS. I've got it setup great locally on my Mac OSX Snow Leopard, with no errors coming up at all when I use runserver. But when I upload an image wi...
Having "Exception Value: The _imaging C module is not installed" with my Buildout/Python/Django/PIL on Mac OSX SL?
I'm using Buildout for my Django projects, with FeinCMS. I've got it setup great locally on my Mac OSX Snow Leopard, with no errors coming up at all when I use runserver. But when I upload an image with FeinCMS in the admin area it comes up with a "Exception Value: The _imaging C module is not installed" error. My tra...
[ "I have gone through the same thing today and found a solution. The problem is that PIL will look for 32-bit libjpeg and Snow Leopard will compile the library as x86_64 by default. This could be fixed by modifying your libjpeg section to look like this:\n[libjpeg]\nrecipe = hexagonit.recipe.cmmi\nurl = http://www.i...
[ 2 ]
[]
[]
[ "buildout", "django", "python", "python_imaging_library" ]
stackoverflow_0002124306_buildout_django_python_python_imaging_library.txt
Q: Subclass builtin List I want to subclass the list type and have slicing return an object of the descendant type, however it is returning a list. What is the minimum code way to do this? If there isn't a neat way to do it, I'll just include a list internally which is slightly more messy, but not unreasonable. My c...
Subclass builtin List
I want to subclass the list type and have slicing return an object of the descendant type, however it is returning a list. What is the minimum code way to do this? If there isn't a neat way to do it, I'll just include a list internally which is slightly more messy, but not unreasonable. My code so far: class Channel(l...
[ "I guess you should override the __getslice__ method to return an object of your type...\nMaybe something like the following?\nclass MyList(list):\n #your stuff here\n\n def __getslice__(self, i, j):\n return MyList(list.__getslice__(self, i, j))\n\n" ]
[ 11 ]
[]
[]
[ "built_in", "list", "python", "subclass" ]
stackoverflow_0002235556_built_in_list_python_subclass.txt
Q: How to split a list into a given number of sub-lists in python Possible Duplicates: splitting a list of arbitrary size into only roughly N-equal parts How do you split a list into evenly sized chunks in Python? I need to create a function that will split a list into a list of list, each containing an equal numbe...
How to split a list into a given number of sub-lists in python
Possible Duplicates: splitting a list of arbitrary size into only roughly N-equal parts How do you split a list into evenly sized chunks in Python? I need to create a function that will split a list into a list of list, each containing an equal number of items (or as equal as possible). e.g. def split_lists(mainlist...
[ "numpy.split does this already: \n\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.split.html\n\nExamples:\n>>> mylist = np.array([1,2,3,4,5,6])\n\n\nsplit_list(mylist,2) will return a list of two lists of three elements\n - [[1,2,3][4,5,6]].\n\n>>> np.split(mylist, 2)\n[array([1, 2, 3]), array([4, 5, 6...
[ 6 ]
[]
[]
[ "list", "python" ]
stackoverflow_0002235526_list_python.txt
Q: Automate file download from http using python I want to automatically save a file from a website. I don't know how to bypass the Download File prompt in python and save it directly to my c: drive. Any help is appreciated, Elliott A: Modules like urllib2 and urlgrabber don't have a "Download File" prompt. A: On...
Automate file download from http using python
I want to automatically save a file from a website. I don't know how to bypass the Download File prompt in python and save it directly to my c: drive. Any help is appreciated, Elliott
[ "Modules like urllib2 and urlgrabber don't have a \"Download File\" prompt.\n", "One idea is to use a module like mechanize to automate the query and the download.\nHere you can find some documentation.\n\nUsually when you post a question here at stackoverflow, it is a good idea to post an example at how you have...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002235458_python.txt
Q: Django: Can't set ForeignKey value to None from admin I have a model Category which has a ForeignKey to a SimplePage model. null and blank are set to True. The problem is, when I edit a Category from the admin interface, I can't change the ForeignKey to --------- (Which looks like the admin's way of saying None.) ...
Django: Can't set ForeignKey value to None from admin
I have a model Category which has a ForeignKey to a SimplePage model. null and blank are set to True. The problem is, when I edit a Category from the admin interface, I can't change the ForeignKey to --------- (Which looks like the admin's way of saying None.) The value can be None initially, and I can change it to an ...
[ "Maybe that's because you have OneToOne relationship defined also in category and you can't therefore break this relationship. Try to remove it and see, if you can set category in SimplePage to None.\n", "gruszczy above is right, each side of o2o relation cannot be null after it was assigned, because django won't...
[ 2, 0 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0002220838_django_orm_python.txt
Q: Interchange of Position of Two Keyword Arguments Throws Error I have an odd problem. I know that in Python, kwargs follow args, so I checked for that and it's not the problem. What is the problem is this: Fine: def __init__(self, sample_rate, label=u"", data=[] ): TypeError: __init__() got multiple values for key...
Interchange of Position of Two Keyword Arguments Throws Error
I have an odd problem. I know that in Python, kwargs follow args, so I checked for that and it's not the problem. What is the problem is this: Fine: def __init__(self, sample_rate, label=u"", data=[] ): TypeError: __init__() got multiple values for keyword argument 'data': def __init__(self, sample_rate, data=[], lab...
[ "You are calling the code with\nChannel(self.sample_rate, self.label, data=list.__getslice__(self,start,stop))\n\nNote that the second parameter has no keyword, so the interpreter assumes this is the data parameter (because that's the order they are defined in the function). If you add label= it should solve it.\nB...
[ 4, 4, 2 ]
[]
[]
[ "keyword_argument", "python" ]
stackoverflow_0002235895_keyword_argument_python.txt
Q: How to get enumerated results from a query in Django? I have a query that orders a table according to a particular field. The table is related to one competition, so knowing the position is important. As the table can grow to have a lot of rows, I have paginate it (25 rows per page) using generic views, but the pr...
How to get enumerated results from a query in Django?
I have a query that orders a table according to a particular field. The table is related to one competition, so knowing the position is important. As the table can grow to have a lot of rows, I have paginate it (25 rows per page) using generic views, but the problem I've got is to present the numbered position on the t...
[ "If you're in your template, you can use something like:\n{{ forloop.counter0|add:page.start_index }}\n\nWhere start_index on pagination's page object gives you the 1-based starting index for that page. Of course, the other way around is probably more readable...\n{{ page.start_index|add:forloop.counter0 }}\n\n", ...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002236010_django_python.txt
Q: Position charts on Django I'm trying to do something similar to this, in Django. This is part of the page of Anna: Pos NickName Points --- --------- ------ 1 The best 1000 ... 35 Roger 550 36 Anna 545 37 Paul 540 It's a chart showing the scoring system, and it intends ...
Position charts on Django
I'm trying to do something similar to this, in Django. This is part of the page of Anna: Pos NickName Points --- --------- ------ 1 The best 1000 ... 35 Roger 550 36 Anna 545 37 Paul 540 It's a chart showing the scoring system, and it intends to show the first position, as ...
[ "Get the COUNT() of records that have a higher points.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002236181_django_python.txt
Q: Emulate floating point string conversion behaviour of Linux on Windows I've encountered an annoying problem in outputting a floating point number. When I format 11.545 with a precision of 2 decimal points on Windows it outputs "11.55", as I would expect. However, when I do the same on Linux the output is "11.54"! ...
Emulate floating point string conversion behaviour of Linux on Windows
I've encountered an annoying problem in outputting a floating point number. When I format 11.545 with a precision of 2 decimal points on Windows it outputs "11.55", as I would expect. However, when I do the same on Linux the output is "11.54"! I originally encountered the problem in Python, but further investigation sh...
[ "First of all it sounds like Windows has it wrong right in this case (not that this really matters). The C Standard requires that the value output by %.2f is rounded to the appropriate number of digits. The best known algorithm for this is dtoa implemented by David M. Gay. You can probably port this to Windows o...
[ 2, 2, 1, 0, 0, 0 ]
[]
[]
[ "c", "floating_point", "precision", "printf", "python" ]
stackoverflow_0002234303_c_floating_point_precision_printf_python.txt
Q: Problem deploying Django-Mingus with Flup and Cherokee. Strange admin behaviour I have a django-mingus blog running perfectly fine with the integrated development web server of django. It's installed in a virtualenv. Once deployed using the django app wizard of cherokee 0.99.42 the admin pannel is displaying a str...
Problem deploying Django-Mingus with Flup and Cherokee. Strange admin behaviour
I have a django-mingus blog running perfectly fine with the integrated development web server of django. It's installed in a virtualenv. Once deployed using the django app wizard of cherokee 0.99.42 the admin pannel is displaying a strange behaviour. Sometimes all apps are displayed in the admin pannel sometime only a ...
[ "I dropped all tables from the database, upgraded to last version of django-mingus after having deleted some dependencies to get them clean installed and I launched the scgi process using a shell script that activate the virtual environment before.\nNow everything seems to be stable.\n" ]
[ 0 ]
[]
[]
[ "cherokee", "django", "python", "scgi" ]
stackoverflow_0002175377_cherokee_django_python_scgi.txt
Q: Will Python use all processors in thread mode? While developing a Django app deployed on Apache mod_wsgi I found that in case of multithreading (Python threads; mod_wsgi processes=1 threads=8) Python won't use all available processors. With the multiprocessing approach (mod_wsgi processes=8 threads=1) all is fine ...
Will Python use all processors in thread mode?
While developing a Django app deployed on Apache mod_wsgi I found that in case of multithreading (Python threads; mod_wsgi processes=1 threads=8) Python won't use all available processors. With the multiprocessing approach (mod_wsgi processes=8 threads=1) all is fine and I can load my machine at full. So the question: ...
[ "Will Python use all processors in thread mode? No.\nPython won't use all available processors; is this Python behavior normal? Yes, it's normal because of the GIL.\nFor a discussion see http://mail.python.org/pipermail/python-3000/2007-May/007414.html.\nYou may find that having a couple (or 4) of threads per core...
[ 10, 4, 3, 1, 1 ]
[]
[]
[ "django", "multiprocessing", "multithreading", "performance", "python" ]
stackoverflow_0002236321_django_multiprocessing_multithreading_performance_python.txt
Q: PHP / cURL problem opening remote file We have a script which pulls some XML from a remote server. If this script is running on any server other than production, it works. Upload it to production however, and it fails. It is using cURL for the request but it doesn't matter how we do it - fopen, file_get_contents, ...
PHP / cURL problem opening remote file
We have a script which pulls some XML from a remote server. If this script is running on any server other than production, it works. Upload it to production however, and it fails. It is using cURL for the request but it doesn't matter how we do it - fopen, file_get_contents, sockets - it just times out. This also happe...
[ "Run Wireshark and see how far the request goes. Could be a firewall issue, a DNS resolution problem, among other things.\nAlso, try bumping your curl timeout to something much higher, like 300s, and see how it goes.\n" ]
[ 1 ]
[]
[]
[ "apache", "curl", "php", "python", "xml" ]
stackoverflow_0002236864_apache_curl_php_python_xml.txt
Q: Passing arguments to the generic views Django queryset I would like to make a queryset on a generic view in this way: category_info = { 'queryset' : ModelObject.objects.filter(category=category_id) } where the category_id will be stated on the URL (r'^category/(?P<category_id>\d+)$', 'object_list', categ...
Passing arguments to the generic views Django queryset
I would like to make a queryset on a generic view in this way: category_info = { 'queryset' : ModelObject.objects.filter(category=category_id) } where the category_id will be stated on the URL (r'^category/(?P<category_id>\d+)$', 'object_list', category_info ) But I don't know how to take the data from the U...
[ "You'll have to define your own view and return the generic view from within:\nurls.py:\n(r'^category/(?P<category_id>\\d+)$', 'myapp.views.category_list')\n\nmyapp/views.py\nfrom django.views.generic.list_detail import object_list\ndef category_list(request, category_id):\n queryset = ModelObject.objects.filter...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002236886_django_python.txt
Q: How can I write to the textfile with "while"? while 1: text_file = open("write_it.txt", "w") word = input("Please add to a text file: ") What else do I need to add to make my code run properly? A: This should work: text_file = open("write_it.txt", "w") while 1: word = input("Please add to a text fil...
How can I write to the textfile with "while"?
while 1: text_file = open("write_it.txt", "w") word = input("Please add to a text file: ") What else do I need to add to make my code run properly?
[ "This should work:\ntext_file = open(\"write_it.txt\", \"w\")\nwhile 1:\n word = input(\"Please add to a text file: \")\n if not word:\n break\n text_file.write(word)\ntext_file.close()\n\n", "Not sure, but that open statement inside of the while couldn't be affecting its behaviour?\nHave you trie...
[ 3, 0 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0002237154_file_io_python.txt
Q: Easiest way to display a pdf, ps or dvi file from python in linux I have created an application with python and wxpython. I would like to display a help file in pdf, ps or dvi format in GNU/Linux. Could use the distribution pdf viewer, but not so easy when you don't know which they have. Any ideas on how to solve ...
Easiest way to display a pdf, ps or dvi file from python in linux
I have created an application with python and wxpython. I would like to display a help file in pdf, ps or dvi format in GNU/Linux. Could use the distribution pdf viewer, but not so easy when you don't know which they have. Any ideas on how to solve this?
[ "Invoke xdg-open against the file.\n", "Try also evince.\n" ]
[ 4, 1 ]
[]
[]
[ "linux", "pdf", "python", "wxpython" ]
stackoverflow_0002235090_linux_pdf_python_wxpython.txt
Q: Use Python logging to determine where a method was called from I'm trying to debug a Python Django app. I've got additional fields being added to a model. I've tracked this down to one method: django.db.models.options.add_field() The only place this method is called is: django.db.models.fields.init.contribute_to_...
Use Python logging to determine where a method was called from
I'm trying to debug a Python Django app. I've got additional fields being added to a model. I've tracked this down to one method: django.db.models.options.add_field() The only place this method is called is: django.db.models.fields.init.contribute_to_class() def contribute_to_class(self, cls, name): self.set_attri...
[ "Use traceback module.\n" ]
[ 1 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002237355_django_logging_python.txt
Q: Using sub filters/queries in Google App Engine I'm trying to use figure out how to sub query a query that uses a filter. From what I've figured out so far while using .filter() it changes the original query, that leads to a second .filter() would also have to match the first filter. I would like to make something ...
Using sub filters/queries in Google App Engine
I'm trying to use figure out how to sub query a query that uses a filter. From what I've figured out so far while using .filter() it changes the original query, that leads to a second .filter() would also have to match the first filter. I would like to make something like this: modules = data.Modules.all().filter('page...
[ "It appears that what you're trying to do is an OR query, which isn't supported in App Engine. You can use an IN query, which simulates this by doing multiple queries for you.\nThe reason the first thing you tried doesn't work is that you're trying to filter your query so that your results match both \"Test\" and ...
[ 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002237224_google_app_engine_python.txt
Q: How can I record live video with gstreamer without dropping frames? I'm trying to use gstreamer 0.10 from Python to simultaneously display a v4l2 video source and record it to xvid-in-avi. Over a long period of time the computer would be fast enough to do this but if another program uses the disk it drops frames. ...
How can I record live video with gstreamer without dropping frames?
I'm trying to use gstreamer 0.10 from Python to simultaneously display a v4l2 video source and record it to xvid-in-avi. Over a long period of time the computer would be fast enough to do this but if another program uses the disk it drops frames. That's bad enough, but on playback there are bursts of movement in the vi...
[ "tee will block if either output blocks, so it's probably your bottleneck. I suggest to write the stream that takes longer to encode to disk and encode from there.\n", "and you need to write xvimagesink, not xvimagesync\n" ]
[ 5, 2 ]
[]
[]
[ "gstreamer", "linux", "python" ]
stackoverflow_0000677641_gstreamer_linux_python.txt
Q: TDD - beginner problems and stumbling blocks While I've written unit tests for most of the code I've done, I only recently got my hands on a copy of TDD by example by Kent Beck. I have always regretted certain design decisions I made since they prevented the application from being 'testable'. I read through the bo...
TDD - beginner problems and stumbling blocks
While I've written unit tests for most of the code I've done, I only recently got my hands on a copy of TDD by example by Kent Beck. I have always regretted certain design decisions I made since they prevented the application from being 'testable'. I read through the book and while some of it looks alien, I felt that I...
[ "As a preliminary comment, TDD takes practice. When I look back at the tests I wrote when I began TDD, I see lots of issues, just like when I look at code I wrote a few year ago. Keep doing it, and just like you begin to recognize good code from bad, the same things will happen with your tests - with patience. \n\...
[ 10, 8, 3, 2, 1, 1, 1 ]
[]
[]
[ "python", "tdd", "testdrivendesign" ]
stackoverflow_0002066593_python_tdd_testdrivendesign.txt
Q: Subtract two dates to give a timedelta I'm trying to get a value from one of my database values, which will be given by subtracting the purchase date from today's date. I've written my code this way: delta = datetime.now() - item.purchase_date But this gives me this error: unsupported operand type(s) for -: 'dat...
Subtract two dates to give a timedelta
I'm trying to get a value from one of my database values, which will be given by subtracting the purchase date from today's date. I've written my code this way: delta = datetime.now() - item.purchase_date But this gives me this error: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date' If I us...
[ "you need to use date.today or datetime.now().date() instead of datetime.now:\n>>> import datetime\n>>> datetime.date.today()\ndatetime.date(2010, 2, 10)\n>>> datetime.datetime.now().date()\ndatetime.date(2010, 2, 10)\n\n" ]
[ 20 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002238008_datetime_python.txt
Q: Applying a decorator to every method in a class? I have decorator @login_testuser applied to method test_1(): class TestCase(object): @login_testuser def test_1(self): print "test_1()" Is there a way I can apply @login_testuser on every method of the class prefixed with "test_"? In other words, th...
Applying a decorator to every method in a class?
I have decorator @login_testuser applied to method test_1(): class TestCase(object): @login_testuser def test_1(self): print "test_1()" Is there a way I can apply @login_testuser on every method of the class prefixed with "test_"? In other words, the decorator would apply to test_1(), test_2() methods...
[ "In Python 2.6, a class decorator is definitely the way to go. e.g., here's a pretty general one for these kind of tasks:\nimport inspect\n\ndef decallmethods(decorator, prefix='test_'):\n def dectheclass(cls):\n for name, m in inspect.getmembers(cls, inspect.isfunction):\n if name.startswith(...
[ 26, 5, 2, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0002237624_decorator_python.txt
Q: AttributeError in tkinter gui programming I want to display my calculated output in a Gui window in python. I am trying with Tkinter. But I'm having problems displaying the output on Tkinter level widget. I am putting input data as address information in text field of Tkinter window and want latitude, longitude of...
AttributeError in tkinter gui programming
I want to display my calculated output in a Gui window in python. I am trying with Tkinter. But I'm having problems displaying the output on Tkinter level widget. I am putting input data as address information in text field of Tkinter window and want latitude, longitude of that inputed address to the text label. Can an...
[ "On line 94 in F:\\JavaWorkspace\\Test\\src\\gui_geo_location.py, you're using self.entryVariable but that object does not have an entryVariable attribute.\nBased on your __init__, it seems you haven't defined entryVariable anywhere. Try adding:\nself.entryVariable = Tkinter.StringVar()\n\nto your __init__ method. ...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0002237700_python_tkinter.txt
Q: What is the pythonic way to unpack tuples? This is ugly. What's a more Pythonic way to do it? import datetime t= (2010, 10, 2, 11, 4, 0, 2, 41, 0) dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6]) A: Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seem...
What is the pythonic way to unpack tuples?
This is ugly. What's a more Pythonic way to do it? import datetime t= (2010, 10, 2, 11, 4, 0, 2, 41, 0) dt = datetime.datetime(t[0], t[1], t[2], t[3], t[4], t[5], t[6])
[ "Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:\nt = (2010, 10, 2, 11, 4, 0, 2, 41, 0)\ndt = datetime.datetime(*t[0:7])\n\nThis is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another...
[ 155, 15 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0002238355_python_tuples.txt
Q: How do I properly work with unicode characters in python to keep from getting errors? I'm working on a python plugin for Google Quick Search Box, and it's doing some odd things with non-ascii characters. It seems like the code works fine up until I try constructing a string containing the non-ascii characters (ü h...
How do I properly work with unicode characters in python to keep from getting errors?
I'm working on a python plugin for Google Quick Search Box, and it's doing some odd things with non-ascii characters. It seems like the code works fine up until I try constructing a string containing the non-ascii characters (ü has been my test character). I am using the following code snippet for the construction, wit...
[ "There are a few things you should do to fix this.\n\nConvert all string literal that contain non-ASCII characters to Unicode literals. Example: u'über'.\nDo intermediate processing on Unicode. In other words, if you receive an encoded string (no matter the encoding), decode it to Unicode before working on it. Exam...
[ 4, 1, 0 ]
[]
[]
[ "ascii", "encoding", "python", "unicode" ]
stackoverflow_0002239017_ascii_encoding_python_unicode.txt
Q: Python: simple CLI GUI A simple question on a python module. Let's say I have the following code: for i in range(1000): print i It'll output something along the lines of: 1 2 'Snip' 999 Is it possible to have the program output all the numbers on the same line? I'm not talking about "1, 2, 3 .." rather I want...
Python: simple CLI GUI
A simple question on a python module. Let's say I have the following code: for i in range(1000): print i It'll output something along the lines of: 1 2 'Snip' 999 Is it possible to have the program output all the numbers on the same line? I'm not talking about "1, 2, 3 .." rather I want the line value to change to...
[ "If you want to draw a GUI inside a terminal, you'll have to use the curses module.\n", "If you want the character to be overwritten/replaced each time, you may need to use a terminal control library like 'curses'. Here's a Python how-to article to get you started.\n", "For a simple case the following code work...
[ 3, 3, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002239476_python.txt
Q: Python win32com: Internet Explorer COM object ? (used to work?) I have this very simple program: from win32com import client ie=client.Dispatch("InternetExplorer.Application") This used to work (I think I broke something when I re-used 'makepy.py' to try and add in constants for IE). It still works on another mac...
Python win32com: Internet Explorer COM object ? (used to work?)
I have this very simple program: from win32com import client ie=client.Dispatch("InternetExplorer.Application") This used to work (I think I broke something when I re-used 'makepy.py' to try and add in constants for IE). It still works on another machine where I haven't been so slap-dash with 'makepy.py'. Here's what ...
[ "Went into here:\nPython26\\Lib\\site-packages\\win32com\\gen_py\n\nRenamed the .py and .pyc file to .py_ and .pyc_ files :\n85CC894D-5673-4868-9A22-9E15B7E694D3x0x1x1.pyc\n\nRestarted Python: now get the Internet Explorer. phew...\n" ]
[ 1 ]
[]
[]
[ "automation", "com", "internet_explorer", "python", "winapi" ]
stackoverflow_0002239199_automation_com_internet_explorer_python_winapi.txt
Q: Is it better to use "is" or "==" for number comparison in Python? Is it better to use the "is" operator or the "==" operator to compare two numbers in Python? Examples: >>> a = 1 >>> a is 1 True >>> a == 1 True >>> a is 0 False >>> a == 0 False A: Use ==. Sometimes, on some python implementations, by coincidenc...
Is it better to use "is" or "==" for number comparison in Python?
Is it better to use the "is" operator or the "==" operator to compare two numbers in Python? Examples: >>> a = 1 >>> a is 1 True >>> a == 1 True >>> a is 0 False >>> a == 0 False
[ "Use ==. \nSometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.\n", "Others have answered your question, but I'll go into a little bit more detail:\nPython's is compares id...
[ 118, 33, 20, 8, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002239737_python.txt
Q: Python equiv. of PHP foreach []? I am fetching rows from the database and wish to populate a multi-dimensional dictionary. The php version would be roughly this: foreach($query as $rows): $values[$rows->id][] = $rows->name; endforeach; return $values; I can't seem to find out the following issues: What is t...
Python equiv. of PHP foreach []?
I am fetching rows from the database and wish to populate a multi-dimensional dictionary. The php version would be roughly this: foreach($query as $rows): $values[$rows->id][] = $rows->name; endforeach; return $values; I can't seem to find out the following issues: What is the python way to add keys to a diction...
[ "values = collections.defaultdict(list)\nfor rows in query:\n values[rows.id].append(rows.name)\nreturn values\n\n", "Just a general note:\n\nPython's dictionaries are mappings without order, while adding numerical keys would allow \"sequential\" access, in case of iteration there's no guarantee that order will ...
[ 8, 4, 2, 1 ]
[]
[]
[ "dictionary", "key", "python" ]
stackoverflow_0002239771_dictionary_key_python.txt
Q: How to set file/directory ownership/permissions in a Samba share on Windows using Python/.NET? I need to create directories and files in a Samba share on Windows, from a Python script. I can (and do) also use .NET 3.5 from Python. I would like to create these directories and files with certain owners and permissio...
How to set file/directory ownership/permissions in a Samba share on Windows using Python/.NET?
I need to create directories and files in a Samba share on Windows, from a Python script. I can (and do) also use .NET 3.5 from Python. I would like to create these directories and files with certain owners and permissions. Can I achieve this somehow?
[ "You can use CACLS.exe to display or modify Access Control Lists (ACLs) for files and folders. You can call this from Python with something like:\nresult = os.popen(\"cacls \" + '\"' + theDirPath + '\"')\nThere is a good example of a Python script which sets up permissions here \n" ]
[ 0 ]
[]
[]
[ ".net", "python", "samba", "windows" ]
stackoverflow_0002239762_.net_python_samba_windows.txt
Q: Does anyone know of a Urwid like environment that is cross-platform for Python 3.x? I would like it to run on Linux, OS X, and Windows (XP/Vista/7). Thanks for any input. A: Your best bet is probably to use 2to3 to convert Urwid itself. A: I believe you're out of luck until Urwid itself is ported to Python 3 (...
Does anyone know of a Urwid like environment that is cross-platform for Python 3.x?
I would like it to run on Linux, OS X, and Windows (XP/Vista/7). Thanks for any input.
[ "Your best bet is probably to use 2to3 to convert Urwid itself.\n", "I believe you're out of luck until Urwid itself is ported to Python 3 (and according to this post from last month, \"the real work to port to python 3 hasn't \nstarted yet\").\n", "Help port Urwid to Python 3! That is most likely more work tha...
[ 2, 2, 0 ]
[]
[]
[ "cross_platform", "python", "python_3.x" ]
stackoverflow_0002226913_cross_platform_python_python_3.x.txt
Q: simple auth system in django failing I'm writing a simple auth system to login (and logout) users. The username is an email address, which looks up an email field. I'm using: user = User.objects.get(email__exact=email) # if user obj exists if user: # if authenticate if authenticate(user, email, password): ...
simple auth system in django failing
I'm writing a simple auth system to login (and logout) users. The username is an email address, which looks up an email field. I'm using: user = User.objects.get(email__exact=email) # if user obj exists if user: # if authenticate if authenticate(user, email, password): # create session request.s...
[ "Use filter() instead of get().\n", "I think this is probably more what you want:\ntry:\n user = User.objects.get(email__exact=email)\n if authenticate(user, email, password):\n request.session['user'] = user\n return HttpResponseRedirect('/home/')\n else:\n return HttpResponseRedire...
[ 2, 1 ]
[]
[]
[ "authentication", "django", "python" ]
stackoverflow_0002238594_authentication_django_python.txt
Q: Does the Python "open" function save its content in memory or in a temp file? For the following Python code: fp = open('output.txt', 'wb') # Very big file, writes a lot of lines, n is a very large number for i in range(1, n): fp.write('something' * n) fp.close() The writing process above can last more than 30...
Does the Python "open" function save its content in memory or in a temp file?
For the following Python code: fp = open('output.txt', 'wb') # Very big file, writes a lot of lines, n is a very large number for i in range(1, n): fp.write('something' * n) fp.close() The writing process above can last more than 30 min. Sometimes I get the error MemoryError. Is the content of the file before clos...
[ "It's stored in the operating system's disk cache in memory until it is flushed to disk, either implicitly due to timing or space issues, or explicitly via fp.flush().\n", "There will be write buffering in the Linux kernel, but at (ir)regular intervals they will be flushed to disk. Running out of such buffer spac...
[ 5, 3, 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002239888_python.txt