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: Should I use a metaclass, class decorator, or override the __new__ method? Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass...
Should I use a metaclass, class decorator, or override the __new__ method?
Here is my problem. I want the following class to have a bunch of property attributes. I could either write them all out like foo and bar, or based on some other examples I've seen, it looks like I could use a class decorator, a metaclass, or override the __new__ method to set the properties automagically. I'm just ...
[ "Magic is bad. It makes your code harder to understand and maintain. You virtually never need metaclasses or __new__. \nIt looks like your use case could be implemented with pretty straightforward code (with only a small hint of magic):\nclass Test(object):\n def calculate_attr(self, attr):\n return somet...
[ 5, 3, 1 ]
[]
[]
[ "inheritance", "metaclass", "python" ]
stackoverflow_0002503676_inheritance_metaclass_python.txt
Q: Keeping track of changes - Django I have various models of which I would like to keep track and collect statistical data. The problem is how to store the changes throughout time. I thought of various alternative: Storing a log in a TextField, open it and update it every time the model is saved. Alternatively pick...
Keeping track of changes - Django
I have various models of which I would like to keep track and collect statistical data. The problem is how to store the changes throughout time. I thought of various alternative: Storing a log in a TextField, open it and update it every time the model is saved. Alternatively pickle a list and store it in a TextField. ...
[ "Don't reinvent the wheel.. Use django-reversion for logging changes.\nI'd break statistics off into a separate model though.\n", "Quoth my elementary chemistry teacher: \"If you don't write it down, it didn't happen\", therefore save logs in a file.\nSince the log information is disjoint from your application da...
[ 6, 1, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002504386_django_django_models_python.txt
Q: wx Menu disappears from frame when shown as a popup I'm trying to create a wx.Menu that will be shared between a popup (called on right-click), and a sub menu accessible from the frame menubar. The following code demonstrates the problem. If you open the "MENU>submenu" from the menubar the item "asdf" is visibl...
wx Menu disappears from frame when shown as a popup
I'm trying to create a wx.Menu that will be shared between a popup (called on right-click), and a sub menu accessible from the frame menubar. The following code demonstrates the problem. If you open the "MENU>submenu" from the menubar the item "asdf" is visible. If you right click on the frame content area, "asdf" ...
[ "I would make a function, create_menu, that creates and returns a wx.Menu object. Call it once to add it to your menu bar and call it in show_popup. So you're using separate Menu objects. Don't worry about creating them on each right-click, it's not a big deal.\n" ]
[ 1 ]
[]
[]
[ "menu", "python", "wxpython" ]
stackoverflow_0002504962_menu_python_wxpython.txt
Q: Yahoo BOSS Python Library, ExpatError I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 & 4 give Expat errors. Here is the output from ex3.py: gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a rese...
Yahoo BOSS Python Library, ExpatError
I tried to install the Yahoo BOSS mashup framework, but am having trouble running the examples provided. Examples 1, 2, 5, and 6 work, but 3 & 4 give Expat errors. Here is the output from ex3.py: gpython examples/ex3.py examples/ex3.py:33: Warning: 'as' will become a reserved keyword in Python 2.6 Traceback (most ...
[ "The problem is the digg search string. It should be \"s=\". Not \"search=\"\n", "I believe that must be an error in the example: it's getting a JSON result (indeed if you copy and paste that URL in your browser, you'll download a file names search.json which starts with \n{\"results\":[{\"profile_image_url\":\n\...
[ 1, 0 ]
[]
[]
[ "expat_parser", "python", "yahoo_boss_api" ]
stackoverflow_0001421099_expat_parser_python_yahoo_boss_api.txt
Q: Splitting a list in python Hey im new to python. How do you get a portion of a list by the relative value of its sorting key. example... list = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10] list.sort() newList = list.split("all numbers that are over 13") assert newList == [14,15,16] A: >>> l = [11,12,13,14,15,16,1,2...
Splitting a list in python
Hey im new to python. How do you get a portion of a list by the relative value of its sorting key. example... list = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10] list.sort() newList = list.split("all numbers that are over 13") assert newList == [14,15,16]
[ ">>> l = [11,12,13,14,15,16,1,2,3,4,5,6,7,8,9,10]\n>>> sorted(x for x in l if x > 13)\n[14, 15, 16]\n\nor with filter (would be a little bit slower if you have big list, because of lambda)\n>>> sorted(filter(lambda x: x > 13, l))\n[14, 15, 16]\n\n", "Use [item for item in newList if item > 13].\nThere is a decent...
[ 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0002505251_python.txt
Q: s/mime v3 with M2Crypto I would like to send a mail with a s/mime v3 attachment through SMTP. The excellent HOWTO below describes the procedure in detail for s/mime v2. http://sandbox.rulemaker.net/ngps/m2/howto.smime.html I would greatly appreciate any help in doing the same for s/mime v3. Arye. A: I don't know...
s/mime v3 with M2Crypto
I would like to send a mail with a s/mime v3 attachment through SMTP. The excellent HOWTO below describes the procedure in detail for s/mime v2. http://sandbox.rulemaker.net/ngps/m2/howto.smime.html I would greatly appreciate any help in doing the same for s/mime v3. Arye.
[ "I don't know about v3, but some updated info...\nThe new location for that howto is at http://svn.osafoundation.org/m2crypto/trunk/doc/howto.smime.html. Note that it is still for v2. There are also some smime tests at http://svn.osafoundation.org/m2crypto/trunk/tests/test_smime.py\n" ]
[ 2 ]
[]
[]
[ "m2crypto", "python", "smime" ]
stackoverflow_0002469271_m2crypto_python_smime.txt
Q: Open Source CMS with linked sub-sections and users I work at a small college that wants to make "sites" for all of the academic departments (~30). I managed to talk them out of their original idea: 30 individual Wordpress installations. What a maintenance nightmare! What I'm looking for is a CMS (preferably Pytho...
Open Source CMS with linked sub-sections and users
I work at a small college that wants to make "sites" for all of the academic departments (~30). I managed to talk them out of their original idea: 30 individual Wordpress installations. What a maintenance nightmare! What I'm looking for is a CMS (preferably Python or PHP, as those are my areas of expertise) that can a...
[ "Take a look at Drupal or Wordpress MU. With a little bit of scripting and code I think these could do what you need.\nTake a close look at Wordpress MU especially. If they were talking about 30 Wordpress installations then Wordpress MU might be exactly what you want. It provides a unified administration backend...
[ 2, 0, 0 ]
[]
[]
[ "content_management_system", "open_source", "php", "python" ]
stackoverflow_0002455091_content_management_system_open_source_php_python.txt
Q: WxPython, popup menus, callbacks and Windows XP My goal: the user clicks a button. From the button pops up a two-level menu. The user clicks on something, and this triggers a callback which does stuff. Here is a minimal example: import wx class MyApp(wx.App): def OnInit(self): frame = TestFrame(None...
WxPython, popup menus, callbacks and Windows XP
My goal: the user clicks a button. From the button pops up a two-level menu. The user clicks on something, and this triggers a callback which does stuff. Here is a minimal example: import wx class MyApp(wx.App): def OnInit(self): frame = TestFrame(None, -1, "Hello from wxPython") frame.Show(True)...
[ "You are handling ID generation yourself and in doing that mixing up IDs, anyway you do not need to generate IDs yourself use wx.NewId(), if you replace next_id with that it will work\ne.g.\nmit = wx.MenuItem(submenu, id=wx.NewId(), text=item)\n\n" ]
[ 2 ]
[]
[]
[ "python", "windows_xp", "wxpython" ]
stackoverflow_0002504094_python_windows_xp_wxpython.txt
Q: Hooking up Sproutcore frontend and custom Python backend I am building a web-based application. The frontend has been designed in Sproutcore. For the backend, we have our own python API which handles all transactions with multiple databases. What is the best way to hook up the front-end with the back-end. AFAIK d...
Hooking up Sproutcore frontend and custom Python backend
I am building a web-based application. The frontend has been designed in Sproutcore. For the backend, we have our own python API which handles all transactions with multiple databases. What is the best way to hook up the front-end with the back-end. AFAIK django is pretty monolithic (correct me if i am wrong) and it w...
[ "The only thing I know about sproutcore is what I read about 10 seconds ago to answer this. Javascript can do ajax so I assume so can sproutcore. So providing a restful api+json to your backend would be an option. If you need to sell it to your boss, call it a service oriented architecture. You'll probably have it ...
[ 2, 2 ]
[]
[]
[ "django", "django_models", "python", "sproutcore" ]
stackoverflow_0002504772_django_django_models_python_sproutcore.txt
Q: How do I do multiple processes for Django, on my WSGI apache? My friend says that Django only has 1 thread or something? And I have to edit my 000-default in order to add more processes? He suggests 4 or 5. What exactly is this, and what do I have to do? Thanks, I'm a noob. A: Use the WSGIDaemonProcess directiv...
How do I do multiple processes for Django, on my WSGI apache?
My friend says that Django only has 1 thread or something? And I have to edit my 000-default in order to add more processes? He suggests 4 or 5. What exactly is this, and what do I have to do? Thanks, I'm a noob.
[ "Use the WSGIDaemonProcess directive to put the app in daemon mode and specify the number of daemon processes and threads.\n" ]
[ 3 ]
[]
[]
[ "apache", "django", "linux", "python", "unix" ]
stackoverflow_0002505541_apache_django_linux_python_unix.txt
Q: Backup of folder + database - Python I feel like this is quite delicate, I have various folders whith projects I would like to backup into a zip/tar file, but would like to avoid backing up files such as pyc files and temporary files. I also have a Postgres db I need to backup. Any tips for running this operatio...
Backup of folder + database - Python
I feel like this is quite delicate, I have various folders whith projects I would like to backup into a zip/tar file, but would like to avoid backing up files such as pyc files and temporary files. I also have a Postgres db I need to backup. Any tips for running this operation as a python script? Also, would there be...
[ "If you're on Linux (or any other form of Unix, such as MacOSX), a simple way to reduce a process's priority -- and therefore, indirectly, its consumption of CPU if other processes want some -- is the nice command. In Python (same OSs), os.nice lets your program \"make itself nicer\" (reduce priority &c).\nFor bac...
[ 4, 2, 1, 1 ]
[]
[]
[ "archiving", "backup", "bash", "postgresql", "python" ]
stackoverflow_0002504907_archiving_backup_bash_postgresql_python.txt
Q: BioPython: extracting sequence IDs from a Blast output file I have a BLAST output file in XML format. It is 22 query sequences with 50 hits reported from each sequence. And I want to extract all the 50x22 hits. This is the code I currently have, but it only extracts the 50 hits from the first query. from Bio.Blas...
BioPython: extracting sequence IDs from a Blast output file
I have a BLAST output file in XML format. It is 22 query sequences with 50 hits reported from each sequence. And I want to extract all the 50x22 hits. This is the code I currently have, but it only extracts the 50 hits from the first query. from Bio.Blast import NCBIXM blast_records = NCBIXML.parse(result_handle) blas...
[ "This should get all records. The novelty compared with the original is the\nfor blast_record in blast_records\n\nwhich is a python idiom to iterate through items in a \"list-like\" object, such as the blast_records (checking the CBIXML module documentation showed that parse() indeed returns an iterator)\nfrom Bio...
[ 3, 2 ]
[]
[]
[ "biopython", "python", "xml_parsing", "xmlblaster" ]
stackoverflow_0001684470_biopython_python_xml_parsing_xmlblaster.txt
Q: sqlite3 'database is locked' won't go away with retries I have a sqlite3 database that is accessed by a few threads (3-4). I am aware of the general limitations of sqlite3 with regards to concurrency as stated http://www.sqlite.org/faq.html#q6 , but I am convinced that is not the problem. All of the threads both r...
sqlite3 'database is locked' won't go away with retries
I have a sqlite3 database that is accessed by a few threads (3-4). I am aware of the general limitations of sqlite3 with regards to concurrency as stated http://www.sqlite.org/faq.html#q6 , but I am convinced that is not the problem. All of the threads both read and write from this database. Whenever I do a write, I ha...
[ "Sqlite locks the entire database every time you try to write to the database. Is there any chance one of your threads is constantly writing? Is only one thread hitting the Database lock or all buy one of them?\n", "Here is a not-so-elegant temporary fix: using an external exclusive lock around the writes rather ...
[ 0, 0, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0002051243_python_sqlite.txt
Q: A business Case for Enterprise Python This will not be a "programming" question but more technology / platform related question. I'm trying to figure out whether Python can be a suitable Java alternative for enterprise / web applications. Which are the ideal cases where you would prefer to use Python instead of J...
A business Case for Enterprise Python
This will not be a "programming" question but more technology / platform related question. I'm trying to figure out whether Python can be a suitable Java alternative for enterprise / web applications. Which are the ideal cases where you would prefer to use Python instead of Java? How would a typical Python web applica...
[ "An enterprise that already has a terabucks of Java investments should add jython to their mix of technologies -- it can be adopted gradually and progressively, at first for ancillary functions such as testing, \"one-off\" data migrations &c, prototyping of new functionality, cases in which using some existing open...
[ 14, 4, 1, 1, 0 ]
[]
[]
[ "enterprise", "python" ]
stackoverflow_0001879113_enterprise_python.txt
Q: ways to execute python So far to execute a Python program, I'm using > python file.py I want to run the Python script simply using file name, like > file.py similar to shell scripts like > sh file.sh > chmod +x file.sh > ./file.sh or move file.sh to bin and then run > file.sh A: Put this at the top of your...
ways to execute python
So far to execute a Python program, I'm using > python file.py I want to run the Python script simply using file name, like > file.py similar to shell scripts like > sh file.sh > chmod +x file.sh > ./file.sh or move file.sh to bin and then run > file.sh
[ "Put this at the top of your Python script:\n#!/usr/bin/env python\n\nThe #! part is called a shebang, and the env command will simply locate python on your $PATH and execute the script through it. You could hard-code the path to the python interpreter, too, but calling /usr/bin/env is a little more flexible. (Fo...
[ 17, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002506437_python.txt
Q: Bash or python for changing spacing in files I have a set of 10000 files. In all of them, the second line, looks like: AAA 3.429 3.84 so there is just one space (requirement) between AAA and the two other columns. The rest of lines on each file are completely different and correspond to 10 columns of numbers. Ran...
Bash or python for changing spacing in files
I have a set of 10000 files. In all of them, the second line, looks like: AAA 3.429 3.84 so there is just one space (requirement) between AAA and the two other columns. The rest of lines on each file are completely different and correspond to 10 columns of numbers. Randomly, in around 20% of the files, and due to some...
[ "Performing line-based changes to text files is often simplest to do in sed.\nsed -e '2s/ */ /g' infile.txt\n\nwill replace any runs of multiple spaces with a single space. This may be changing more than you want, though.\nsed -e '2s/^\\([^ ]*\\) /\\1 /' infile.txt\n\nshould just replace instances of two spaces ...
[ 8, 6, 4, 2, 2, 1, 1, 1, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0002500358_bash_python.txt
Q: SWIG: Python list to uint32_t *? I'm trying to work with a Python module that was generated by SWIG. There's a C++ class defined that works like this (simplified): namespace Foo { class Thing { public: Thing(); ~Thing(); bool DoSomething(uint32_t x, uint32_t y, uint32_t z, uin...
SWIG: Python list to uint32_t *?
I'm trying to work with a Python module that was generated by SWIG. There's a C++ class defined that works like this (simplified): namespace Foo { class Thing { public: Thing(); ~Thing(); bool DoSomething(uint32_t x, uint32_t y, uint32_t z, uint32_t *buffer); }; }; When I try ...
[ "The last parameter to DoSomething is a pointer to uint32_t, not uint32_t. So unlike the other parameters, the function expects to receive a pointer to an integer or an array of integers (since arrays can be used wherever pointers are expected).\nI suspect in this case (because it's called 'buffer') that the funct...
[ 2 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0002503592_c++_python_swig.txt
Q: Python and .exe files, another way How to build exe files from py files (compatible with win32)? please don't refer to py2exe. that is blocked service in IRI. for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge? A: Pick up a mirr...
Python and .exe files, another way
How to build exe files from py files (compatible with win32)? please don't refer to py2exe. that is blocked service in IRI. for Iranians only: do you know how to download something (like py2exe) from blocked sites? especially from sourceforge ande fontforge?
[ "Pick up a mirror like this \nhttp://git.kitsu.ru/mirrors/py2exe.git\nand download it with git clone, and compile it by running setup.py after that.\n", "How about PyInstaller (link to preliminary python 2.6 on Windows bin)?\n", "Legal issues aside, blocked sites can be accessed (and downloaded from) using any ...
[ 4, 3, 1, 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0002506857_py2exe_python.txt
Q: String searching algorithm for Chinese characters There is Python code available for normal string searching algorithms, such as Boyer-Moore. I am looking to use this on Chinese characters, but it doesn't seem like the same implementation would work. What would I do in order to make the algorithm work with Chinese...
String searching algorithm for Chinese characters
There is Python code available for normal string searching algorithms, such as Boyer-Moore. I am looking to use this on Chinese characters, but it doesn't seem like the same implementation would work. What would I do in order to make the algorithm work with Chinese characters? I am referring to this: http://en.literate...
[ "As long as all your text is in unicodes it should work just fine. The algorithm looks sequence-independent, provided each \"element\" is one sequence-unit in length.\n" ]
[ 3 ]
[]
[]
[ "cjk", "python", "string_search", "unicode" ]
stackoverflow_0002506970_cjk_python_string_search_unicode.txt
Q: Having trouble scraping an ASP .NET web page I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup: conn = Http() # do a get first to retrieve important values page = conn.request(u"http://somepage.co...
Having trouble scraping an ASP .NET web page
I am trying to scrape an ASP.NET website but am having trouble getting the results from a post. I have the following python code and am using httplib2 and BeautifulSoup: conn = Http() # do a get first to retrieve important values page = conn.request(u"http://somepage.com/Search.aspx", "GET") #event_validation and view...
[ "This isn't technically an answer, but you could use Fiddler to examine the difference between what you are sending with your python code, versus what would be sent if you used a web browser to do the post.\nI find that usually helps in these types of situations.\n", "Well, You need to see first what you have wri...
[ 2, 0 ]
[]
[]
[ "asp.net", "python" ]
stackoverflow_0002507280_asp.net_python.txt
Q: Use BeautifulSoup to extract sibling nodes between two nodes I've got a document like this: <p class="top">I don't want this</p> <p>I want this</p> <table> <!-- ... --> </table> <img ... /> <p> and all that stuff too</p> <p class="end>But not this and nothing after it</p> I want to extract everything betwe...
Use BeautifulSoup to extract sibling nodes between two nodes
I've got a document like this: <p class="top">I don't want this</p> <p>I want this</p> <table> <!-- ... --> </table> <img ... /> <p> and all that stuff too</p> <p class="end>But not this and nothing after it</p> I want to extract everything between the p[class=top] and p[class=end] paragraphs. Is there a nice ...
[ "node.nextSibling attribute is your solution:\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(html)\n\nnextNode = soup.find('p', {'class': 'top'})\nwhile True:\n # process\n nextNode = nextNode.nextSibling\n if getattr(nextNode, 'name', None) == 'p' and nextNode.get('class', None) == 'end...
[ 8 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0002507301_beautifulsoup_python.txt
Q: Detecting Infinite recursion in Python or dynamic languages Recently I tried compiling program something like this with GCC: int f(int i){ if(i<0){ return 0;} return f(i-1); f(100000); and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just...
Detecting Infinite recursion in Python or dynamic languages
Recently I tried compiling program something like this with GCC: int f(int i){ if(i<0){ return 0;} return f(i-1); f(100000); and it ran just fine. When I inspected the stack frames the compiler optimized the program to use only one frame, by just jumping back to the beginning of the function and only replacing...
[ "The optimisation you're talking about is known as tail call elimination - a recursive call is unfolded into an iterative loop.\nThere has been some discussion of this, but the current situation is that this will not be added, at least to cpython proper. See Guido's blog entry for some discussion.\nHowever, there ...
[ 12, 6, 4 ]
[]
[]
[ "compiler_construction", "gcc", "python" ]
stackoverflow_0002507395_compiler_construction_gcc_python.txt
Q: C++ Arrays manipulations (python-like operations) I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this: values = numpy.array(inp.data) idx1 = numpy.where(values > -2.14) idx2 = numpy.where(values < 2.0) res1 = (values[i...
C++ Arrays manipulations (python-like operations)
I'm trying to figure out the best C++ library/package for array manipulations in a manner of python. Basically I need a simplicity like this: values = numpy.array(inp.data) idx1 = numpy.where(values > -2.14) idx2 = numpy.where(values < 2.0) res1 = (values[idx1] - diff1)/1000 res2 = (values[idx2] - diff2)*1000 ...
[ "You should not be using arrays at all. Please sit down and learn about the std::vector class and about iterators and Standard Library algorithms. I strongly suggest reading the book The C++ Standard Library.\n", "You can achieve something similar in C++ but you shouldn't use plain C arrays for it.\nThe easiest w...
[ 5, 5, 4, 1, 1 ]
[]
[]
[ "arrays", "c++", "python" ]
stackoverflow_0002507422_arrays_c++_python.txt
Q: Scripting in Java Me and some friends are writing a MORPG in Java, and we would like to use a scripting language to, eg. to create quests. We have non experience with scripting in Java. We have used Python, but we are very inexperienced with it. One of us also have used Javascript. What scripting language should ...
Scripting in Java
Me and some friends are writing a MORPG in Java, and we would like to use a scripting language to, eg. to create quests. We have non experience with scripting in Java. We have used Python, but we are very inexperienced with it. One of us also have used Javascript. What scripting language should we use? What scripting ...
[ "I'm responsible for a fairly large hybrid Java/Jython system. We use java for core API development, then wire Java objects together using Jython. This is in a scientific computing environment where we need to be able to put together ad-hoc data analysis scripts quickly.\nIf I were starting this system from scr...
[ 9, 7, 5, 4, 4, 3, 1, 1, 1, 1, 0 ]
[]
[]
[ "java", "javascript", "python", "scripting_language" ]
stackoverflow_0000211536_java_javascript_python_scripting_language.txt
Q: read only permission in admin interface I saw this post, https://stackoverflow.com/posts/1348076/revisions , only at step 3 i'm getting confused, he tells to put 3. Add "get_view_permission" to default model class but what's the default model class? It doesn't seem to work to me, i get following error message: At...
read only permission in admin interface
I saw this post, https://stackoverflow.com/posts/1348076/revisions , only at step 3 i'm getting confused, he tells to put 3. Add "get_view_permission" to default model class but what's the default model class? It doesn't seem to work to me, i get following error message: AttributeError at /admin/ 'Options' object has ...
[ "Looks like he means in django/db/models.py.\n" ]
[ 0 ]
[]
[]
[ "admin", "django", "permissions", "python" ]
stackoverflow_0002508027_admin_django_permissions_python.txt
Q: Repeatedly querying xml using python I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. The way it works is I run the scripts several times with different arguments, depending on what I want to find out. Th...
Repeatedly querying xml using python
I have some xml documents I need to run queries on. I've created some python scripts (using ElementTree) to do this, since I'm vaguely familiar with using it. The way it works is I run the scripts several times with different arguments, depending on what I want to find out. These files can be relatively large (10MB+) ...
[ "While I second the suggestion to use lxml, you can get a huge performance boost by using the builtin cElementTree.\nfrom xml.etree import cElementTree as ElementTree\n\n", "First off, consider using the lxml implementation of ElementTree:\nhttp://lxml.de/\nThis is a wrapper for libxml2, which I find performs wel...
[ 3, 1, 1 ]
[]
[]
[ "caching", "elementtree", "python", "xml" ]
stackoverflow_0002507772_caching_elementtree_python_xml.txt
Q: Getting the previous line in Jython I want to print the line immediately before the searched string. How can I do that? Lets say my two lines are AADRG SDFJGKDFSDF and I am searching for SDF. I have found SDFJGKDFSDF, but how can I obtain the previous line AADRG? Does file.readline()-1 work? A: lastLine = "" ...
Getting the previous line in Jython
I want to print the line immediately before the searched string. How can I do that? Lets say my two lines are AADRG SDFJGKDFSDF and I am searching for SDF. I have found SDFJGKDFSDF, but how can I obtain the previous line AADRG? Does file.readline()-1 work?
[ "lastLine = \"\"\nfor line in lines:\n if line.find(\"SDF\"):\n print lastLine\n\n lastLine = line\n\nor \nlines = open(\"file\").readlines()\nfor line in lines:\n if \"SDF\" in line:\n # test for not being the first line of course.\n print lines[lines.index(line) - 1]\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0002508279_python.txt
Q: wxPython & pyGame Assignment I'm actually in need of your help and advice here on my assignment that I am working on. First of all, I was task to do a program that runs langton's ant simulation. For that, I've managed to get the source code (from snippets.dzone.com/posts/show/5143) and edited it accordingly to my ...
wxPython & pyGame Assignment
I'm actually in need of your help and advice here on my assignment that I am working on. First of all, I was task to do a program that runs langton's ant simulation. For that, I've managed to get the source code (from snippets.dzone.com/posts/show/5143) and edited it accordingly to my requirements. This was done and ra...
[ "Here's the page for you: pygame GUI discussion\nTo sum it up: Don't use any standard GUI stuff together with pygame. It might work, but it's most definitely gonna annoy you big time. Also on this page, there's a discussion of various different GUI libraries available which work directly in pygame. It sounds like y...
[ 1 ]
[]
[]
[ "pygame", "python", "wxpython" ]
stackoverflow_0002508352_pygame_python_wxpython.txt
Q: List of dict in Python I've got a list of dict in Python: dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream} self.list_cfg.append(dico_cfg) I append to my list a lot of dict in the same way. Now I would like to delete one dict and only one dict in this list? What is th...
List of dict in Python
I've got a list of dict in Python: dico_cfg = {'name': entry_name, 'ip': entry_ip, 'vendor': combo_vendor, 'stream': combo_stream} self.list_cfg.append(dico_cfg) I append to my list a lot of dict in the same way. Now I would like to delete one dict and only one dict in this list? What is the best way to proceed? I've ...
[ "A better solution would be to have a dict of dicts instead, indexed by the id attribute. This way, even if you remove a single dict, the other id's still remain the same.\n", "If you have a reference to the dictionary you want to remove, you can try:\nself.list_cfg.remove( your_dictionary )\n\nIf you don't have ...
[ 8, 2, 1, 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0002508513_dictionary_list_python.txt
Q: Most efficient way to concatenate and rearrange files I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed...
Most efficient way to concatenate and rearrange files
I am reading from several files, each file is divided into 2 pieces, first a header section of a few thousand lines followed by a body of a few thousand. My problem is I need to concatenate these files into one file where all the headers are on the top followed by the body. Currently I am using two loops: one to pull ...
[ "How fast would you expect it to be to move 13Gb of data around? This problem is I/O bound and not a problem with Python. To make it faster, do less I/O. Which means that you are either (a) stuck with the speed you've got or (b) should retool later elements of your toolchain to handle the files in-place rather t...
[ 2, 2, 0 ]
[]
[]
[ "concatenation", "file", "python" ]
stackoverflow_0002508610_concatenation_file_python.txt
Q: Need to understand Python signals and modules I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is: import sys, signal sigterm_caught...
Need to understand Python signals and modules
I am trying to get up to speed with Python, trying to replace some C with it. I have run into a problem with sharing data between modules, or more likely my understanding of the whole thing. I have a signal module which simplified is: import sys, signal sigterm_caught = False def SignalHandler(signum, stackframe): ...
[ "You need to add a global statement to the handler:\ndef SignalHandler(signum, stackframe):\n global sigterm_caught\n if signum == signal.SIGTERM:\n sigterm_caught = True\n sys.stdout.write(\"SIGTERM caught\\n\")\n\nThe Python compiler, by default, deems each name (like sigterm_caught) to be local to a func...
[ 8, 3 ]
[]
[]
[ "module", "python", "signals" ]
stackoverflow_0002508748_module_python_signals.txt
Q: Named pipe is not flushing in Python I have a named pipe created via the os.mkfifo() command. I have two different Python processes accessing this named pipe, process A is reading, and process B is writing. Process A uses the select function to determine when there is data available in the fifo/pipe. Despite the f...
Named pipe is not flushing in Python
I have a named pipe created via the os.mkfifo() command. I have two different Python processes accessing this named pipe, process A is reading, and process B is writing. Process A uses the select function to determine when there is data available in the fifo/pipe. Despite the fact that process B flushes after each writ...
[ "What APIs are you using? os.read() and os.write() don't buffer anything.\n", "To find out if Python's internal buffering is causing your problems, when running your scripts do \"python -u\" instead of \"python\". This will force python in to \"unbuffered mode\" which will cause all output to be printed instanta...
[ 1, 1, 0 ]
[]
[]
[ "flush", "ipc", "named_pipes", "python", "select" ]
stackoverflow_0002136844_flush_ipc_named_pipes_python_select.txt
Q: Convert or strip out "illegal" Unicode characters I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database. However for some characters, it explodes. I get complaints like this: UnicodeDecodeError: 'ascii' codec ...
Convert or strip out "illegal" Unicode characters
I've got a database in MSSQL that I'm porting to SQLite/Django. I'm using pymssql to connect to the database and save a text field to the local SQLite database. However for some characters, it explodes. I get complaints like this: UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 1916: ordinal not in...
[ "When you decode, just pass 'ignore' to strip those characters\nthere is some more way of stripping / converting those are\n'replace': replace malformed data with a suitable replacement marker, such as '?' or '\\ufffd' \n\n'ignore': ignore malformed data and continue without further notice \n\n'backslashreplace': r...
[ 11, 11 ]
[]
[]
[ "pymssql", "python", "unicode" ]
stackoverflow_0002508847_pymssql_python_unicode.txt
Q: ValidationError while running Google adwords client library examples I get the following error when I try to run sample example of Google adwords [root@some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in page = targeting_idea_servi...
ValidationError while running Google adwords client library examples
I get the following error when I try to run sample example of Google adwords [root@some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingIdeaService.py", line 105,...
[ "This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:\na) You're formatting the headers as specified in http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders , as Goose Bumper mentioned. This ap...
[ 0 ]
[]
[]
[ "google_ads_api", "python" ]
stackoverflow_0002479395_google_ads_api_python.txt
Q: How to format contour lines from Matplotlib I am working on using Matplotlib to produce plots of implicit equations (eg. y^x=x^y). With many thanks to the help I have already received I have got quite far with it. I have used a contour line to produce the plot. My remaining problem is with formatting the contour l...
How to format contour lines from Matplotlib
I am working on using Matplotlib to produce plots of implicit equations (eg. y^x=x^y). With many thanks to the help I have already received I have got quite far with it. I have used a contour line to produce the plot. My remaining problem is with formatting the contour line eg width, color and especially zorder, where ...
[ "This is rather hackish but...\nApparently in the current release Matplotlib does not support zorder on contours. This support, however, was recently added to the trunk.\nSo, the right way to do this is either to wait for the 1.0 release or just go ahead and re-install from trunk.\nNow, here's the hackish part. I...
[ 3 ]
[]
[]
[ "matplotlib", "python", "sympy" ]
stackoverflow_0002488800_matplotlib_python_sympy.txt
Q: Restful authentication between two GAE apps I am trying to write a RESTful Google app engine application (Python) that accepts requests only from another GAE that I wrote. I dont like any of the ways that I thought of getting this done, please advise if you know of something better than: Get SSL setup, and simply...
Restful authentication between two GAE apps
I am trying to write a RESTful Google app engine application (Python) that accepts requests only from another GAE that I wrote. I dont like any of the ways that I thought of getting this done, please advise if you know of something better than: Get SSL setup, and simply add the credentials on the request that my consu...
[ "Use an HMAC. Embed the same secret in each app, and sign requests and responses using the HMAC. Don't forget to include nonces and timestamps to prevent replay attacks!\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python", "rest", "restful_authentication" ]
stackoverflow_0002509205_google_app_engine_python_rest_restful_authentication.txt
Q: catalogue a list of dictionaries I have a list of dictionaries: people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}, {"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}, {"name": "Dana", "city": "Dallas", "a...
catalogue a list of dictionaries
I have a list of dictionaries: people = [{"name": "Roger", "city": "NY", "age": 20, "sex": "M"}, {"name": "Dan", "city": "Boston", "age": 20, "sex": "M"}, {"name": "Roger", "city": "Boston", "age": 21, "sex": "M"}, {"name": "Dana", "city": "Dallas", "age": 30, "sex": "F"}] I want to catal...
[ "recursively:\nimport itertools, operator\n\ndef catalog(fields,people):\n cur_field = operator.itemgetter(fields[0])\n groups = itertools.groupby(sorted(people, key=cur_field),cur_field)\n if len(fields)==1:\n return dict((k,list(v)) for k,v in groups)\n else:\n return dict((k,catalog(fie...
[ 7, 0, 0 ]
[]
[]
[ "catalog", "dictionary", "nested", "python" ]
stackoverflow_0002509260_catalog_dictionary_nested_python.txt
Q: python urllib2.openurl doesn't work with specific URL (redirect)? I need to download a CSV file, which works fine in browsers using: http://www.ftse.com/objects/csv_to_csv.jsp?infoCode=100a&theseFilters=&csvAll=&theseColumns=Mw==&theseTitles=&tableTitle=FTSE%20100%20Index%20Constituents&dl=&p_encoded=1&e=.csv The...
python urllib2.openurl doesn't work with specific URL (redirect)?
I need to download a CSV file, which works fine in browsers using: http://www.ftse.com/objects/csv_to_csv.jsp?infoCode=100a&theseFilters=&csvAll=&theseColumns=Mw==&theseTitles=&tableTitle=FTSE%20100%20Index%20Constituents&dl=&p_encoded=1&e=.csv The following code works for any other file (url) (with a fully qualified ...
[ "urllib2 uses httplib under the hood, so the best way to diagnose this is to turn on http connection debugging. Add this code before you access the url and you should get a nice summary of exactly what http traffic is being generated:\nimport httplib\nhttplib.HTTPConnection.debuglevel = 1\n\n" ]
[ 1 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0002509073_python_urllib2.txt
Q: Convert UTF-8 bytes to some other encoding in Python I need to do in Python 2.4 (yes, 2.4 :-( ). I've got a plain string object, which represents some text encoded with UTF-8. It comes from an external library, which can't be modified. So, what I think I need to do, is to create an Unicode object using bytes from ...
Convert UTF-8 bytes to some other encoding in Python
I need to do in Python 2.4 (yes, 2.4 :-( ). I've got a plain string object, which represents some text encoded with UTF-8. It comes from an external library, which can't be modified. So, what I think I need to do, is to create an Unicode object using bytes from that source object, and then convert it to some other enco...
[ ">>> x.decode('utf8').encode('iso-8859-2')\n'Sk\\xb3odowski'\n\n" ]
[ 9 ]
[]
[]
[ "encoding", "python", "unicode" ]
stackoverflow_0002509578_encoding_python_unicode.txt
Q: compare two following values in numpy array What is the best way to touch two following values in an numpy array? example: npdata = np.array([13,15,20,25]) for i in range( len(npdata) ): print npdata[i] - npdata[i+1] this looks really messed up and additionally needs exception code for the last iteration of ...
compare two following values in numpy array
What is the best way to touch two following values in an numpy array? example: npdata = np.array([13,15,20,25]) for i in range( len(npdata) ): print npdata[i] - npdata[i+1] this looks really messed up and additionally needs exception code for the last iteration of the loop. any ideas? Thanks!
[ "numpy provides a function diff for this basic use case\n>>> import numpy\n>>> x = numpy.array([1, 2, 4, 7, 0])\n>>> numpy.diff(x)\narray([ 1, 2, 3, -7])\n\nYour snippet computes something closer to -numpy.diff(x).\n", "How about range(len(npdata) - 1) ?\nHere's code (using a simple array, but it doesn't matter...
[ 3, 0, 0 ]
[]
[]
[ "indexing", "iteration", "loops", "numpy", "python" ]
stackoverflow_0002509644_indexing_iteration_loops_numpy_python.txt
Q: Defining the context of a word - Python I think this is an interesting question, at least for me. I have a list of words, let's say: photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet and I have a list of contexts: Programming World news Techno...
Defining the context of a word - Python
I think this is an interesting question, at least for me. I have a list of words, let's say: photo, free, search, image, css3, css, tutorials, webdesign, tutorial, google, china, censorship, politics, internet and I have a list of contexts: Programming World news Technology Web Design I need to try and match wor...
[ "This sounds like it's more of a categorization/ontology problem than NLP. Try WordNet for a standard ontology.\nI don't see any real NLP in your stated problem, but if you do need some semantic analysis or a parser try NLTK.\n", "Where do these words come from? Do they come from real texts. If they are then it...
[ 3, 2, 2, 1 ]
[]
[]
[ "dictionary", "django", "nlp", "python" ]
stackoverflow_0002500732_dictionary_django_nlp_python.txt
Q: Python - Nested List to Tab Delimited File? I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g., nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]. I wish to create a function in order to output this data construct into a tab delimited format, e.g., x y z a b c Any help gr...
Python - Nested List to Tab Delimited File?
I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g., nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]. I wish to create a function in order to output this data construct into a tab delimited format, e.g., x y z a b c Any help greatly appreciated! Thanks in advance, Seafoid.
[ ">>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]\n>>> for line in nested_list:\n... print '\\t'.join(line)\n... \nx y z\na b c\n>>> \n\n", "with open('fname', 'w') as file:\n file.writelines('\\t'.join(i) + '\\n' for i in nested_list)\n\n", "In my view, it's a simple one-liner:\nprint '\\n'.jo...
[ 6, 6, 5, 3, 1 ]
[]
[]
[ "csv", "list", "nested", "python" ]
stackoverflow_0002509706_csv_list_nested_python.txt
Q: Can this be done with the ORM? - Django I have a few item listed in a database, ordered through Reddit's algorithm. This is it: def reddit_ranking(post): t = time.mktime(post.created_on.timetuple()) - 1134000000 x = post.score if x>0: y=1 elif x==0: y=-0 else: y=-1 if x<0: z=1 else: z...
Can this be done with the ORM? - Django
I have a few item listed in a database, ordered through Reddit's algorithm. This is it: def reddit_ranking(post): t = time.mktime(post.created_on.timetuple()) - 1134000000 x = post.score if x>0: y=1 elif x==0: y=-0 else: y=-1 if x<0: z=1 else: z=x return (log(z) + y * t/45000) I'm w...
[ "It's not much work to do it manually:\nfrom django.db import connection\n\nitems = Item.objects.filter(created_on__gte=datetime.now()-timedelta(days=7))\ncursor = connection.cursor()\ncursor.executemany(\"UPDATE myapp_item SET reddit_rank = %s WHERE id = %s\",\n [(reddit_rank(item), item.pk) for ...
[ 2 ]
[]
[]
[ "django", "django_orm", "orm", "python", "sql" ]
stackoverflow_0002510031_django_django_orm_orm_python_sql.txt
Q: More nest Python nested dictionaries After reading What is the best way to implement nested dictionaries? why is it wrong to do: c = collections.defaultdict(collections.defaultdict(int)) in python? I would think this would work to produce {key:{key:1}} or am I thinking about it wrong? A: The constructor of de...
More nest Python nested dictionaries
After reading What is the best way to implement nested dictionaries? why is it wrong to do: c = collections.defaultdict(collections.defaultdict(int)) in python? I would think this would work to produce {key:{key:1}} or am I thinking about it wrong?
[ "The constructor of defaultdict expects a callable. defaultdict(int) is a default dictionary object, not a callable. Using a lambda it can work, however:\nc = collections.defaultdict(lambda: collections.defaultdict(int))\n\nThis works since what I pass to the outer defaultdict is a callable that creates a new defau...
[ 14, 5 ]
[]
[]
[ "collections", "nested", "python" ]
stackoverflow_0002510126_collections_nested_python.txt
Q: Why can't my Apache see my media folder? Alias /media/ /home/matt/repos/hello/media <Directory /home/matt/repos/hello/media> Options -Indexes Order deny,allow Allow from all </Directory> WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi /media is my directory. When I go to mydomain.com/media/, it says 403...
Why can't my Apache see my media folder?
Alias /media/ /home/matt/repos/hello/media <Directory /home/matt/repos/hello/media> Options -Indexes Order deny,allow Allow from all </Directory> WSGIScriptAlias / /home/matt/repos/hello/wsgi/django.wsgi /media is my directory. When I go to mydomain.com/media/, it says 403 Forbidden. And, the rest of my site doesn't w...
[ "You have Indexes disabled, so Apache won't generate a listing of the files when you request the directory /media (instead, it shows the 403 Forbidden error). Try accessing a file directly within there, e.g.: http://localhost/media/some_image.jpg\n", "It looks to me that WSGIScriptAlias / /home/matt/repos/hello/...
[ 4, 3, 2, 0, 0 ]
[]
[]
[ "apache", "django", "linux", "python", "unix" ]
stackoverflow_0002506883_apache_django_linux_python_unix.txt
Q: What's the best django way to do a query that spans several tables? I have a reviews/ratings web application, a la Digg. My django app content has the following model: class Content(models.Model): title = models.CharField(max_length=128) url = models.URLField(max_length=2048) description = models.TextF...
What's the best django way to do a query that spans several tables?
I have a reviews/ratings web application, a la Digg. My django app content has the following model: class Content(models.Model): title = models.CharField(max_length=128) url = models.URLField(max_length=2048) description = models.TextField(blank=True) class Recommendation(models.Model): user = models.F...
[ "I would use:\nRecommendation.objects.filter(user__publication_set__subscriber=request.user).select_related()\n\nThat will get you all the Recommendation objects as you requested, and the select_related will load all the related User and Content objects into memory so that subsequent access of them won't hit the DB...
[ 10, 1 ]
[]
[]
[ "database", "django", "mysql", "python" ]
stackoverflow_0002510429_database_django_mysql_python.txt
Q: Looping an executable to get the result from Python script In my python script, I need to call within a for loop an executable, and waiting for that executable to write the result on the "output.xml". How do I manage to use wait() & how do I know when one of my executable is finished generating the result to get t...
Looping an executable to get the result from Python script
In my python script, I need to call within a for loop an executable, and waiting for that executable to write the result on the "output.xml". How do I manage to use wait() & how do I know when one of my executable is finished generating the result to get the result? How do I close that process and open a new one to cal...
[ "Popen.wait() will make the script wait until the process ends. There's no need to kill the process afterwards, since it will have already exited.\n", "I think the easiest way to do is using call:\nimport subprocess\nretcode = subprocess.call('command', shell=True)\n\nIt waits for the process to terminate and ass...
[ 1, 1 ]
[]
[]
[ "executable", "linux", "python", "system_calls" ]
stackoverflow_0002484049_executable_linux_python_system_calls.txt
Q: python, accessing a psycopg2 form a def? i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python i have tried this: def get_dblink( dbstring): """ Return a database cnx. """ global psycopg2 try cnx = psycopg2.connect( dbstring) except Exception,...
python, accessing a psycopg2 form a def?
i'm trying to make a group of defs in one file so then i just can import them whenever i want to make a script in python i have tried this: def get_dblink( dbstring): """ Return a database cnx. """ global psycopg2 try cnx = psycopg2.connect( dbstring) except Exception, e: print "Unable to connect to DB. Error ...
[ "You just need to import psycopg2 in your first snippet.\nIf you need to there's no problem to 'also' import it in the second snippet (Python makes sure the modules are only imported once). Trying to use globals for this is bad practice.\nSo: at the top of every module, import every module which is used within that...
[ 7 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0002510756_psycopg2_python.txt
Q: increment a variable in django templates All, How Can we increment a value like the following in django templates, {{ flag =0 }} {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/> {% endfor %} thanks.. A: I don't think it's inte...
increment a variable in django templates
All, How Can we increment a value like the following in django templates, {{ flag =0 }} {% for op in options %} {{op.choices}}<input type="radio" name="template" id="template" value="template{{flag++}}"/> {% endfor %} thanks..
[ "I don't think it's intended you should alter data in your templates. For in your specific case, you could instead use the forloop.counter variable.\nFor example: \n{% for op in options %}\n {{op.choices}}<input type=\"radio\" name=\"template\" id=\"template{{forloop.counter}}\" value=\"template{{forloop.counter}}...
[ 20, 9, 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0002507284_django_django_templates_python.txt
Q: Python - create blacklist file of IP addresses that have more than 5 failed login attempts in the authlog Basically I have an authlog/syslog file with a list of log in attempts and IP addresses - I need to make a Python program that will create a txt file with all the IP addresses that have more than 5 failed logi...
Python - create blacklist file of IP addresses that have more than 5 failed login attempts in the authlog
Basically I have an authlog/syslog file with a list of log in attempts and IP addresses - I need to make a Python program that will create a txt file with all the IP addresses that have more than 5 failed login attempts - a sort of "blacklist". So basically something like: if "uniqueipaddress" and "authentication failu...
[ "For each line:\n\nread the IP and attempt status\nkeep a dictionary by IP of amount of failed attempts\n\nThen go over the dictionary:\n\nprint to file all IPs with 5 or more attempts\n\n\nPython hints:\n\nTo read a file line by line: for line in open(filename)\nParsing the log line depends entirely on its format....
[ 1, 0 ]
[]
[]
[ "blacklist", "ip_address", "python", "syslog" ]
stackoverflow_0002510158_blacklist_ip_address_python_syslog.txt
Q: Sqlalchemy layout with WSGI application I'm working on writing a small WSGI application using Bottle and SqlAlchemy and am confused on how the "layout" of my application should be in terms of SqlAlchemy. My confusion is with creating engines and sessions. My understanding is that I should only create one engine wi...
Sqlalchemy layout with WSGI application
I'm working on writing a small WSGI application using Bottle and SqlAlchemy and am confused on how the "layout" of my application should be in terms of SqlAlchemy. My confusion is with creating engines and sessions. My understanding is that I should only create one engine with the 'create_engine' method. Should I be cr...
[ "What you need to achieve is well described in the pylons documentation: Defining Tables and ORM classes:\n\nThe model consists of two files: __init__.py and meta.py. __init__.py contains your table definitions and ORM classes, and an init_model() function which must be called at application startup. meta.py is mer...
[ 6, 2 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002505426_python_sqlalchemy.txt
Q: Calling private parent class method from parent class (django) I want to call a redefined private method from an abstract parent class. I am using django if that matters. class Parent(models.Model): def method1(self): #do somthing self.__method2() def method2(self): pass # I als...
Calling private parent class method from parent class (django)
I want to call a redefined private method from an abstract parent class. I am using django if that matters. class Parent(models.Model): def method1(self): #do somthing self.__method2() def method2(self): pass # I also tried calling up a prent method with super class child(Parent): ...
[ "Initial double underscores prevent polymorphism since both the method definition and the method call get mangled, to two different names. Replace with a single underscore to fix this.\nAlso, double underscores are not used for \"private\" attributes, and you should discard whatever reference told you that they are...
[ 4 ]
[]
[]
[ "abstract_class", "django", "inheritance", "python" ]
stackoverflow_0002511321_abstract_class_django_inheritance_python.txt
Q: How do I render text with pixel heights rather than points in pyglet? Pyglet only seems to use points. Is there a way to convert easily? Surely there must be a simple way because it's something obviously important, to be able to use pixels for text height. class Font(): def __init__(self,font,size): se...
How do I render text with pixel heights rather than points in pyglet?
Pyglet only seems to use points. Is there a way to convert easily? Surely there must be a simple way because it's something obviously important, to be able to use pixels for text height. class Font(): def __init__(self,font,size): self.size = size self.font = font def return_surface(self,label):...
[ "The number of pixels taken up by a certain point size will depend on your screens DPI.\nFor example, \"14pt\" is the distance covering 14 points, which at a default DPI of 96 is around 18 pixels.\nThis site give a good explanation of converting point sizes to pixels.\n" ]
[ 0 ]
[]
[]
[ "fonts", "label", "pyglet", "python", "text" ]
stackoverflow_0002510278_fonts_label_pyglet_python_text.txt
Q: Is there a way to change lookandfeel for wx Python? i was curious if there is some sort of way to change the look and feel of wxpython to something that is more standardized. I am writing a small application for windows and mac os x. And i noticed that Mac formats the layout and look of my application pretty terri...
Is there a way to change lookandfeel for wx Python?
i was curious if there is some sort of way to change the look and feel of wxpython to something that is more standardized. I am writing a small application for windows and mac os x. And i noticed that Mac formats the layout and look of my application pretty terribly. I looked around online and could not find anything. ...
[ "From http://old.nabble.com/wxPython-Themes-Colors-td20337650.html:\n\nNot really. The default colors are always the platform and/or theme\n defaults, but some things can be changed by setting the colors of the\n parent window before creating the children. Not everything works that\n way however, such as thing...
[ 2 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0002511228_python_wxpython_wxwidgets.txt
Q: Clear all class variables between instances This is probably a stupid question, but what's the best way to clear class variables between instances? I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? Or am I doing something totally wrong that requires a di...
Clear all class variables between instances
This is probably a stupid question, but what's the best way to clear class variables between instances? I know I could reset each variable individually in the constructor; but is there a way to do this in bulk? Or am I doing something totally wrong that requires a different approach? Thanks for helping ... class U...
[ "Can you just pass the parameters into the constructor like this?\nclass User(object):\n def __init__(self, name, email):\n self.name = name\n self.email = email\n def commit(self):\n pass\n\njason = User('jason', 'jason@email.com')\njack = User('jack', 'jack@yahoo.com')\n\nThere's nothin...
[ 3, 3, 0, 0 ]
[]
[]
[ "class", "oop", "pylons", "python" ]
stackoverflow_0002511556_class_oop_pylons_python.txt
Q: running python code in matlab? i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful.... A: You should probably avoid this. Use one or the other - preferably Python. But if you have to use both, you could try this: http://github.co...
running python code in matlab?
i have some python code(some functions) and i want to implement this in bigger matlab program!how can i do this?any help will be useful....
[ "You should probably avoid this. Use one or the other - preferably Python.\nBut if you have to use both, you could try this:\nhttp://github.com/kw/pymex (scroll down for the readme)\nDisclaimer: I wrote this. It may be somewhat difficult to get it to compile and work, particularly if you're on Windows (there is a p...
[ 4, 1, 1 ]
[ "There is a library called PyMat. It allows to call python code from matlab.\n" ]
[ -2 ]
[ "matlab", "python" ]
stackoverflow_0002509927_matlab_python.txt
Q: How to optimize my PageRank calculation? In the book Programming Collective Intelligence I found the following function to compute the PageRank: def calculatepagerank(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create ...
How to optimize my PageRank calculation?
In the book Programming Collective Intelligence I found the following function to compute the PageRank: def calculatepagerank(self,iterations=20): # clear out the current PageRank tables self.con.execute("drop table if exists pagerank") self.con.execute("create table pagerank(urlid primary key,score)") ...
[ "If you have a very large database (e.g. # records ~ # pages in the WWW) using the database in a manner similar to what's suggested in the book makes sense, because you're not going to be able to keep all that data in memory.\nIf your dataset is small enough, you can (probably) improve your second version by not do...
[ 2, 1, 0, 0 ]
[]
[]
[ "optimization", "pagerank", "python", "sql" ]
stackoverflow_0002484445_optimization_pagerank_python_sql.txt
Q: Looking for a recommendation of a good tutorial on best practices for a web scraping project? I need to do a fairly extensive project involving web scraping and am considering using Hpricot or Beautiful Soup (i.e. Ruby or Python). Has anyone come across a tutorial that they thought was particularly good on this su...
Looking for a recommendation of a good tutorial on best practices for a web scraping project?
I need to do a fairly extensive project involving web scraping and am considering using Hpricot or Beautiful Soup (i.e. Ruby or Python). Has anyone come across a tutorial that they thought was particularly good on this subject that would help me start the project off on the right foot?
[ "Two of my favorite tools for Python web scraping are Scrapy and Mechanize. Each of these projects has its own tutorial and best practices.\n", "Not a tool, really, but a good discussion is Michael Shrenk's book, Webbots, Spiders, and Screen Scrapers.\nThe book succeeds very well in its stated mission: explaining...
[ 9, 5, 4, 3, 0 ]
[]
[]
[ "beautifulsoup", "hpricot", "python", "ruby", "screen_scraping" ]
stackoverflow_0000684629_beautifulsoup_hpricot_python_ruby_screen_scraping.txt
Q: Bundle module with app on Google App Engine This may be a basic question but how can I include a module with my app. I'm very new to python and what I want to do is to include this module simplejson with my app, but after downloading it I have no idea what to do next :( This is how the module looks like after un...
Bundle module with app on Google App Engine
This may be a basic question but how can I include a module with my app. I'm very new to python and what I want to do is to include this module simplejson with my app, but after downloading it I have no idea what to do next :( This is how the module looks like after unzip it. I don't know what files to move to my ap...
[ "Put the simplejson directory (that is inside the simplejson-2.1.0) in your app.\nOr, you could just use the simplejson lib that's bundled with the Django lib that's bundled with App Engine by doing the following import wherever you need it:\nfrom django.utils import simplejson\n\nThat's always available, without n...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002511883_google_app_engine_python.txt
Q: Numpy Matrix keeps giving me an Error, Okay this is werid, i keep getting the error, randomly. ValueError: matrix must be 2-dimensional So i tracked it down, and cornered it to basically something like this: a_list = [[(1,100) for _ in range(32)] for _ in range(32)] numpy.matrix(a_list) Whats wrong with this? If...
Numpy Matrix keeps giving me an Error,
Okay this is werid, i keep getting the error, randomly. ValueError: matrix must be 2-dimensional So i tracked it down, and cornered it to basically something like this: a_list = [[(1,100) for _ in range(32)] for _ in range(32)] numpy.matrix(a_list) Whats wrong with this? If i print a_list it is clearly a 2d matrix of...
[ "The easiest way around this is to just use a numpy array, instead of a numpy matrix:\na_list = [[(1,100) for _ in range(32)] for _ in range(32)]\narr=numpy.array(a_list)\n\nNumpy matrices are strictly 2-dimensional, and a_list is 3-dimensional. So numpy matrices are not an option.\n", "tuples have more than one ...
[ 4, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002512033_numpy_python.txt
Q: Allowing threads from python after calling a blocking i/o code in a python extension generated using SWIG I have written a python extension wrapping an existing C++ library live555 (wrapping RTSP client interface to be specific) in SWIG. The extension works when it is operated in a single thread, but as soon as I ...
Allowing threads from python after calling a blocking i/o code in a python extension generated using SWIG
I have written a python extension wrapping an existing C++ library live555 (wrapping RTSP client interface to be specific) in SWIG. The extension works when it is operated in a single thread, but as soon as I call the event loop function of the library, python interpreter never gets the control back. So if I create a s...
[ "SWIG gives you plenty of hooks to help make this happen. If a coarse solution is sufficient for your needs, one thing I've done in the past is put something like this in my .swig file:\n%exception {\n Py_BEGIN_ALLOW_THREADS\n $action\n Py_END_ALLOW_THREADS\n}\n\nThis (ab)uses the SWIG facility for decora...
[ 5 ]
[]
[]
[ "python", "rtsp_client", "swig" ]
stackoverflow_0002510696_python_rtsp_client_swig.txt
Q: Unknown syntax error Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead. Please help :) def dealcards(): for i in range(len(cards)): cards[i] = '' for j in range(8): cards[i] = c...
Unknown syntax error
Why do I get a syntax error running this code? If I remove the highlighted section (return cards[i]) I get the error highlighting the function call instead. Please help :) def dealcards(): for i in range(len(cards)): cards[i] = '' for j in range(8): cards[i] = cards[i].append(random.rand...
[ "cards[i] = cards[i].append(random.randint(0,9)\n ^\n\nMissing closing parenthesis. And the return statement on the next line is incorrectly indented.\n", "Missing a close:\ncards[i] = cards[i].append(random.randint(0,9))\n\n", "\nYour SyntaxError is due to an unclos...
[ 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002511722_python.txt
Q: Pylons/Routes Did url_for() change within templates? I'm getting an error: GenerationException: url_for could not generate URL. Called with args: () {} from this line of a mako template: <p>Your url is ${h.url_for()}</p> Over in my helpers.py, I do have: from routes import url_for Looking at the Routes-1.12.1-p...
Pylons/Routes Did url_for() change within templates?
I'm getting an error: GenerationException: url_for could not generate URL. Called with args: () {} from this line of a mako template: <p>Your url is ${h.url_for()}</p> Over in my helpers.py, I do have: from routes import url_for Looking at the Routes-1.12.1-py2.6.egg/routes/util.py, I seem to go wrong about line it ...
[ "I didn't know url_for() (no arguments) was ever legal, but if it was and this is what you're referring to as \"url_current\", I believe the new approach is to use the url object, calling a method on it as url.current().\n" ]
[ 5 ]
[]
[]
[ "mako", "pylons", "python", "routes" ]
stackoverflow_0002512264_mako_pylons_python_routes.txt
Q: Find new messages added to an imap mailbox since I last checked with python imaplib2? I am trying to write a program that monitors an IMAP mailbox and automatically copies every new incoming message into an "Archive" folder. I'm using imaplib2 which implements the IDLE command. Here's my basic program: M = imaplib...
Find new messages added to an imap mailbox since I last checked with python imaplib2?
I am trying to write a program that monitors an IMAP mailbox and automatically copies every new incoming message into an "Archive" folder. I'm using imaplib2 which implements the IDLE command. Here's my basic program: M = imaplib2.IMAP4("mail.me.com") M.login(username,password) lst = M.list() assert lst[0]=='OK' for mb...
[ "See example and references in python-imap-idle-with-imaplib2 (Wayback Machine snapshot).\nThe module involves threading, you should pay attention to event synchronization.\nThe example suggests synchronizing with events, and leaves mail processing to the reader:\n# The method that gets called when a new email arri...
[ 2, 2 ]
[]
[]
[ "imap", "imaplib", "python", "python_idle" ]
stackoverflow_0002047067_imap_imaplib_python_python_idle.txt
Q: pyenchant RPM for alt-install of python2.6. ELF class error I know what my problem is with this issue, but I'm a little confused about how to best go about fixing it. I have a RHEL 5.4 system, with Python2.6 alt-installed (via the geekymedia RPMS). everything seems to be working. As I tweak a spec file, I'm able...
pyenchant RPM for alt-install of python2.6. ELF class error
I know what my problem is with this issue, but I'm a little confused about how to best go about fixing it. I have a RHEL 5.4 system, with Python2.6 alt-installed (via the geekymedia RPMS). everything seems to be working. As I tweak a spec file, I'm able to build out RPMs to work with this new Python install. I'm bui...
[ "Just in case someone else runs into this:\n\nI removed the RHEL versions of enchant\ndownloaded the RHEL source RPM for enchant (same version)\nbuilt my own 64-bit only RPM for enchant\ninstalled that\n\nmy Py2.6 altinstall python-enchant package now works.\n" ]
[ 1 ]
[]
[]
[ "installation", "pyenchant", "python" ]
stackoverflow_0002495428_installation_pyenchant_python.txt
Q: How to chroot Django Can one run Django in a chroot? Notably, what's necessary in order to set up (for example) /var/www as a chroot'd directory and then have Django run in that chroot'd directory? Thank you - I'm grateful for any input. A: There are many reasons mod_wsgi is preferred for Python web app deployme...
How to chroot Django
Can one run Django in a chroot? Notably, what's necessary in order to set up (for example) /var/www as a chroot'd directory and then have Django run in that chroot'd directory? Thank you - I'm grateful for any input.
[ "There are many reasons mod_wsgi is preferred for Python web app deployment. One is stability, another is the variety of configuration options... one of which is ability to chroot the mod_wsgi daemon (starting with version 3.00).\nThe chroot option is not yet documented for the WSGIDaemonProcess directive at http:...
[ 3, 2 ]
[]
[]
[ "chroot", "django", "jail", "python", "security" ]
stackoverflow_0002512428_chroot_django_jail_python_security.txt
Q: FancyURLOpener failing since moving to python 3.1.2 I had an application that was downloading a .CSV file from a password-protected website then processing it futher. I was using FancyURLOpener, and simply hardcoding the username and password. (Obviously, security is not a high priority in this particular instance...
FancyURLOpener failing since moving to python 3.1.2
I had an application that was downloading a .CSV file from a password-protected website then processing it futher. I was using FancyURLOpener, and simply hardcoding the username and password. (Obviously, security is not a high priority in this particular instance). Since downloading Python 3.1.2, this code has stopped ...
[ "It's a known bug: http://bugs.python.org/issue8123\n" ]
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0002512538_python_python_3.x.txt
Q: Is this the correct way to convert a UTC datetime string into localtime? Is this the correct way to convert a UTC string into local time allowing for daylight savings? It looks ok to me but you never know :) import time UTC_STRING = "2010-03-25 02:00:00" stamp = time.mktime(time.strptime(UTC_STRING,"%Y-%m-%d %H:%M...
Is this the correct way to convert a UTC datetime string into localtime?
Is this the correct way to convert a UTC string into local time allowing for daylight savings? It looks ok to me but you never know :) import time UTC_STRING = "2010-03-25 02:00:00" stamp = time.mktime(time.strptime(UTC_STRING,"%Y-%m-%d %H:%M:%S")) stamp -= time.timezone now = time.localtime() if now[8] == 1: sta...
[ "timezone related calculations are not trivial and there are already good libraries available e.g. use pytz, using that you will be able to convert from any timezone to any other timezone with confidence. usage is as simple as this\n>>> warsaw = pytz.timezone('Europe/Warsaw')\n>>> loc_dt1 = warsaw.localize(datetime...
[ 5 ]
[]
[]
[ "python", "time" ]
stackoverflow_0002512854_python_time.txt
Q: How do I constrain the SCons Command builder to run only if its dependencies have changed? I am using the Command builder in scons to specify that a particular script needs to be invoked to produce a particular file. I would like to only run the script if it has been modified since the file was previously generat...
How do I constrain the SCons Command builder to run only if its dependencies have changed?
I am using the Command builder in scons to specify that a particular script needs to be invoked to produce a particular file. I would like to only run the script if it has been modified since the file was previously generated. The default behaviour of the Command builder seems to be to always run the script. How can I...
[ "First, it looks like code/speed.py has no control on the output filename... Hardcoded output filenames are usually considered bad practice in scons (see yacc tool). It would read better like this:\nspeed = Command('speed_analysis.tex', [], 'python code/speed.py -o $TARGET')\n\nNow, the PDF target produces a report...
[ 11, 1 ]
[]
[]
[ "python", "scons" ]
stackoverflow_0000828075_python_scons.txt
Q: XML document being parsed as single element instead of sequence of nodes Given xml that looks like this: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Store> I am getti...
XML document being parsed as single element instead of sequence of nodes
Given xml that looks like this: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Store> I am getting this as my parsed xmldoc: >>> from xml.dom import minidom >>> xmldoc = mini...
[ "An XML document always has a single root element. If you don't care about the root element, just ignore it and look at its children instead!\nFor example, using the more modern element-tree (but minidom offers similar possibilities in this respect):\ntry:\n import xml.etree.cElementTree as et\nexcept ImportError...
[ 2, 0 ]
[]
[]
[ "minidom", "python", "xml" ]
stackoverflow_0002512702_minidom_python_xml.txt
Q: Django debug error I have the following in my model: class info(models.Model): add = models.CharField(max_length=255) name = models.CharField(max_length=255) An in the views when i say info_l = info.objects.filter(id=1) logging.debug(info_l.name) i get an error saying name d...
Django debug error
I have the following in my model: class info(models.Model): add = models.CharField(max_length=255) name = models.CharField(max_length=255) An in the views when i say info_l = info.objects.filter(id=1) logging.debug(info_l.name) i get an error saying name doesnt exist at debug sta...
[ "1. Selecting Single Items\nIt looks like you're trying to get a single object. Using filter will return a QuerySet object (as is happening in your code), which behaves more like a list (and, as you've noticed, lacks the name attribute).\nYou have two options here. First, you can just grab the first element:\nin...
[ 2 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0002513237_django_django_views_python.txt
Q: Python: Count lines and differentiate between them I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. An example output is this...
Python: Count lines and differentiate between them
I'm using an application that gives a timed output based on how many times something is done in a minute, and I wish to manually take the output (copy paste) and have my program, and I wish to count how many times each minute it is done. An example output is this: 13:48 An event happened. 13:48 Another event happene...
[ "You could just use the time as a key for a dictionary and point it to a list of event messages. The length of that value would give you the number of events, while still letting you get at the specific events themselves:\n>>> from pprint import pprint\n>>> from collections import defaultdict\n>>> events = defaultd...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "count", "python" ]
stackoverflow_0002510651_count_python.txt
Q: Structure accessible by attribute name or index options I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd. In trying to...
Structure accessible by attribute name or index options
I am very new to Python, and trying to figure out how to create an object that has values that are accessible either by attribute name, or by index. For example, the way os.stat() returns a stat_result or pwd.getpwnam() returns a struct_passwd. In trying to figure it out, I've only come across C implementations of th...
[ "Python 2.6 introduced collections.namedtuple to make this easy. With older Python versions you can use the named tuple recipe.\nQuoting directly from the docs:\n>>> Point = namedtuple('Point', 'x y')\n>>> p = Point(11, y=22) # instantiate with positional or keyword arguments\n>>> p[0] + p[1] # inde...
[ 5, 3, 0 ]
[]
[]
[ "data_structures", "namedtuple", "python" ]
stackoverflow_0002512671_data_structures_namedtuple_python.txt
Q: Apps not showing in Django admin site I have a Django project with about 10 apps in it. But the admin interface only shows Auth and Site models which are part of Django distribution. Yes, the admin interface is up and working but none of my self-written apps shows there. INSTALLED_APPS INSTALLED_APPS = ( 'djan...
Apps not showing in Django admin site
I have a Django project with about 10 apps in it. But the admin interface only shows Auth and Site models which are part of Django distribution. Yes, the admin interface is up and working but none of my self-written apps shows there. INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites...
[ "Which version of Django are you using? Support for files named admin.py was added in version 1.0 (I think). Before that, you'd have to add extra information to your model.\n", "If something in your app throws an exception, the app or model may be excluded from the admin on subsequent requests.\nIf that is the ...
[ 0, 0 ]
[]
[]
[ "admin", "django", "model", "python" ]
stackoverflow_0002398721_admin_django_model_python.txt
Q: Discovery of web services using Python I have several devices on a network. I am trying to use a library to discover the presence and itentity of these devices using Python script, the devices all have a web service. My question is, are there any modules that would help me with this problem as the only module I ha...
Discovery of web services using Python
I have several devices on a network. I am trying to use a library to discover the presence and itentity of these devices using Python script, the devices all have a web service. My question is, are there any modules that would help me with this problem as the only module I have found is ws-discovery for Python? And if...
[ "Unfortunately I've never used ws-discovery myself, but there seems to be a Python project which implements it:\nhttps://pypi.org/project/WSDiscovery/\nFrom their documentation here's a short example on how to use it:\nwsd = WSDiscovery()\nwsd.start()\n\nttype = QName(\"abc\", \"def\")\n\nttype1 = QName(\"namespace...
[ 1, 1 ]
[]
[]
[ "python", "web_services", "ws_discovery" ]
stackoverflow_0002462618_python_web_services_ws_discovery.txt
Q: python manage.py runserver fails I am trying to learn django by following along with this tutorial. I am using django version 1.1.1 I run django-admin.py startproject mysite and it creates the files it should. Then I try to start the server by running python manage.py runserver but here is where I get the follow...
python manage.py runserver fails
I am trying to learn django by following along with this tutorial. I am using django version 1.1.1 I run django-admin.py startproject mysite and it creates the files it should. Then I try to start the server by running python manage.py runserver but here is where I get the following error. Traceback (most recent call...
[ "Something is broken in your django installation. maybe you have a (very) old version somewhere in the path? \nLOCALE_PATHS was given a default value in the global settings file a long time ago.\n", "Can't really explain that. Try removing the project directory and starting again.\nAre you definitely running the ...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0002506079_django_python.txt
Q: making python 2.6 exception backward compatible I have the following python code: try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how ...
making python 2.6 exception backward compatible
I have the following python code: try: pr.update() except ConfigurationException as e: returnString=e.line+' '+e.errormsg This works under python 2.6, but the "as e" syntax fails under previous versions. How can I resolved this? Or in other words, how do I catch user-defined exceptions (and use their ins...
[ "This is both backward AND forward compatible:\nimport sys\ntry:\n pr.update()\nexcept (ConfigurationException,):\n e = sys.exc_info()[1]\n returnString = \"%s %s\" % (e.line, e.errormsg)\n\nThis gets rid of the ambiguity problem in python 2.5 and earlier, while still not losing any of the advantages of th...
[ 12, 9, 5, 1 ]
[]
[]
[ "exception", "python", "python_2.x", "syntax" ]
stackoverflow_0001373255_exception_python_python_2.x_syntax.txt
Q: Number Sequence in MySQL In Python if I wanted a sequence from 0 - 9 (inclusive) I would use xrange(0,10) . Is there a way I can do this in MySQL? A: Since there is no such thing as xrange, one could use a separate table stored with integer (as previously answered), or just make a stored procedure to do the job:...
Number Sequence in MySQL
In Python if I wanted a sequence from 0 - 9 (inclusive) I would use xrange(0,10) . Is there a way I can do this in MySQL?
[ "Since there is no such thing as xrange, one could use a separate table stored with integer (as previously answered), or just make a stored procedure to do the job:\nDROP PROCEDURE IF EXISTS xrange;\nDELIMITER //\nCREATE PROCEDURE xrange(x INT, y INT)\nBEGIN\n DECLARE i INT DEFAULT x;\n CREATE TEMPORARY TABLE xra...
[ 2, 0, 0, 0 ]
[]
[]
[ "mysql", "python", "sequence", "sql", "xrange" ]
stackoverflow_0002495487_mysql_python_sequence_sql_xrange.txt
Q: How can I programmatically determine (in Python) when someone connects into my windows 7 machine via RDP? This doesn't need to be a real time solution, but are there some log files or system messages that could be read to identify periods of time where someone was connected via RDP to a Windows 7 machine? I'm buil...
How can I programmatically determine (in Python) when someone connects into my windows 7 machine via RDP?
This doesn't need to be a real time solution, but are there some log files or system messages that could be read to identify periods of time where someone was connected via RDP to a Windows 7 machine? I'm building a watchdog script for a computer which will be deployed in a remote place and would like to add this metri...
[ "Run with os.system or subprocess module\nC:\\> netstat -n | find \":3389 \"\n\nTCP x.x.x.x:3389 y.y.y.y:zzz ESTABLISHED\n\nWhere, x.x.x.x is own IP and y.y.y.y is remote IP, and zzz is remote port.\n", "If you look at the Event viewer and the tab Security you can find when people login/logout there. Not sure if...
[ 3, 1 ]
[]
[]
[ "connection", "detection", "logging", "python", "rdp" ]
stackoverflow_0002514450_connection_detection_logging_python_rdp.txt
Q: Count warnings in Python 2.4 I've got some tests that need to count the number of warnings raised by a function. In Python 2.6 this is simple, using with warnings.catch_warnings(record=True) as warn: ... self.assertEquals(len(warn), 2) Unfortunately, with is not available in Python 2.4, so what else could...
Count warnings in Python 2.4
I've got some tests that need to count the number of warnings raised by a function. In Python 2.6 this is simple, using with warnings.catch_warnings(record=True) as warn: ... self.assertEquals(len(warn), 2) Unfortunately, with is not available in Python 2.4, so what else could I use? I can't simply check if th...
[ "I was going to suggest the same workaround as Ignacio, a bit more complete example of testing code:\nimport warnings\n\ndef setup_warning_catcher():\n \"\"\" Wrap warnings.showwarning with code that records warnings. \"\"\"\n\n\n caught_warnings = []\n original_showwarning = warnings.showwarning\n\n de...
[ 6, 3 ]
[]
[]
[ "python", "python_2.4", "warnings" ]
stackoverflow_0002324820_python_python_2.4_warnings.txt
Q: how to count all distinct records in many-to-many relations in django ORM? class Project(models.Model): categories = models.ManyToManyField(Category) class Category(models.Model): name = models.CharField() now, i make some queryset: query = Project.objects.filter(id__in=[1,2,3,4]) and i like to get list of...
how to count all distinct records in many-to-many relations in django ORM?
class Project(models.Model): categories = models.ManyToManyField(Category) class Category(models.Model): name = models.CharField() now, i make some queryset: query = Project.objects.filter(id__in=[1,2,3,4]) and i like to get list of all distinct categories in this queryset with count of projects with refering t...
[ "Category.objects.filter(project__in=query).annotate(Count('project'))\n\n" ]
[ 1 ]
[]
[]
[ "django", "orm", "python" ]
stackoverflow_0002514910_django_orm_python.txt
Q: How do I create new xml from ElementTree? Bit of a beginner question here: Say I have a block of xml: <root> <district> <house><room><door/><room></house> </district> <district> <street> <house>and so on</house> </street> etc. With ElementTree I can do: houses=doc.findall(".//house") to select all th...
How do I create new xml from ElementTree?
Bit of a beginner question here: Say I have a block of xml: <root> <district> <house><room><door/><room></house> </district> <district> <street> <house>and so on</house> </street> etc. With ElementTree I can do: houses=doc.findall(".//house") to select all the house nodes, regardless of their parent. What...
[ "You can call findall on the elements returned by the first findall:\n>>> doc = \"\"\"<root>\n... <district>\n... <house><room><door/></room></house>\n... </district>\n... <district>\n... <street>\n... <house>and so on</house>\n... </street>\n... </district>\n... </root>\"\"\"\n>>>\n>>> from xml.etree ...
[ 2 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0002515253_elementtree_python_xml.txt
Q: PRTime to datetime in Python I am writing a script that is retrieving information from file places.sqlite (history) and realized that it stores the time in the PRTime format. Is there a method available in Python which could convert this date time or do I have to make it myself? A: PRTime is the number of micros...
PRTime to datetime in Python
I am writing a script that is retrieving information from file places.sqlite (history) and realized that it stores the time in the PRTime format. Is there a method available in Python which could convert this date time or do I have to make it myself?
[ "PRTime is the number of microseconds since 1970-01-01 (see https://developer.mozilla.org/en/PRTime), so just do this to get UTC time:\ndatetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=pr_time)\n\nFor example,\nprint datetime.datetime(1970, 1, 1) + datetime.timedelta(microseconds=time.time()*1000*100...
[ 3, 1 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0002515782_datetime_python.txt
Q: Eclipse PyDev: setting breakpoints in site-packages source I am debugging a problem in Django with Pydev. I can set breakpoint in my django project code with out a problem. However I can't set breakpoints in the Django library source code (in site-packages). The PyDev debugger user interface in this case simply ...
Eclipse PyDev: setting breakpoints in site-packages source
I am debugging a problem in Django with Pydev. I can set breakpoint in my django project code with out a problem. However I can't set breakpoints in the Django library source code (in site-packages). The PyDev debugger user interface in this case simply does nothing when I click to set the breakpoint and does not bre...
[ "Have you imported the Django source as a project? To do that you just create a new PyDev project and set it's location to the Django source folder.\n", "Hey, this is timely! Eric Moritz just announced the release of an interesting new way to debug views using pdb called django-viewtools.\n", "You might try ins...
[ 5, 1, 0, 0 ]
[]
[]
[ "django", "eclipse", "pydev", "python" ]
stackoverflow_0000558999_django_eclipse_pydev_python.txt
Q: Keeping track of user habits and activities? - Django I was working on a project a few months ago, and had the need to implement an award system. Similar to StackOverflow's badge system. Badges I might have not implemented it in the best possible way, and I am curious what your say in it would be. What would a go...
Keeping track of user habits and activities? - Django
I was working on a project a few months ago, and had the need to implement an award system. Similar to StackOverflow's badge system. Badges I might have not implemented it in the best possible way, and I am curious what your say in it would be. What would a good way to track user activities, needed for badge awarding ...
[ "I don't think is as complicated as you think. I highly doubt that SO calculates badges with some kind of user activity log (although technically the entire database is a user activity log). When I look at the lists of badges, I don't see anything that can't be implemented by running a SQL select query.\nSome of ...
[ 2, 0 ]
[]
[]
[ "badge", "django", "logging", "python", "sql" ]
stackoverflow_0002510264_badge_django_logging_python_sql.txt
Q: Python string comparison I have a python function that makes a subprocess call to a shell script that outputs 'true' or 'false'. I'm storing the output from subprocess.communicate() and trying to do return output == 'true' but it returns False every time. I'm not too familiar with python, but reading about strin...
Python string comparison
I have a python function that makes a subprocess call to a shell script that outputs 'true' or 'false'. I'm storing the output from subprocess.communicate() and trying to do return output == 'true' but it returns False every time. I'm not too familiar with python, but reading about string comparisons says you can com...
[ "Are you sure that there isn't a terminating line feed character, making your string contain \"true\\n\"? That seems likely.\nYou could try return isdeployed.startswith(\"true\"), or some stripping.\n", "Have you tried to call \nisdeployed.strip()\n\nbefore the comparision\n" ]
[ 8, 6 ]
[]
[]
[ "compare", "python", "string" ]
stackoverflow_0002516787_compare_python_string.txt
Q: Loop over a file and write the next line if a condition is met Having a hard time fixing this or finding any good hints about it. I'm trying to loop over one file, modify each line slightly, and then loop over a different file. If the line in the second file starts with the line from the first then the following ...
Loop over a file and write the next line if a condition is met
Having a hard time fixing this or finding any good hints about it. I'm trying to loop over one file, modify each line slightly, and then loop over a different file. If the line in the second file starts with the line from the first then the following line in the second file should be written to a third file. with ope...
[ "Here's a mostly flattened implementation. Depending on how many hits you're going to get for each ID, and how many entries there are in 'seqres' you could redesign it.\n# Extract the IDs in the desired format and cache them\nids = [ x.lower()[0:4]+'_'+x[4] for x in open('ids.txt','rU')]\nids = set(ids)\n\n# Create...
[ 2, 2, 1, 1, 0 ]
[]
[]
[ "file_io", "iterator", "python", "string" ]
stackoverflow_0002513847_file_io_iterator_python_string.txt
Q: Perl for a Python programmer I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around. My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as ...
Perl for a Python programmer
I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around. My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as contrasted with Pythonic) way of d...
[ "One area where Perl is more \"convenient\" is using it for one liners. Python can be used to produced one liners, but often its \"clunky\" (or ugly). Note that Perl is renowned for its \"terseness\" or \"short and concise\", often at the expense of readability. So coming from Python, you have to learn to get used ...
[ 17, 15, 11, 4, 4, 3 ]
[]
[]
[ "perl", "python" ]
stackoverflow_0002515814_perl_python.txt
Q: Get information about a function in python, looking at source code the following code comes from the matplotlib gallery: #!/usr/bin/env python from pylab import * x = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) I am new to python, a...
Get information about a function in python, looking at source code
the following code comes from the matplotlib gallery: #!/usr/bin/env python from pylab import * x = array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) y = array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]) I am new to python, and would like to change the content of x and y from an input file. I hav...
[ "As to your 1. that's due to bad habits of the person giving you that program. It should have been:\n#!/usr/bin/env python\nimport pylab\n\nx = pylab.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5])\ny = pylab.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68])\n\nhelp(pylab.array)\n\nor\n#!/usr...
[ 2, 1, 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0002516034_numpy_python.txt
Q: Downloading RSS using python I have list of 200 rss feeds, which I have to downloading. It's continuous process - I have to download every post, nothing can be missing, but also no duplicates. So best practice should be remember last update of feed and control it for change in x-hour interval? And how to handle if...
Downloading RSS using python
I have list of 200 rss feeds, which I have to downloading. It's continuous process - I have to download every post, nothing can be missing, but also no duplicates. So best practice should be remember last update of feed and control it for change in x-hour interval? And how to handle if downloader will be restarted? So ...
[ "Typically this is what you'd want to do:\n\nFetch the feeds periodically and parse them using the universal feedparser and store the entries somewhere.\nUse ETags and IfModified headers when fetching feeds to avoid parsing feeds that have not changed since your last fetch. you'll have to maintain Etags and Ifmodif...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0002517648_python.txt
Q: Weird Cron ls Behavior I have a Python script that is running a few ls commands. This script runs under cron all day. I use awk to write out the column that the filename is in when ls -l is executed. When I run the script via command line the output looks like this -rw-rw---- 1 mysql adm 141 2010-03-25 08:56...
Weird Cron ls Behavior
I have a Python script that is running a few ls commands. This script runs under cron all day. I use awk to write out the column that the filename is in when ls -l is executed. When I run the script via command line the output looks like this -rw-rw---- 1 mysql adm 141 2010-03-25 08:56 mysql-bin.000485 -rw-rw----...
[ "Problem is with different locales between your account and root. You can change them temporarily by:\n$ LC_ALL=\"locale name\" your-script\n\n", "If you're on GNU ls, you can pass --time-style=long-iso. More formats are here.\n" ]
[ 3, 3 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0002517961_cron_python.txt
Q: How to convert an UTF string with scandinavian characters to ASCII? I would like to convert this string foo_utf = u'nästy chäräctörs with å and co.' # unicode into this foo_ascii = 'nästy chäräctörs with å and co.' # ASCII . Any idea how to do this in Python (2.6)? I found unicodedata module but I have no idea h...
How to convert an UTF string with scandinavian characters to ASCII?
I would like to convert this string foo_utf = u'nästy chäräctörs with å and co.' # unicode into this foo_ascii = 'nästy chäräctörs with å and co.' # ASCII . Any idea how to do this in Python (2.6)? I found unicodedata module but I have no idea how to do the transformation.
[ "I don't think you can. Those \"nästy chäräctörs\" can't be encoded as ASCII, so you'll have to pick a different encoding (UTF-8 or Latin-1 or Windows-1252 or something).\n", "Try the encode method of string.\n>>> u'nästy chäräctörs with å and co.'.encode('latin-1')\n'n\\xe4sty ch\\xe4r\\xe4ct\\xf6rs with \\xe5 ...
[ 4, 3, 3, 2, 2 ]
[]
[]
[ "ascii", "python", "utf" ]
stackoverflow_0002518005_ascii_python_utf.txt
Q: Python, a smarter way of string to integer conversion I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 . class Phone(): def __init__(self,input): self.phone = input def __str__(self): return self.phone #convert to integer. d...
Python, a smarter way of string to integer conversion
I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 . class Phone(): def __init__(self,input): self.phone = input def __str__(self): return self.phone #convert to integer. def to_int(self): return int((self.phone).replace(" ...
[ "p = \"0(532) 222 22 22\"\nprint ''.join([x for x in p if x.isdigit()])\n\nNote that you'll \"lose\" the leading zero if you want to convert it to int (like you suggested in the title). If you want to do that, just wrap the above in a int() call. A telephone number does make more sense as a string though (in my opi...
[ 9, 6, 1 ]
[ "SilentGhost: dis.dis does demonstrate underlying conceptual / executional complexity. after all, the OP complained about the original replacement chain being too ‘clumsy’, not too ‘slow’. \ni recommend against using regular expressions where not inevitable; they just add conceptual overhead and a speed penalty oth...
[ -1 ]
[ "integer", "python", "string", "type_conversion" ]
stackoverflow_0002499966_integer_python_string_type_conversion.txt
Q: Counting removed items in a Set in Python Given two sets a = [5,3,4,1,2,6,7] b = [1,2,4,9] c = set(a) - set(b) # c -> [5,3,6,7] is it possible to count how many items were removed from set 'a' ? A: How about len(set(a)) - len(c)? Edit: len(a) could be incorrect if a contains duplicates. A: Assuming lack of du...
Counting removed items in a Set in Python
Given two sets a = [5,3,4,1,2,6,7] b = [1,2,4,9] c = set(a) - set(b) # c -> [5,3,6,7] is it possible to count how many items were removed from set 'a' ?
[ "How about len(set(a)) - len(c)?\nEdit: len(a) could be incorrect if a contains duplicates.\n", "Assuming lack of duplicates:\nlen(a)-len(c)\notherwise try:\nlen(set(a)) - len(c)\n", "there might be a more efficient way, but\n len(set(a)-set(c))\n\nwill work\n" ]
[ 6, 3, 3 ]
[ "a = [5,3,4,1,2,6,7] \nb = [1,2,4,9] \nc = set(a) - set(b)\n\nprint len(c)\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0002518711_python.txt
Q: Python's mechanize proxy support I have a question about python mechanize's proxy support. I'm making some web client script, and I would like to insert proxy support function into my script. For example, if I have: params = urllib.urlencode({'id':id, 'passwd':pw}) rq = mechanize.Request('http://www.example.com', ...
Python's mechanize proxy support
I have a question about python mechanize's proxy support. I'm making some web client script, and I would like to insert proxy support function into my script. For example, if I have: params = urllib.urlencode({'id':id, 'passwd':pw}) rq = mechanize.Request('http://www.example.com', params) rs = mechanize.urlopen(rq) H...
[ "I'm not sure whether that help or not but you can set proxy settings on mechanize proxy browser.\nbr = Browser()\n# Explicitly configure proxies (Browser will attempt to set good defaults).\n# Note the userinfo (\"joe:password@\") and port number (\":3128\") are optional.\nbr.set_proxies({\"http\": \"joe:password@...
[ 31, 9 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0001997894_mechanize_python.txt
Q: best way to implement a deck for a card game in python What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable? For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits an...
best way to implement a deck for a card game in python
What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable? For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits and values of specific cards, and how would these names and va...
[ "Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human.\n>>> import random\n>>> import itertools\n>>> SUITS = 'cdhs'\n>>> RANKS = '23456789TJQKA'\n>>> DECK = tuple(''.join(card) for card in itertools.p...
[ 26, 7, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0002518753_python.txt
Q: Storing simulation results in a persistent manner for Python? Background: I'm running multiple simulations on a set of data. For each session, I'm allocating projects to students. The difference between each session is that I'm randomising the order of the students such that all the students get a shot at being as...
Storing simulation results in a persistent manner for Python?
Background: I'm running multiple simulations on a set of data. For each session, I'm allocating projects to students. The difference between each session is that I'm randomising the order of the students such that all the students get a shot at being assigned a project they want. I was writing out some of the allocatio...
[ "A two-dimension display of data is a Relational database table with two keys.\nIn your example, the Student Key and the Session Key.\nA \"Composite key\" is a piece of noise that you can ignore. It isn't helpful and isn't necessary. A composite key does not solve any problems well and create many difficulties. ...
[ 3, 1, 0 ]
[]
[]
[ "persistence", "python", "sqlalchemy" ]
stackoverflow_0002512609_persistence_python_sqlalchemy.txt
Q: How do I mock a class property with mox? I have a class: class MyClass(object): @property def myproperty(self): return 'hello' Using mox and py.test, how do I mock out myproperty? I've tried: mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty = 'goodbye' and mock.StubOutWithMock(mycla...
How do I mock a class property with mox?
I have a class: class MyClass(object): @property def myproperty(self): return 'hello' Using mox and py.test, how do I mock out myproperty? I've tried: mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty = 'goodbye' and mock.StubOutWithMock(myclass, 'myproperty') myclass.myproperty.AndReturn...
[ "When stubbing out class attributes mox uses setattr. Thus\nmock.StubOutWithMock(myinstance, 'myproperty')\nmyinstance.myproperty = 'goodbye'\n\nis equivalent to\n# Save old attribute so it can be replaced during teardown\nsaved = getattr(myinstance, 'myproperty')\n# Replace the existing attribute with a mock\nmock...
[ 9, 3 ]
[]
[]
[ "mocking", "mox", "properties", "python" ]
stackoverflow_0002512453_mocking_mox_properties_python.txt
Q: Creating Read-only logs with python I am writing a python script that needs to make a log entry whenever it's invoked. The log created by the script must not be changeable by the user (except root) who invoked the script. I tried the syslog module and while this does exactly what I want in terms of file permission...
Creating Read-only logs with python
I am writing a python script that needs to make a log entry whenever it's invoked. The log created by the script must not be changeable by the user (except root) who invoked the script. I tried the syslog module and while this does exactly what I want in terms of file permissions, I need to be able to put the resulting...
[ "I see you are on linux,\nDepending on which filesystem you are using, you may be able to use the chattr command. You can make files that are append only by setting the a attribute\n", "Run your script with setuid root.\n" ]
[ 1, 0 ]
[]
[]
[ "linux", "logging", "permissions", "python" ]
stackoverflow_0002519706_linux_logging_permissions_python.txt
Q: Detect user logout / shutdown in Python / GTK under Linux - SIGTERM/HUP not received OK this is presumably a hard one, I've got an pyGTK application that has random crashes due to X Window errors that I can't catch/control. So I created a wrapper that restarts the app as soon as it detects a crash, now comes the p...
Detect user logout / shutdown in Python / GTK under Linux - SIGTERM/HUP not received
OK this is presumably a hard one, I've got an pyGTK application that has random crashes due to X Window errors that I can't catch/control. So I created a wrapper that restarts the app as soon as it detects a crash, now comes the problem, when the user logs out or shuts down the system, the app exits with status 1. But ...
[ "OK, I finally found the solution :)\nYou simply can't rely on signals in this case. You have to connect to the Desktop Session in order to get notified that a logout is going to happen.\nimport gnome.ui\n\ngnome.program_init('Program', self.version) # This is going to trigger a warning that program name has been s...
[ 2, 0 ]
[]
[]
[ "gtk", "linux", "pygtk", "python", "sigterm" ]
stackoverflow_0002490166_gtk_linux_pygtk_python_sigterm.txt