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:
How do I find userid by login (Python under *NIX)
I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login?
I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?
A:
You might want to have a look... | How do I find userid by login (Python under *NIX) | I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login?
I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?
| [
"You might want to have a look at the pwd module in the python stdlib, for example:\nimport pwd\npw = pwd.getpwnam(\"nobody\")\nuid = pw.pw_uid\n\nit uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is... | [
21,
5
] | [] | [] | [
"linux",
"process_management",
"python",
"unix"
] | stackoverflow_0000294470_linux_process_management_python_unix.txt |
Q:
Flattening one-to-many relationship in Django
I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:
class Book(models.Model):
name = models.CharField(max_length=64)
class Recipe(models.Model):
book = models.ForeignKey(... | Flattening one-to-many relationship in Django | I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:
class Book(models.Model):
name = models.CharField(max_length=64)
class Recipe(models.Model):
book = models.ForeignKey(Book)
name = models.CharField(max_length=64)
c... | [
"Actually, it looks like there's a better approach using filter:\nmy_book = Book.objects.get(pk=1)\nall_ingredients = Ingredient.objects.filter(recipe__book=my_book)\n\n",
"To print each recipe and its ingredients:\nmybook = Book.objects.get(name=\"Jason's Cookbook\")\nfor recipe in mybook.recipe_set.all():\n ... | [
11,
1
] | [] | [] | [
"django",
"flatten",
"list",
"python"
] | stackoverflow_0000294712_django_flatten_list_python.txt |
Q:
Django multiselect checkboxes
I have a list of objects, each with it's own checkbox, where the user can select multiple of these. The list is a result of a query.
How can I mark in the view which checkboxes are already selected? There doesn't seem to be an in operator in the template language.
I want something alo... | Django multiselect checkboxes | I have a list of objects, each with it's own checkbox, where the user can select multiple of these. The list is a result of a query.
How can I mark in the view which checkboxes are already selected? There doesn't seem to be an in operator in the template language.
I want something along the lines of:
<input {% if id in... | [
"You could use a templatetag like the one in this snippet comments:\nhttp://www.djangosnippets.org/snippets/177/\n@register.filter\ndef in_list(value,arg):\n return value in arg\n\nTo be used in templates:\nThe item is \n{% if item|in_list:list %} \n in list \n{% else %} \n not in list\n{% endif %}\n\nNot ... | [
0
] | [] | [] | [
"checkbox",
"django",
"django_templates",
"python"
] | stackoverflow_0000286558_checkbox_django_django_templates_python.txt |
Q:
Inplace substitution from ConfigParser
I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read
self.post.id
from a .cfg file and use it as a variable in the script. How do I achieve this?
I suppose I was un... | Inplace substitution from ConfigParser | I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read
self.post.id
from a .cfg file and use it as a variable in the script. How do I achieve this?
I suppose I was unclear in my query. The .cfg file looks somet... | [
"test.ini:\n[head]\nvar: self.post.id\n\npython:\nimport ConfigParser\n\nclass Test:\n def __init__(self):\n self.post = TestPost(5)\n def getPost(self):\n config = ConfigParser.ConfigParser()\n config.read('/path/to/test.ini')\n newvar = config.get('head', 'var')\n print eval(newvar) \n\... | [
5,
0
] | [] | [] | [
"configuration_files",
"python"
] | stackoverflow_0000295028_configuration_files_python.txt |
Q:
How do I remove a specific number of files using python (version 2.5)?
I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should ... | How do I remove a specific number of files using python (version 2.5)? | I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of... | [
"It sounds like what you really want is a temp file:\nhttp://docs.python.org/library/tempfile.html\n",
"It is perfectly acceptable to have a 'cleanup()' function that you call at the end of your script, which will call 'os.remove()' on your files.\n",
"Just call os.remove(\"path/to/file\"). For example, to remo... | [
4,
0,
-1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0000296490_file_python.txt |
Q:
Which is more efficient in Python: standard imports or contextual imports?
I apologize in advance if this question seems remedial.
Which would be considered more efficient in Python:
Standard import
import logging
try:
...some code...
exception Exception, e:
logging.error(e)
...or...
Contextual import
try:
... | Which is more efficient in Python: standard imports or contextual imports? | I apologize in advance if this question seems remedial.
Which would be considered more efficient in Python:
Standard import
import logging
try:
...some code...
exception Exception, e:
logging.error(e)
...or...
Contextual import
try:
...some code...
exception Exception, e:
import logging
logging.error(e)
| [
"Contextual imports are technically more efficient, but I think they can create other problems.\nLater, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any... | [
6,
3,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000296270_python.txt |
Q:
Pycurl WRITEDATA WRITEFUNCTION collision/crash
How do I turnoff WRITEFUNCTION and WRITEDATA?
Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string.
To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (... | Pycurl WRITEDATA WRITEFUNCTION collision/crash | How do I turnoff WRITEFUNCTION and WRITEDATA?
Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string.
To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (pycurl.WRITEFUNCTION, 0) which cause problems. Int i... | [
"using the writefunction, instead of turning it off would save you a lot off trouble. you might want to rewrite your pageAsString by utilizing WRITEFUNCTION..\nas an example: \nfrom cStringIO import StringIO\nc = pycurl.Curl()\nbuffer = StringIO()\nc.setopt(pycurl.WRITEFUNCTION, buffer.write)\nc.setopt(pycurl.URL, ... | [
2
] | [] | [] | [
"crash",
"libcurl",
"pycurl",
"python"
] | stackoverflow_0000294960_crash_libcurl_pycurl_python.txt |
Q:
how do i use python libraries in C++?
I want to use the nltk libraries in c++.
Is there a glue language/mechanism I can use to do this?
Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.
Thanks
A:
Although calling c++ libs from python is more nor... | how do i use python libraries in C++? | I want to use the nltk libraries in c++.
Is there a glue language/mechanism I can use to do this?
Reason:
I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time.
Thanks
| [
"Although calling c++ libs from python is more normal - you can call a python module from c++ by bascially calling the python intepreter and have it execute the python source.\nThis is called embedding\nAlternatively the boost.python library makes it very easy.\n",
"You can also try the Boost.Python library; whic... | [
17,
14,
2,
1
] | [] | [] | [
"c++",
"nltk",
"python"
] | stackoverflow_0000297112_c++_nltk_python.txt |
Q:
How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately
I have a port scanning application that uses work queues and threads.
It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i... | How do I count bytecodes in Python so I can modify sys.setcheckinterval appropriately | I have a port scanning application that uses work queues and threads.
It uses simple TCP connections and spends a lot of time waiting for packets to come back (up to half a second). Thus the threads don't need to fully execute (i.e. first half sends a packet, context switch, does stuff, comes back to thread which has n... | [
"For higher level (method, class) wise, dis module should help.\nBut if one needs finer grain, tracing will be unavoidable. Tracing does operate line by line basis but explained here is a great hack to dive deeper at the bytecode level. Hats off to Ned Batchelder.\n",
"Reasoning about a system of this complexity ... | [
3,
2,
1
] | [] | [] | [
"internals",
"multithreading",
"performance",
"python"
] | stackoverflow_0000294963_internals_multithreading_performance_python.txt |
Q:
Recommended data format for describing the rules of chess
I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky ... | Recommended data format for describing the rules of chess | I'm going to be writing a chess server and one or more clients for chess and I want to describe the rules of chess (e.g. allowable moves based on game state, rules for when a game is complete) in a programming language independant way. This is a bit tricky since some of the chess rules (e.g. King Castling, en passent, ... | [
"Let's think. We're describing objects (locations and pieces) with states and behaviors. We need to note a current state and an ever-changing set of allowed state changes from a current state.\nThis is programming. You don't want some \"meta-language\" that you can then parse in a regular programming language. ... | [
4,
2,
2,
2,
2,
2,
0,
0,
0
] | [] | [] | [
"c#",
"chess",
"dataformat",
"java",
"python"
] | stackoverflow_0000194289_c#_chess_dataformat_java_python.txt |
Q:
Formatting dict.items() for wxPython
I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like
[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
I know dictionary.items() is a list of tuples, but... | Formatting dict.items() for wxPython | I have a text box in wxPython that takes the output of dictionary.items() and displays it to the user as items are added to the dictionary. However, the raw data is very ugly, looking like
[(u'BC',45)
(u'CHM',25)
(u'CPM',30)]
I know dictionary.items() is a list of tuples, but I can't seem to figure out how to make a ... | [
"There is no built-in dictionary method that would return your desired result.\nYou can, however, achieve your goal by creating a helper function that will format the dictionary, e.g.:\ndef getNiceDictRepr(aDict):\n return '\\n'.join('%s %s' % t for t in aDict.iteritems())\n\nThis will produce your exact desired... | [
5,
0,
0,
0,
0,
0
] | [] | [] | [
"dictionary",
"python",
"wxpython"
] | stackoverflow_0000237859_dictionary_python_wxpython.txt |
Q:
python (jython) archiving library
Is there a neat archiving library that automatically handles archiving a folder or directories for you out there?
I am using Jython, so Java libs are also open for use.
-UPDATE-
Also Im looking for timestamp archiving. ie
archive-dir/2008/11/16/zipfilebypreference.zip
then the ne... | python (jython) archiving library | Is there a neat archiving library that automatically handles archiving a folder or directories for you out there?
I am using Jython, so Java libs are also open for use.
-UPDATE-
Also Im looking for timestamp archiving. ie
archive-dir/2008/11/16/zipfilebypreference.zip
then the next day call it again and it creates ano... | [
"You have either the:\n\ngzip library used here in a Jython servlet: \n\n \nimport javax.servlet.http.HttpServlet\n\nimport cStringIO\nimport gzip\nimport string\n\ndef compressBuf(buf):\n zbuf = cStringIO.StringIO()\n zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 6)\n zfile.writ... | [
3,
1
] | [] | [] | [
"archive",
"java",
"jython",
"python"
] | stackoverflow_0000298004_archive_java_jython_python.txt |
Q:
Python MySQL Statement returning Error
hey, I'm very new to all this so please excuse stupidity :)
import os
import MySQLdb
import time
db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace")
cursor = db.cursor()
tailoutputfile = os.popen('tail -f syslog.log')
while 1:
x = ... | Python MySQL Statement returning Error | hey, I'm very new to all this so please excuse stupidity :)
import os
import MySQLdb
import time
db = MySQLdb.connect(host="localhost", user="root", passwd="********", db="workspace")
cursor = db.cursor()
tailoutputfile = os.popen('tail -f syslog.log')
while 1:
x = tailoutputfile.readline()
if len(x... | [
"As pointed out, you're failing to copy the Python variable values into the query, only their names, which mean nothing to MySQL.\nHowever the direct string concatenation option:\ncursor.execute(\"INSERT INTO releases (date, cat, name) VALUES ('%s', '%s', '%s')\" % (timestring, y[4], y[7]))\n\nis dangerous and shou... | [
10,
4,
1
] | [] | [] | [
"python",
"sql"
] | stackoverflow_0000257563_python_sql.txt |
Q:
How to make the keywords recognizable in simpleparse?
I've been trying to create a parser using simpleparse. I've defined the grammar like this:
<w> := [ \n]*
statement_list := statement,(w,statement)?
statement := "MOVE",w,word,w,"TO",w,(word,w)+
word := [A-Za-z],[A-Za-z0-9]*,([-]+,[A-Za-z0-9]+)*
Now if I try to... | How to make the keywords recognizable in simpleparse? | I've been trying to create a parser using simpleparse. I've defined the grammar like this:
<w> := [ \n]*
statement_list := statement,(w,statement)?
statement := "MOVE",w,word,w,"TO",w,(word,w)+
word := [A-Za-z],[A-Za-z0-9]*,([-]+,[A-Za-z0-9]+)*
Now if I try to parse a string
MOVE ABC-DEF TO ABC
MOVE DDD TO XXX
The se... | [
"The grammar is currently ambiguous. On paper you cannot parse if \"MOVE A TO B MOVE C TO D\" is two statements, or one statement with particular badly named destinations.\nYou have two answers. You may like neither.\n\nYou explicitly make your WORD not match any reserved word. That is, you specifically disallo... | [
2
] | [] | [] | [
"parsing",
"python"
] | stackoverflow_0000298034_parsing_python.txt |
Q:
Python xml.dom.minidom.parse() function ignores DTDs
I have the following Python code:
import xml.dom.minidom
import xml.parsers.expat
try:
domTree = ml.dom.minidom.parse(myXMLFileName)
except xml.parsers.expat.ExpatError, e:
return e.args[0]
which I am using to parse an XML file. Although it quite hap... | Python xml.dom.minidom.parse() function ignores DTDs | I have the following Python code:
import xml.dom.minidom
import xml.parsers.expat
try:
domTree = ml.dom.minidom.parse(myXMLFileName)
except xml.parsers.expat.ExpatError, e:
return e.args[0]
which I am using to parse an XML file. Although it quite happily spots simple XML errors like mismatched tags, it comp... | [
"See this question - the accepted answer is to use lxml validation.\n",
"Just by way of explanation: Python xml.dom.minidom and xml.sax use the expat parser by default, which is a non-validating parser. It may read the DTD in order to do entity replacement, but it won't validate against the DTD.\ngimel and Tim r... | [
5,
3,
2,
1,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0000298782_python_xml.txt |
Q:
How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?
I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (locate... | How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line? | I am familiar with using the os.system to run from the command line. However, I would like to be able to run a jar file from inside of a specific folder, eg. my 'test' folder. This is because my jar (located in my 'test' folder) requires a file inside of my 'test' folder. So, how would I write a function in my script t... | [
"Here is a small script to get you started. There are ways to make it \"better\", but not knowing the full scope of what you are trying to accomplish this should be sufficient.\nimport os\n\nif __name__ == \"__main__\":\n startingDir = os.getcwd() # save our current directory\n testDir = \"\\\\test\" # note tha... | [
8,
1
] | [] | [] | [
"python"
] | stackoverflow_0000299249_python.txt |
Q:
Calling Java (or python or perl) from a PHP script
I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up ... | Calling Java (or python or perl) from a PHP script | I've been trying to build a simple prototype application in Django, and am reaching the point of giving up, sadly, as it's just too complicated (I know it would be worth it in the long-run, but I really just don't have enough time available -- I need something up and running in a few days). So, I'm now thinking of goin... | [
"\"where I just can't figure out what model I need to produce the HTML form I want, which seems such a basic thing that I fear for my chances of doing anything more complex\" \nCommon problem.\nRoot cause: Too much programming.\nSolution. Do less programming. Seriously.\nDefine the Django model. Use the default... | [
4,
2
] | [] | [] | [
"dynamic_linking",
"java",
"php",
"python"
] | stackoverflow_0000299913_dynamic_linking_java_php_python.txt |
Q:
Is it possible to bind an event against a menu instead of a menu item in wxPython?
Nothing to add
A:
Do you want an event when your menu is opened? Use EVT_MENU_OPEN(func) (wxMenuEvent). But it's not in particular precise. As the documentation says, it is only sent once if you open a menu. For another event you ... | Is it possible to bind an event against a menu instead of a menu item in wxPython? | Nothing to add
| [
"Do you want an event when your menu is opened? Use EVT_MENU_OPEN(func) (wxMenuEvent). But it's not in particular precise. As the documentation says, it is only sent once if you open a menu. For another event you have to close it and open another menu again. I.e in between, you can open other menus (by hovering oth... | [
3
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0000300032_python_wxpython.txt |
Q:
Looping in Django forms
I've just started building a prototype application in Django. I started out by working through the Django app tutorial on the Django site which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions:
I want to put a loop in... | Looping in Django forms | I've just started building a prototype application in Django. I started out by working through the Django app tutorial on the Django site which was pretty helpful, and gave me what I needed to get started. Now I have a couple of what I hope are very simple questions:
I want to put a loop into views.py, looping over a s... | [
"You need to look at the Django forms.\nYou should never build your own form like that.\nYou should declare a Form class which includes a ChoiceField and provide the domain of choices to that field. Everything will happen pretty much automatically from there.\nThe choices, BTW, should be defined in your Model as t... | [
7,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000298446_django_python.txt |
Q:
Why is fuse not using the class supplied in file_class
I have a python fuse project based on the Xmp example in the fuse documentation. I have included a small piece of the code to show how this works. For some reason get_file does get called and the class gets created, but instead of fuse calling .read() on the c... | Why is fuse not using the class supplied in file_class | I have a python fuse project based on the Xmp example in the fuse documentation. I have included a small piece of the code to show how this works. For some reason get_file does get called and the class gets created, but instead of fuse calling .read() on the class from get_file (file_class) fuse keeps calling Dstorage.... | [
"Looking at the code of the Fuse class (which is a maze of twisty little passages creating method proxies), I see this bit (which is a closure used to create a setter inside Fuse.MethodProxy._add_class_type, line 865):\n def setter(self, xcls):\n\n setattr(self, type + '_class', xcls)\n\n ... | [
1
] | [] | [] | [
"fuse",
"python"
] | stackoverflow_0000300047_fuse_python.txt |
Q:
loadComponentFromURL falls over and dies, howto do CPR?
Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automati... | loadComponentFromURL falls over and dies, howto do CPR? | Well I testing my jython program, that does some neat [".xls", ".doc", ".rtf", ".tif", ".tiff", ".pdf" files] -> pdf (intermediary file) -> tif (final output) conversion using Open Office. We moved away from MS Office due to the problems we had with automation. Now it seems we have knocked down many bottles related t... | [
"OpenOffice.org has a \"-headless\" parameter to run it without a GUI. I'm not sure this actually frees up all resources that would be spent on GUI. Here's how I run my server-side headless instance:\nsoffice -headless -accept=\"socket,port=1234;urp\" -display :25\n\nI can't tell what's causing the stalling problem... | [
1,
1
] | [] | [] | [
"java",
"jython",
"openoffice.org",
"python"
] | stackoverflow_0000301239_java_jython_openoffice.org_python.txt |
Q:
Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states?
I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my p... | Does anyone know of a widget for a desktop toolkit(GTK, Qt, WX) for displaying a map of US states? | I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually. GTK is my personal preference, but at this point I'd settle for just about anything. The application itself will b... | [
"You can use QGraphicsView in PyQt. Each state is a new QGraphicsItem, which is either a bitmap or a path object. You just need to provide the outlines (or bitmaps) and the positions of the states. \nIf you have SVGs of the states, you can use them, too.\nThere is no generally accepted canvas class for GTK+.\n",
... | [
2,
2,
1,
1,
0
] | [] | [] | [
"desktop",
"gtk",
"python",
"qt"
] | stackoverflow_0000112483_desktop_gtk_python_qt.txt |
Q:
How does Python handle classes being in separate files or are they all supposed to be in one file
I'm working on framework for testing some command line utilities. I want to create some classes to hold the different types of information more easily.
Python is fairly new to me so I'm not sure how you would handle... | How does Python handle classes being in separate files or are they all supposed to be in one file | I'm working on framework for testing some command line utilities. I want to create some classes to hold the different types of information more easily.
Python is fairly new to me so I'm not sure how you would handle this. Do you keep all your classes in one file with your main script or can you separate them into th... | [
"An answer from the duplicate question in the comments seems to answer my question. My understanding now is that you can add multiple classes to a separate file which would then be referred to as a module. Then you can import that module to use your classes.\n",
"\"What is the paradigm for how you create multip... | [
3,
2,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0000302729_oop_python.txt |
Q:
Can I Use Python to Make a Delete Button in a 'web page'
I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that w... | Can I Use Python to Make a Delete Button in a 'web page' | I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also cr... | [
"You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a \"Keep this page\" and a \"Delete this page.\" When you click either but... | [
1,
0,
0,
0
] | [] | [] | [
"browser",
"python",
"web_applications"
] | stackoverflow_0000256021_browser_python_web_applications.txt |
Q:
information seemingly coming out of mysqldb incorrectly, python django
In a latin-1 database i have '\222\222\223\225', when I try to pull this field from the django models I get back u'\u2019\u2019\u201c\u2022'.
from django.db import connection ... | information seemingly coming out of mysqldb incorrectly, python django | In a latin-1 database i have '\222\222\223\225', when I try to pull this field from the django models I get back u'\u2019\u2019\u201c\u2022'.
from django.db import connection ... | [
"A little browsing of already-asked questions would have led you to UTF-8 latin-1 conversion issues, which was asked and answered yesterday.\nBTW, I couldn't remember the exact title, so I just googled on django+'\\222\\222\\223\\225' and found it. Remember, kids, Google Is Your Friend (tm).\n",
"Django uses UTF-... | [
2,
0
] | [] | [] | [
"character_encoding",
"django",
"mysql",
"python"
] | stackoverflow_0000275541_character_encoding_django_mysql_python.txt |
Q:
scons : src and include dirs
can someone give a scons config file which allows the following structure
toplevel/
/src - .cc files
/include .h files
at top level I want the o and final exe.
A:
Here is one example of Sconscript file
env=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0... | scons : src and include dirs | can someone give a scons config file which allows the following structure
toplevel/
/src - .cc files
/include .h files
at top level I want the o and final exe.
| [
"Here is one example of Sconscript file\nenv=Environment(CPPPATH='/usr/include/glib-2.0/:/usr/lib/glib-2.0/include:inc',\n CPPDEFINES=[],\n LIBS=['glib-2.0']) \nenv.Program('runme', Glob('src/*.c'))\n\n(The environment line is not really necessary for the example, but I have it to incl... | [
7,
5,
4
] | [] | [] | [
"python",
"scons"
] | stackoverflow_0000302835_python_scons.txt |
Q:
Newbie Python Question about tuples
I am new to Python, and I'm working on writing some database code using the cx_Oracle module. In the cx_Oracle documentation they have a code example like this:
import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
... | Newbie Python Question about tuples | I am new to Python, and I'm working on writing some database code using the cx_Oracle module. In the cx_Oracle documentation they have a code example like this:
import sys
import cx_Oracle
connection = cx_Oracle.Connection("user/pw@tns")
cursor = connection.cursor()
try:
cursor.execute("select 1 / 0 from dual")
... | [
"error, = exc.args\n\nThis is a case of sequence unpacking.\nA more readable way to write the same, and the style I personally favor, is:\n[error] = exc.args\n\nThere are two bits required to understand the previous example:\n\nWhen the left hand side of an assignment is a recursive sequence of names, the value of ... | [
10,
5,
4
] | [] | [] | [
"cx_oracle",
"python",
"tuples"
] | stackoverflow_0000303664_cx_oracle_python_tuples.txt |
Q:
Template Lib (Engine) in Python running with Jython
Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).
A:
Have you tried Cheetah, I don't have direct experience running it under Jython but there seem to be some people that do.
A:
Jinja is ... | Template Lib (Engine) in Python running with Jython | Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).
| [
"Have you tried Cheetah, I don't have direct experience running it under Jython but there seem to be some people that do. \n",
"Jinja is pretty cool and seems to work on Jython.\n",
"Use StringTemplate, see http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf for details of why. There is nothing better, and... | [
2,
2,
1
] | [] | [] | [
"jython",
"python",
"template_engine"
] | stackoverflow_0000157313_jython_python_template_engine.txt |
Q:
Find all nodes from an XML using cElementTree
Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.
A:
You can use XPath paths on the findall method:
The 1.2 release supports simple
element location paths. In its
simplest form, a location path i... | Find all nodes from an XML using cElementTree | Is there a way to find all nodes in a xml tree using cElementTree? The findall method works only for specified tags.
| [
"You can use XPath paths on the findall method:\n\nThe 1.2 release supports simple\n element location paths. In its\n simplest form, a location path is one\n or more tag names, separated by\n slashes (/).\nYou can also use an asterisk (*)\n instead of a tag name, to match all\n elements at that level. For exa... | [
3,
1
] | [] | [] | [
"celementtree",
"python",
"search",
"xml"
] | stackoverflow_0000304216_celementtree_python_search_xml.txt |
Q:
Running Django with FastCGI or with mod_python
which would you recommend?
which is faster, reliable?
apache mod_python or nginx/lighttpd FastCGI?
A:
I've done both, and Apache/mod_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod_wsgi, which is everything I've... | Running Django with FastCGI or with mod_python | which would you recommend?
which is faster, reliable?
apache mod_python or nginx/lighttpd FastCGI?
| [
"I've done both, and Apache/mod_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod_wsgi, which is everything I've ever wanted and more:\n\nEasy management of daemon processes.\nAs a result, much better process isolation (running multiple sites in the same Apache c... | [
21,
6,
5,
2,
2,
2,
2
] | [] | [] | [
"apache",
"django",
"fastcgi",
"python"
] | stackoverflow_0000245237_apache_django_fastcgi_python.txt |
Q:
Python printing the word
If any one can help me with Python code:
If I input a letter, How can I print all the words start with that word?
A:
print [word for word in words if word.startswith(letter)]
A:
There are many ways of doing this, e.g.:
words = ["zwei", "peanuts", "were", "walking", "down", "the", "stra... | Python printing the word | If any one can help me with Python code:
If I input a letter, How can I print all the words start with that word?
| [
"print [word for word in words if word.startswith(letter)]\n\n",
"There are many ways of doing this, e.g.:\nwords = [\"zwei\", \"peanuts\", \"were\", \"walking\", \"down\", \"the\", \"strasse\"]\nletter = \"w\"\noutput = [x for x in words if x[0] == letter]\n\nThe contents of output will be:\n['were', 'walking']\... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000305422_python.txt |
Q:
How can I get a list of the running applications with GTK?
How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen.
A:
I believe what you are looking for is libwnck
A:
The panel you are referring to is the GNOME panel. So this is a GNOME question, no... | How can I get a list of the running applications with GTK? | How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen.
| [
"I believe what you are looking for is libwnck\n",
"The panel you are referring to is the GNOME panel. So this is a GNOME question, not a GTK question.\nThere is not a well-defined concept of \"multi-window application\" in GNOME that I know of. The panel task list is probably build by querying the window manager... | [
3,
0
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0000306456_gtk_pygtk_python.txt |
Q:
With Python, how can I ensure that compression of a folder takes place within a particular folder?
I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my ... | With Python, how can I ensure that compression of a folder takes place within a particular folder? | I have been able to zip the contents of my folder. But I would like the zipped file to remain in the folder that was just compressed. For example, I've zipped a folder called test in my C: drive. But I would like my "test.zip" file to be contained in C:\test. How can I do this? Thanks in advance.
clarification of quest... | [
"Whatever you pass as zip_file to your function will be the file that the ZipFile object will write to. So if you pass it a full path, then it will be put there. If you pass it just a filename, then it will be written to that filename under the current working path. It sounds like you just need to make sure that zi... | [
2
] | [] | [] | [
"file",
"python",
"zip"
] | stackoverflow_0000306811_file_python_zip.txt |
Q:
Django foreign key access in save() function
Here's my code:
class Publisher(models.Model):
name = models.CharField(
max_length = 200,
unique = True,
)
url = models.URLField()
def __unicode__(self):
return self.name
def save(self):
pass
class Item(mod... | Django foreign key access in save() function | Here's my code:
class Publisher(models.Model):
name = models.CharField(
max_length = 200,
unique = True,
)
url = models.URLField()
def __unicode__(self):
return self.name
def save(self):
pass
class Item(models.Model):
publisher = models.ForeignKey(Publ... | [
"You should be able to do something like the following:\ndef save(self, **kwargs):\n super(Publisher, self).save(**kwargs)\n\n for item in self.item_set.all():\n item.code = \"%s - whatever\" % item.code\n\nI don't really like what you're doing here, this isn't a good way to relate Item to Publisher. ... | [
12
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0000307038_django_django_models_python.txt |
Q:
The best way to invoke methods in Python class declarations?
Say I am declaring a class C and a few of the declarations are very similar. I'd like to use a function f to reduce code repetition for these declarations. It's possible to just declare and use f as usual:
>>> class C(object):
... def f(num):
... ... | The best way to invoke methods in Python class declarations? | Say I am declaring a class C and a few of the declarations are very similar. I'd like to use a function f to reduce code repetition for these declarations. It's possible to just declare and use f as usual:
>>> class C(object):
... def f(num):
... return '<' + str(num) + '>'
... v = f(9)
... w = ... | [
"Quite simply, the solution is that f does not need to be a member of the class. I am assuming that your thought-process has gone through a Javaish language filter causing the mental block. It goes a little something like this:\ndef f(n):\n return '<' + str(num) + '>'\n\nclass C(object):\n\n v = f(9)\n w =... | [
14,
3,
2,
1,
1,
0
] | [] | [] | [
"class",
"declaration",
"invocation",
"python",
"static_methods"
] | stackoverflow_0000304655_class_declaration_invocation_python_static_methods.txt |
Q:
Embedded Web Server in Python?
Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.
A:
How minimalistic and for what purpose?
SimpleHTTPServer comes free as part of the standard Python libraries.
If you need more features, look into CherryPy or (at the top end) Twist... | Embedded Web Server in Python? | Can you recommend a minimalistic python webserver that I can embedded in my Desktop Application.
| [
"How minimalistic and for what purpose? \nSimpleHTTPServer comes free as part of the standard Python libraries.\nIf you need more features, look into CherryPy or (at the top end) Twisted.\n",
"I'm becoming a big fan of the newly released circuits library. It's a component/event framework that comes with a very n... | [
17,
5,
4,
3,
3,
1,
0
] | [] | [] | [
"embeddedwebserver",
"python",
"simplehttpserver"
] | stackoverflow_0000302615_embeddedwebserver_python_simplehttpserver.txt |
Q:
Why do new instances of a class share members with other instances?
class Ball:
a = []
def __init__(self):
pass
def add(self,thing):
self.a.append(thing)
def size(self):
print len(self.a)
for i in range(3):
foo = Ball()
foo.add(1)
foo.add(2)
foo.size()
I would expect a return of :
2... | Why do new instances of a class share members with other instances? | class Ball:
a = []
def __init__(self):
pass
def add(self,thing):
self.a.append(thing)
def size(self):
print len(self.a)
for i in range(3):
foo = Ball()
foo.add(1)
foo.add(2)
foo.size()
I would expect a return of :
2
2
2
But I get :
2
4
6
Why is this? I've found that by doing a=[] in th... | [
"doh\nI just figured out why.\nIn the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the init block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seem... | [
4,
2,
1
] | [] | [] | [
"mutable",
"python",
"scope"
] | stackoverflow_0000307729_mutable_python_scope.txt |
Q:
pygtk glade question: why isn't this simple script working?
I've been writing writing a small pygtk application using glade to put together the UIs. I've created several windows already that work, but for some reason this one isn't working. I get the following traceback:
Traceback (most recent call last):
File... | pygtk glade question: why isn't this simple script working? | I've been writing writing a small pygtk application using glade to put together the UIs. I've created several windows already that work, but for some reason this one isn't working. I get the following traceback:
Traceback (most recent call last):
File "test.py", line 7, in <module>
class TestClass:
File "test... | [
"That code and window and signal connection work fine here.\nThere is a small bug though when calling the signal handler. The signal handler should not have a data argument, since only the widget is passed as an argument.\ndef on_TestClass_destroy(self, widget):\n gtk.main_quit()\n\nThe data argument(s) are only... | [
4
] | [] | [] | [
"glade",
"gtk",
"pygtk",
"python"
] | stackoverflow_0000308913_glade_gtk_pygtk_python.txt |
Q:
Python data structures overhead/performance
Is there any performance advantage to using lists over dictionaries over tuples in Python?
If I'm optimising for speed, is there any reason to prefer one over another?
A:
Rich,
Lists and dicts are beasts suitable for different needs. Make sure you don't use lists for l... | Python data structures overhead/performance | Is there any performance advantage to using lists over dictionaries over tuples in Python?
If I'm optimising for speed, is there any reason to prefer one over another?
| [
"Rich,\nLists and dicts are beasts suitable for different needs. Make sure you don't use lists for linear searches where dicts hashes are perfect, because it's way slower. Also, if you just need a list of elements to traverse, don't use dicts because it will take much more space than lists.\nThat may sound obvious,... | [
20,
6,
2,
0
] | [] | [] | [
"optimization",
"python"
] | stackoverflow_0000308912_optimization_python.txt |
Q:
Python - Setting / Getting Environment Variables and Addrs
I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?
Edit: The scop... | Python - Setting / Getting Environment Variables and Addrs | I need to set an environment variable in Python and find the address in memory where it is located. Since it's on Linux, I don't mind about using libraries that only work consistently on Linux (if that's the only way). How would you do this?
Edit: The scope of the problem is as follows: I'm trying to hack a program for... | [
"For accessing and setting environment variables, read up on the os.environ dictionary. You can also use os.putenv to set an environment variable.\n",
"The built in function id() returns a unique id for any object, which just happens to be it's memory address. \nhttp://docs.python.org/library/functions.html#id\n"... | [
4,
1,
0
] | [] | [] | [
"environment_variables",
"linux",
"python"
] | stackoverflow_0000310118_environment_variables_linux_python.txt |
Q:
Cleaning form data in Django
How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms.
What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug... | Cleaning form data in Django | How can i clean and modify data from a form in django. I would like to define it on a per field basis for each model, much like using ModelForms.
What I want to achieve is automatically remove leading and trailing spaces from defined fields, or turn a title (from one field) into a slug (which would be another field).
| [
"You can define clean_FIELD_NAME() methods which can validate and alter data, as documented here: http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation\n"
] | [
12
] | [] | [] | [
"django",
"forms",
"python",
"slug"
] | stackoverflow_0000310931_django_forms_python_slug.txt |
Q:
How can I translate the following filename to a regular expression in Python?
I am battling regular expressions now as I type.
I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned... | How can I translate the following filename to a regular expression in Python? | I am battling regular expressions now as I type.
I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a... | [
"Now that you have a human readable description of your file name, it's quite straight forward to translate it into a regular expression (at least in this case ;)\n\nmust start with\n\nThe caret (^) anchors a regular expression to the beginning of what you want to match, so your re has to start with this symbol.\n\... | [
12,
4,
4,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000310199_python_regex.txt |
Q:
using rstrip on form.cleaned_data[i] in Django
In my views.py, i have a snippit of code like this:
def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
im... | using rstrip on form.cleaned_data[i] in Django | In my views.py, i have a snippit of code like this:
def clean_post_data(form):
for i in form.cleaned_data:
form.cleaned_data[i] = form.cleaned_data[i].rstrip()
def add_product(request):
form = ProductForm(request.POST, request.FILES or None)
image = Image.objects.all()
action = "Add"
if... | [
"The clean_post_data shouldn't be a stand-alone function.\nIt should be a method in the form, named clean. See Form and Field Validation.\n",
"Most likely you have several elements on your form with same name. When it is submitted one of the elements returned by cleaned_data is a list\nIf you want to skip (or do... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0000310833_django_python.txt |
Q:
Admin generic inlines for multi-table subclassed models broken --- any alternatives?
Here's what I'm trying to do, and failing...
I have a File model which has a generic-relation to other objects:
class File(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerFiel... | Admin generic inlines for multi-table subclassed models broken --- any alternatives? | Here's what I'm trying to do, and failing...
I have a File model which has a generic-relation to other objects:
class File(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
file = models.FileField(upload_to... | [
"Inheritance can be implemented two ways in a relational model.\nA subclass can be a new table with all the same columns as the superclass repeated. This works well when you have an abstract superclass or subclass features that override the superclass.\nA subclass can be just the unique columns with a join to the ... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0000311300_django_django_admin_django_models_python.txt |
Q:
python as a "batch" script (i.e. run commands from python)
I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.
how can I run a command from python such that the program when run, will replace the script? The program is int... | python as a "batch" script (i.e. run commands from python) | I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.
how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and ask... | [
"You should create a new processess using the subprocess module.\nI'm not fluent in windows processes but its Popen function is cross-platform, and should be preffered to OS specific solutions.\nEDIT: I maintain that you should prefer the Subprocess module to os.* OS specific functions, it is cross-platform and mor... | [
18,
7,
4,
2
] | [] | [] | [
"batch_file",
"python",
"scripting"
] | stackoverflow_0000311601_batch_file_python_scripting.txt |
Q:
Python Input/Output, files
I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.
In c++ I could do this by simply making my class methods use std::istream and std::ostream which co... | Python Input/Output, files | I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.
In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, t... | [
"The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with StringIO:\nfrom cStringIO import StringIO\n\ns = \"My very long string I want to read like a file\"\nfile_like_string = StringIO(s)\ndata = file_like_string.read(10)\n\nRemember ... | [
10,
0
] | [] | [] | [
"python"
] | stackoverflow_0000310629_python.txt |
Q:
Public free web services for testing soap client
Are there any publicly available SOAP 1.2/WSDL 2.0 compliant free web services for testing a Python based soap client library (e.g. Zolera SOAP Infrastructure)?
So far, it appears to me that Google Web API may be the only option.
Otherwise, how can one test a SOAP ... | Public free web services for testing soap client | Are there any publicly available SOAP 1.2/WSDL 2.0 compliant free web services for testing a Python based soap client library (e.g. Zolera SOAP Infrastructure)?
So far, it appears to me that Google Web API may be the only option.
Otherwise, how can one test a SOAP 1.2 compliant client library?
| [
"There is a bunch on here:\nhttp://www.webservicex.net/WS/wscatlist.aspx\nJust google for \"Free WebService\" or \"Open WebService\" and you'll find tons of open SOAP endpoints.\nRemember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.\n"
] | [
73
] | [] | [] | [
"python",
"soap",
"soappy",
"web_services",
"zsi"
] | stackoverflow_0000311654_python_soap_soappy_web_services_zsi.txt |
Q:
How do I not raise a Python exception when converting an integer-as-string to an int
I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row then it should have some values tha... | How do I not raise a Python exception when converting an integer-as-string to an int | I have some HTML I am trying to parse. There are cases where the html attributes alone are not going to help me identify the row type (header versus data). Fortunately, if my row is a data row then it should have some values that can be converted to integers. I have figured out how to convert the unicode to an integ... | [
"Have you looked at the try statement?\ntry:\n x = int(rowColumn[1][3].replace(',','').strip('$'))\nexcept ValueError, e:\n x = None # rowColumn[1][3] was not an integer\n\n"
] | [
5
] | [] | [] | [
"integer",
"python",
"text"
] | stackoverflow_0000311963_integer_python_text.txt |
Q:
How to build "Tagging" support using CouchDB?
I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?
def by_tag(tag):
return '''
function(doc) {
if (doc.tags... | How to build "Tagging" support using CouchDB? | I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?
def by_tag(tag):
return '''
function(doc) {
if (doc.tags.length > 0) {
for (var tag in doc.... | [
"Disclaimer: I didn't test this and don't know if it can perform better. \nCreate a single perm view:\nfunction(doc) {\n for (var tag in doc.tags) {\n emit([tag, doc.published], doc)\n }\n};\n\nAnd query with \n_view/your_view/all?startkey=['your_tag_here']&endkey=['your_tag_here', {}]\nResulting JSON structur... | [
7,
3,
1,
0
] | [] | [] | [
"couchdb",
"document_oriented_db",
"python",
"tagging"
] | stackoverflow_0000211118_couchdb_document_oriented_db_python_tagging.txt |
Q:
Python, optparse and file mask
if __name__=='__main__':
parser = OptionParser()
parser.add_option("-i", "--input_file",
dest="input_filename",
help="Read input from FILE", metavar="FILE")
(options, args) = parser.parse_args()
print options
result is
$ py... | Python, optparse and file mask | if __name__=='__main__':
parser = OptionParser()
parser.add_option("-i", "--input_file",
dest="input_filename",
help="Read input from FILE", metavar="FILE")
(options, args) = parser.parse_args()
print options
result is
$ python convert.py -i video_*
{'input_f... | [
"Python has nothing to do with this -- it's the shell.\nCall\n$ python convert.py -i 'video_*'\n\nand it will pass in that wildcard.\nThe other six values were passed in as args, not attached to the -i, exactly as if you'd run python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6, and the -i only att... | [
8,
2,
1,
0
] | [] | [] | [
"optparse",
"python"
] | stackoverflow_0000312673_optparse_python.txt |
Q:
Is it correct to inherit from built-in classes?
I want to parse an Apache access.log file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.
I am going to create a class ApacheAccessLog, and the only thing I can imagine now, it will ... | Is it correct to inherit from built-in classes? | I want to parse an Apache access.log file with a python program in a certain way, and though I am completely new to object-oriented programming, I want to start doing it now.
I am going to create a class ApacheAccessLog, and the only thing I can imagine now, it will be doing is 'readline' method. Is it conventionally c... | [
"In this case I would use delegation rather than inheritance. It means that your class should contain the file object as an attribute and invoke a readline method on it. You could pass a file object in the constructor of the logger class.\nThere are at least two reasons for this:\n\nDelegation reduces coupling, for... | [
15,
6,
1,
1,
1,
0
] | [] | [] | [
"inheritance",
"oop",
"python"
] | stackoverflow_0000288695_inheritance_oop_python.txt |
Q:
Access second result set of stored procedure with SQL or other work-around? Python\pyodbc
I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there a... | Access second result set of stored procedure with SQL or other work-around? Python\pyodbc | I'm using python\pyodbc and would like to access the second result set of a stored procedure. As near as I can tell, pyodbc does not support multiple result sets. Additionally, I can't modify the stored procedure. Are there any options to access the second result set using SQL or some other work-around? Perhaps create ... | [
"No need for anything fancy. Just use the cursor's nextset() method:\n\nimport pyodbc\n\ndb = pyodbc.connect (\"\")\nq = db.cursor ()\nq.execute (\"\"\"\nSELECT TOP 5 * FROM INFORMATION_SCHEMA.TABLES\nSELECT TOP 10 * FROM INFORMATION_SCHEMA.COLUMNS\n\"\"\")\ntables = q.fetchall ()\nq.nextset ()\ncolumns = q.fetchal... | [
20,
0
] | [] | [] | [
"pyodbc",
"python",
"sql"
] | stackoverflow_0000273203_pyodbc_python_sql.txt |
Q:
Effective Keyboard Input Handling
What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:
for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass ... | Effective Keyboard Input Handling | What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:
for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass #make everything an elif
elif r... | [
"You could create a dictionary where the keys are the input and the value is a function that handles the keypress:\ndef handle_quit():\n quit()\n\ndef handle_left():\n curpiece.shift(-1, 0)\n shadowpiece = curpiece.clone(); setupshadow(shadowpiece)\n\ndef handle_right():\n curpiece.shift(1, 0)\n shadow... | [
17,
3,
2
] | [] | [] | [
"interactive",
"keyboard",
"python",
"user_input",
"user_interface"
] | stackoverflow_0000312263_interactive_keyboard_python_user_input_user_interface.txt |
Q:
Are there problems developing Django on Jython?
The background
I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.
The o... | Are there problems developing Django on Jython? | The background
I'm building a fair-sized web application with a friend in my own time, and we've decided to go with the Django framework on Python. Django provides us with a lot of features we're going to need, so please don't suggest alternative frameworks.
The only decision I'm having trouble with, is whether we u... | [
"Django does work on Jython, although you'll need to use the development release of Jython, since technically Jython 2.5 is still in beta. However, Django 1.0 and up should work unmodified.\nSo as to whether you should use the regular Python implementation or Jython, I'd say it's a matter of whether you prefer hav... | [
3,
3,
1,
0
] | [] | [] | [
"django",
"jvm",
"jython",
"python"
] | stackoverflow_0000314234_django_jvm_jython_python.txt |
Q:
Best way to access table instances when using SQLAlchemy's declarative syntax
All the docs for SQLAlchemy give INSERT and UPDATE examples using the local table instance (e.g. tablename.update()... )
Doing this seems difficult with the declarative syntax, I need to reference Base.metadata.tables["tablename"] to get... | Best way to access table instances when using SQLAlchemy's declarative syntax | All the docs for SQLAlchemy give INSERT and UPDATE examples using the local table instance (e.g. tablename.update()... )
Doing this seems difficult with the declarative syntax, I need to reference Base.metadata.tables["tablename"] to get the table reference.
Am I supposed to do this another way? Is there a different ... | [
"well it works for me:\nclass Users(Base):\n __tablename__ = 'users'\n __table_args__ = {'autoload':True}\n\nusers = Users()\nprint users.__table__.select()\n\n...SELECT users.......\n",
"via the __table__ attribute on your declarative class\n",
"There may be some confusion between table (the object) a... | [
10,
4,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0000075829_python_sql_sqlalchemy.txt |
Q:
Comparing multiple dictionaries in Python
I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.
When the user s... | Comparing multiple dictionaries in Python | I'm new to Python and am running to a problem I can't google my way out of. I've built a GUI using wxPython and ObjectiveListView. In its very center, the GUI has a list control displaying data in X rows (the data is loaded by the user) and in five columns.
When the user selects multiple entries from the list control (... | [
">>> mysets = (set(x.items()) for x in MyList)\n>>> reduce(lambda a,b: a.intersection(b), mysets)\nset([('sum', '-21,90'), ('type', 'Purchase'), ('target', 'Apple Store')])\n\nFirst, I've created a generator that will convert the list of dicts into an iterable sequence of sets of key,value pairs. You could use a li... | [
8,
8,
2,
1,
0
] | [] | [] | [
"data_mining",
"python"
] | stackoverflow_0000314583_data_mining_python.txt |
Q:
How do I search through a folder for the filename that matches a regular expression using Python?
I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search ... | How do I search through a folder for the filename that matches a regular expression using Python? | I am having some difficulty writing a function that will search through a directory for a file that matches a specific regular expression (which I have compiled using 're.compile'). So my question is: How do I search through a directory (I plan to use os.walk) for a file that matches a specific regular expression? An e... | [
"This will find all files starting with two digits and ending in gif, you can add the files into a global list, if you wish:\nimport re\nimport os\nr = re.compile(r'\\d{2}.+gif$')\nfor root, dirs, files in os.walk('/home/vinko'):\n l = [os.path.join(root,x) for x in files if r.match(x)]\n if l: print l #Or append... | [
11,
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0000315381_python_regex.txt |
Q:
How can I do synchronous rpc calls
I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead... | How can I do synchronous rpc calls | I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server us... | [
"For a synchronous client, Twisted probably isn't the right option. Instead, you might want to use the socket module directly.\nimport socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((self.host, self.port))\ns.send(output)\ndata = s.recv(size)\ns.close()\n\nThe recv() call might need to be... | [
2,
2,
2,
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0000281922_python_twisted.txt |
Q:
Running a function periodically in twisted protocol
I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logi... | Running a function periodically in twisted protocol | I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reac... | [
"You would probably want to do this in the Factory for the connections. The Factory is not automatically notified of every time a connection is made and lost, so you can notify it from the Protocol.\nHere is a complete example of how to use twisted.internet.task.LoopingCall in conjunction with a customised basic Fa... | [
38,
3
] | [] | [] | [
"protocols",
"python",
"tcp",
"twisted"
] | stackoverflow_0000315716_protocols_python_tcp_twisted.txt |
Q:
Twisted FTPFileListProtocol and file names with spaces
I am using Python and the Twisted framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant.
When connecting and calling the list method on an FTPClient, the resulting FTPFileListProtoco... | Twisted FTPFileListProtocol and file names with spaces | I am using Python and the Twisted framework to connect to an FTP site to perform various automated tasks. Our FTP server happens to be Pure-FTPd, if that's relevant.
When connecting and calling the list method on an FTPClient, the resulting FTPFileListProtocol's files collection does not contain any directories or fil... | [
"Firstly, if you're performing automated tasks on a retrieived FTP listing then you should probably be looking at NLST rather than LIST as noted in RFC 959 section 4.1.3:\n\n NAME LIST (NLST)\n ...\n This command is intended to return information that\n can be used by a program to further proc... | [
2,
0
] | [] | [] | [
"ftp",
"python",
"twisted"
] | stackoverflow_0000304152_ftp_python_twisted.txt |
Q:
Decimal place issues with floats and decimal.Decimal
I seem to be losing a lot of precision with floats.
For example I need to solve a matrix:
4.0x -2.0y 1.0z =11.0
1.0x +5.0y -3.0z =-6.0
2.0x +2.0y +5.0z =7.0
This is the code I use to import the matrix from a text file:
f = open('gauss.dat')
lines = f.readlines... | Decimal place issues with floats and decimal.Decimal | I seem to be losing a lot of precision with floats.
For example I need to solve a matrix:
4.0x -2.0y 1.0z =11.0
1.0x +5.0y -3.0z =-6.0
2.0x +2.0y +5.0z =7.0
This is the code I use to import the matrix from a text file:
f = open('gauss.dat')
lines = f.readlines()
f.close()
j=0
for line in lines:
bits = string.spl... | [
"IEEE floating point is binary, not decimal. There is no fixed length binary fraction that is exactly 0.1, or any multiple thereof. It is a repeating fraction, like 1/3 in decimal.\nPlease read What Every Computer Scientist Should Know About Floating-Point Arithmetic\nOther options besides a Decimal class are \n\nu... | [
14,
12,
4,
4,
2,
0
] | [] | [] | [
"decimal",
"floating_accuracy",
"floating_point",
"python"
] | stackoverflow_0000286061_decimal_floating_accuracy_floating_point_python.txt |
Q:
Ghostscript PDF -> TIFF throws an untrappable exception, when consuming files with asian fonts
Ghostscript curls up and dies, throwing an exception to stdout which I cannot catch and log. I am pretty sure it gets sick when I give it asian fonts. Has anybody backed into this problem and solved it?
A:
It may be th... | Ghostscript PDF -> TIFF throws an untrappable exception, when consuming files with asian fonts | Ghostscript curls up and dies, throwing an exception to stdout which I cannot catch and log. I am pretty sure it gets sick when I give it asian fonts. Has anybody backed into this problem and solved it?
| [
"It may be that you need to read stderr from the child process.\n"
] | [
1
] | [] | [] | [
"ghostscript",
"jython",
"python",
"tiff"
] | stackoverflow_0000316518_ghostscript_jython_python_tiff.txt |
Q:
Newbie Python question about strings with parameters: "%%s"?
I'm trying to figure out what the following line does exactly - specifically the %%s part?
cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
Any good mini-tutorial about string formatting and inserting v... | Newbie Python question about strings with parameters: "%%s"? | I'm trying to figure out what the following line does exactly - specifically the %%s part?
cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))
Any good mini-tutorial about string formatting and inserting variables into strings with Python?
| [
"The %% becomes a single %. This code is essentially doing two levels of string formatting. First the %sourcedest is executed to turn your code essentially into:\ncursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n))\n\nthen the db layer applies the parameters to the slots that... | [
7,
4,
3,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0000317368_python_string.txt |
Q:
Python: packing an ip address as a ctype.c_ulong() for use with DLL
given the following code:
import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
how can I correctly pack this for a DLL that expects it as a c_ulong datatype?
I've tried using:
ip_netFrmt = socket.... | Python: packing an ip address as a ctype.c_ulong() for use with DLL | given the following code:
import ctypes
ip="192.168.1.1"
thisdll = ctypes.cdll['aDLL']
thisdll.functionThatExpectsAnIP(ip)
how can I correctly pack this for a DLL that expects it as a c_ulong datatype?
I've tried using:
ip_netFrmt = socket.inet_aton(ip)
ip_netFrmt_c = ctypes.c_ulong(ip_netFrmt)
however, the c_u... | [
"The inet_aton returns a string of bytes. This used to be the lingua franca for C-language interfaces.\nHere's how to unpack those bytes into a more useful value.\n>>> import socket\n>>> packed_n= socket.inet_aton(\"128.0.0.1\")\n>>> import struct\n>>> struct.unpack( \"!L\", packed_n )\n(2147483649L,)\n>>> hex(_[0... | [
6,
0,
0,
0
] | [] | [] | [
"ctypes",
"dll",
"ip_address",
"python"
] | stackoverflow_0000317531_ctypes_dll_ip_address_python.txt |
Q:
Spambots are cluttering my log file [Django]
I have a nice and lovely Django site up and running, but have noticed that my error.log file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a b... | Spambots are cluttering my log file [Django] | I have a nice and lovely Django site up and running, but have noticed that my error.log file was getting huge, over 150 MB after a couple of months of being live. Turns out a bunch of spambots are looking for well known URL vulnerabilities (or something) and hitting a bunch of sub-directories like http://mysite.com/ie ... | [
"Um, perhaps, use logrotate to rotate and compress the logs periodically, if it isn't being done already.\n",
"If you can find a pattern in UserAgent string, you may use DISALLOWED_USER_AGENT setting. Mine is:\nDISALLOWED_USER_AGENTS = (\n re.compile(r'Java'),\n re.compile(r'gigamega'),\n re.compile(r'li... | [
7,
4,
3,
3,
0,
0,
0
] | [
"A programming solution would be to :\n\nopen the log file\nread the lines in a buffer\nreplace the lines that match the errors the bots caused\nseek to the beginning of the file\nwrite the new buffer\ntruncate the file to current pointer position\nclose\n\nVoila ! It's done !\n"
] | [
-1
] | [
"apache",
"django",
"python",
"spam_prevention"
] | stackoverflow_0000315363_apache_django_python_spam_prevention.txt |
Q:
Python: converting strings for use with ctypes.c_void_p()
given a string:
msg="hello world"
How can I define this as a ctypes.c_void_p() data type?
the following code yields a "cannot be converted to pointer" exception:
data=ctypes.c_void_p(msg)
data is required to be a void* type in C, because it is being passe... | Python: converting strings for use with ctypes.c_void_p() | given a string:
msg="hello world"
How can I define this as a ctypes.c_void_p() data type?
the following code yields a "cannot be converted to pointer" exception:
data=ctypes.c_void_p(msg)
data is required to be a void* type in C, because it is being passed to a DLL.
I'm assuming there is a way to pack/unpack the str... | [
"Something like this? Using ctypes.cast?\n>>> import ctypes\n>>> p1= ctypes.c_char_p(\"hi mom\")\n>>> ctypes.cast( p1, ctypes.c_void_p )\nc_void_p(11133300)\n\n"
] | [
12
] | [] | [] | [
"ctypes",
"dll",
"python",
"types"
] | stackoverflow_0000318067_ctypes_dll_python_types.txt |
Q:
Python as FastCGI under windows and apache
I need to run a simple request/response python module under an
existing system with windows/apache/FastCGI.
All the FastCGI wrappers for python I tried work for Linux only
(they use socket.fromfd() and other such shticks).
Is there a wrapper that runs under windows?
A:
... | Python as FastCGI under windows and apache | I need to run a simple request/response python module under an
existing system with windows/apache/FastCGI.
All the FastCGI wrappers for python I tried work for Linux only
(they use socket.fromfd() and other such shticks).
Is there a wrapper that runs under windows?
| [
"You might find it easier to ditch FastCGI altogether and just run a python webserver on a localhost port. Then just use mod_rewrite to map the apache urls to the internal webserver.\n(I started offering FastCGI at my hosting company and to my surprise, nearly everyone ditched it in favor of just running their own ... | [
2,
1,
0
] | [] | [] | [
"apache",
"fastcgi",
"python",
"windows"
] | stackoverflow_0000312928_apache_fastcgi_python_windows.txt |
Q:
Does anyone know where there is a recipe for serializing data and preserving its order in the output?
I am working with a set of data that I have converted to a list of dictionaries
For example one item in my list is
{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070... | Does anyone know where there is a recipe for serializing data and preserving its order in the output? | I am working with a set of data that I have converted to a list of dictionaries
For example one item in my list is
{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005',
'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'}
Per request
The second item in my list could be... | [
"So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem).\n>>> import pickle\n>>> d1 = {1:'one', 2:'two', 3:'three'}\n>>> d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}\n>>> d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty... | [
5,
1,
1
] | [] | [] | [
"python",
"serialization"
] | stackoverflow_0000318700_python_serialization.txt |
Q:
Adding a dimension to every element of a numpy.array
I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:
>>> my_ar = numpy.array((0,5,10))
[0, 5, 10]
>>> transformed = my_fun(my_ar) # In reality, my_fun() would do somet... | Adding a dimension to every element of a numpy.array | I'm trying to transform each element of a numpy array into an array itself (say, to interpret a greyscale image as a color image). In other words:
>>> my_ar = numpy.array((0,5,10))
[0, 5, 10]
>>> transformed = my_fun(my_ar) # In reality, my_fun() would do something more useful
array([
[ 0, 0, 0],
[ 5, 10... | [
"Does numpy.dstack do what you want? The first two indexes are the same as the original array, and the new third index is \"depth\".\n>>> import numpy as N\n>>> a = N.array([[1,2,3],[4,5,6],[7,8,9]])\n>>> a\narray([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])\n>>> b = N.dstack((a,a,a))\n>>> b\narray([[[1, 1, 1... | [
7,
2,
1,
1
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0000310459_arrays_numpy_python.txt |
Q:
Problem with relative path in Python
I know this is a simple, beginner-ish Python question, but I'm having trouble opening a file using a relative path. This behavior seems odd to me (coming from a non-Python background):
import os, sys
titles_path = os.path.normpath("../downloads/movie_titles.txt")
print "Curre... | Problem with relative path in Python | I know this is a simple, beginner-ish Python question, but I'm having trouble opening a file using a relative path. This behavior seems odd to me (coming from a non-Python background):
import os, sys
titles_path = os.path.normpath("../downloads/movie_titles.txt")
print "Current working directory is {0}".format(os.get... | [
"normpath only returns a normalized version of that particular path. It does not actually do the work of resolving the path for you. You might want to do os.path.abspath(yourpath).\nAlso, I'm assuming you're on IronPython. Otherwise, the standard way of expressing that string format would be:\n\"Current working dir... | [
3
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0000319037_python_windows.txt |
Q:
Standard C or Python libraries to compute standard deviation of normal distribution
Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P.
What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that ta... | Standard C or Python libraries to compute standard deviation of normal distribution | Say we have normal distribution n(x): mean=0 and \int_{-a}^{a} n(x) = P.
What is the easiest way to compute standard deviation of such distribution? May be there are standard libraries for python or C, that are suitable for that task?
| [
"If X is normal with mean 0 and standard deviation sigma, it must hold \nP = Prob[ -a <= X <= a ] = Prob[ -a/sigma <= N <= a/sigma ]\n = 2 Prob[ 0 <= N <= a/sigma ]\n = 2 ( Prob[ N <= a/sigma ] - 1/2 )\n\nwhere N is normal with mean 0 and standard deviation 1. Hence\nP/2 + 1/2 = Prob[ N <= a/sigma ] = Phi(a/sigma... | [
7,
6,
3,
1
] | [] | [] | [
"algorithm",
"c",
"math",
"probability",
"python"
] | stackoverflow_0000317963_algorithm_c_math_probability_python.txt |
Q:
How do you iterate over a tree?
What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?
def children(self):
stack = [self.entities]... | How do you iterate over a tree? | What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?
def children(self):
stack = [self.entities]
while stack:
for e in s... | [
"Unless your tree is really large or you have really high (real) requirements for speed, I would choose the recursive method. Easier to read, easier to code.\n",
"Recursive function calls are not incredibly inefficient, that is an old programming myth. (If they're badly implemented, they may incur a larger overhe... | [
5,
5,
5,
4,
3,
1,
0,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0000320052_algorithm_python.txt |
Q:
Python type-error issue
I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way ... | Python type-error issue | I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code;
sta... | [
"A stacktrace would've helped, but presumably the error is:\nmaterials = 1 + (level * 1)\n\n‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.\nlevel= raw_input('blah')\ntry:\n level= int(level)\nexcept ValueError:\n # user put some... | [
13
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0000320827_python_typeerror.txt |
Q:
python - check at the end of the loop if need to run again
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;
"loop again? y/n"
A:
while True:
func()
answer = raw... | python - check at the end of the loop if need to run again | It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;
"loop again? y/n"
| [
"while True:\n func()\n answer = raw_input( \"Loop again? \" )\n if answer != 'y':\n break\n\n",
"keepLooping = True\nwhile keepLooping:\n # do stuff here\n\n # Prompt the user to continue\n q = raw_input(\"Keep looping? [yn]: \")\n if not q.startswith(\"y\"):\n keepLooping = False\n\n",
... | [
14,
6,
5,
1
] | [] | [] | [
"loops",
"python"
] | stackoverflow_0000273612_loops_python.txt |
Q:
How do I skip processing the attachments of an email which is an attachment of a different email
using jython
I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file.
I am caught in a rather nasty situation, because sometimes people se... | How do I skip processing the attachments of an email which is an attachment of a different email | using jython
I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file.
I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments.
What I want to do is ski... | [
"The problem with existing suggestions is the walk method. This recursively, depth-first, walks the entire tree, including children.\nLook at the source of the walk method, and adapt it to skip the recursive part. A cursory reading suggests:\nif msg.is_multipart():\n for part in msg.get_payload():\n \"\... | [
2,
0,
0,
0
] | [] | [] | [
"attachment",
"email",
"jython",
"python"
] | stackoverflow_0000319896_attachment_email_jython_python.txt |
Q:
OpenCV's Python - OS X
I get the following error while building OpenCV on OS X 10.5 (intel):
ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architectur... | OpenCV's Python - OS X | I get the following error while building OpenCV on OS X 10.5 (intel):
ld: warning in .libs/_cv_la-_cv.o, file is not of required architecture
ld: warning in .libs/_cv_la-error.o, file is not of required architecture
ld: warning in .libs/_cv_la-pyhelpers.o, file is not of required architecture
ld: warning in .libs/_cv_l... | [
"It seems a little weird that it is warning about different architectures when looking for /Developer/SDKs/MacOSX10.4u.sdk while linking - can you give us some more detail about your build environment (version of XCode, GCC, Python, $PATH etc)\nAlternatively, won't any of the OpenCV binaries available work for you?... | [
1,
0,
0
] | [] | [] | [
"macos",
"opencv",
"python"
] | stackoverflow_0000315803_macos_opencv_python.txt |
Q:
python logging into a forum
I've written this to try and log onto a forum (phpBB3).
import urllib2, re
import urllib, re
logindata = urllib.urlencode({'username': 'x', 'password': 'y'})
page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata])
output = page.read()
However when I run it it ... | python logging into a forum | I've written this to try and log onto a forum (phpBB3).
import urllib2, re
import urllib, re
logindata = urllib.urlencode({'username': 'x', 'password': 'y'})
page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata])
output = page.read()
However when I run it it comes up with;
Traceback (most re... | [
"Your line\npage = urllib.urlopen(\"http://www.woarl.com/board/ucp.php?mode=login\"[logindata])\n\nis semantically invalid Python. Presumably you meant\npage = urllib.urlopen(\"http://www.woarl.com/board/ucp.php?mode=login\", [logindata])\n\nwhich has a comma separating the arguments. However, what you ACTUALLY w... | [
5,
1,
1,
1
] | [
"This would be easier with the high-level \"mechanize\" module.\n"
] | [
-1
] | [
"authentication",
"phpbb3",
"python",
"typeerror"
] | stackoverflow_0000321304_authentication_phpbb3_python_typeerror.txt |
Q:
urllib2 data sending
I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.
import urllib2, re
import urllib, re
logindata = urllib.urlencode({'username': 'x', 'password': 'y'})
page = urlli... | urllib2 data sending | I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.
import urllib2, re
import urllib, re
logindata = urllib.urlencode({'username': 'x', 'password': 'y'})
page = urllib2.urlopen("http://www.woa... | [
"Someone recently asked the same question you're asking. If you read through the answers to that question you'll see code examples showing you how to stay logged in while browsing a site in a Python script using only stuff in the standard library.\nThe accepted answer might not be as useful to you as this other an... | [
5,
3,
1,
0
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0000321582_python_urllib2.txt |
Q:
split twice in the same expression?
Imagine I have the following:
inFile = "/adda/adas/sdas/hello.txt"
# that instruction give me hello.txt
Name = inFile.name.split("/") [-1]
# that one give me the name I want - just hello
Name1 = Name.split(".") [0]
Is there any chance to simplify that doing the same job in ju... | split twice in the same expression? | Imagine I have the following:
inFile = "/adda/adas/sdas/hello.txt"
# that instruction give me hello.txt
Name = inFile.name.split("/") [-1]
# that one give me the name I want - just hello
Name1 = Name.split(".") [0]
Is there any chance to simplify that doing the same job in just one expression?
| [
"You can get what you want platform independently by using os.path.basename to get the last part of a path and then use os.path.splitext to get the filename without extension.\nfrom os.path import basename, splitext\n\npathname = \"/adda/adas/sdas/hello.txt\"\nname, extension = splitext(basename(pathname))\nprint n... | [
20,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0000324132_python.txt |
Q:
What is the equivalent of map > in Python?
In C++ often do something like this:
typedef map<int, vector<int> > MyIndexType;
Where I then use it like this:
MyIndexType myIndex;
for( ... some loop ...)
{
myIndex[someId].push_back(someVal);
}
If there was no entry in the map the code will insert a new empty vecto... | What is the equivalent of map > in Python? | In C++ often do something like this:
typedef map<int, vector<int> > MyIndexType;
Where I then use it like this:
MyIndexType myIndex;
for( ... some loop ...)
{
myIndex[someId].push_back(someVal);
}
If there was no entry in the map the code will insert a new empty vector and then append to it.
In Python it would look... | [
"You want to use:\nfrom collections import defaultdict\nmyIndex = defaultdict(list)\nmyIndex[someId].append(someVal)\n\nStandard Library defaultdict objects.\nExample usage from the Python documentation:\n>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]\n>>> d = defaultdict(list)\n>>> fo... | [
15,
10,
2,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0000324643_dictionary_python.txt |
Q:
JDBC & MSSQL seem to be truncating large fields
I'm using jython 2.2.1, and jdbc 1.2 and connecting to a mssql 2000 database, writing the contents of an email to it. When I get to the body of the email which can be quite large sometimes I need to truncate the data at 5000 chars. Except mssql & jdbc gang up on me l... | JDBC & MSSQL seem to be truncating large fields | I'm using jython 2.2.1, and jdbc 1.2 and connecting to a mssql 2000 database, writing the contents of an email to it. When I get to the body of the email which can be quite large sometimes I need to truncate the data at 5000 chars. Except mssql & jdbc gang up on me like school yard bullies, when i check the database lo... | [
"Deleted my answer - it was totally wrong. Keeping it here though so comments & conversation hang around.\nEDIT:\nAs you can read in the comments, here's what happened:\nThe data was being put into the database fine, but the MSSQL Query Manager could not display the Chinese characters.\n"
] | [
0
] | [] | [] | [
"jdbc",
"jython",
"python",
"sql_server"
] | stackoverflow_0000324945_jdbc_jython_python_sql_server.txt |
Q:
Strategies for speeding up batch ORM operations in Django
One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next:
for item in Something.objects.filter(x='y'):
... | Strategies for speeding up batch ORM operations in Django | One of my API calls can result in updates to a large number of objects (Django models). I'm running into performance issues with this since I'm updating each item individually, saving, and moving on to the next:
for item in Something.objects.filter(x='y'):
item.a="something"
item.save()
Sometimes my filter cri... | [
"The ticket you linked to is for bulk creation - if you're not relying on an overridden save method or pre/post save signals to do bits of work on save, QuerySet has an update method which you can use to perform an UPDATE on the filtered rows:\nSomething.objects.filter(x__in=['a', 'b', 'c']).update(a='something')\n... | [
15,
1
] | [] | [] | [
"batch_file",
"django",
"orm",
"python"
] | stackoverflow_0000324779_batch_file_django_orm_python.txt |
Q:
How to include output of PHP script in Python driven Plone site?
I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?
I was thinki... | How to include output of PHP script in Python driven Plone site? | I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?
I was thinking a long the lines of having a display.php that just runs display() a... | [
"Well, use AJAX to call the PHP script (yes, you will need apache) and display the output. Adding a custom JS to plone is trivial and this abstract the technology issue.\nJust be sure this is not a critical feature. Some users still deactivate JS and the web page should therefor degrade itself nicely.\n",
"Anothe... | [
1,
1,
0
] | [] | [] | [
"php",
"plone",
"python"
] | stackoverflow_0000320979_php_plone_python.txt |
Q:
How to analyse .exe parameters inside the program?
I have a program that can have a lot of parameters (we have over +30 differents options).
Example:
myProgram.exe -t alpha 1 -prod 1 2 -sleep 200
This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse... | How to analyse .exe parameters inside the program? | I have a program that can have a lot of parameters (we have over +30 differents options).
Example:
myProgram.exe -t alpha 1 -prod 1 2 -sleep 200
This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (sp... | [
"(Well, since this is tagged with Python):\nWe use Python's optparse module for this purpose. It has a much friendlier API than lots of ifs.\n",
"Create a hash table which stores function pointers (in C# that'd be delegates) for handling each of the parameters, keyed using the parameter text. Then you just go th... | [
6,
5,
5,
4,
1,
1,
1,
0,
0
] | [] | [] | [
".net",
"c#",
"java",
"python"
] | stackoverflow_0000323866_.net_c#_java_python.txt |
Q:
Problem with Boolean Expression with a string value from a lIst
I have the following problem:
# line is a line from a file that contains ["baa","beee","0"]
line = TcsLine.split(",")
NumPFCs = eval(line[2])
if NumPFCs==0:
print line
I want to print all the lines from the file if the second position of... | Problem with Boolean Expression with a string value from a lIst | I have the following problem:
# line is a line from a file that contains ["baa","beee","0"]
line = TcsLine.split(",")
NumPFCs = eval(line[2])
if NumPFCs==0:
print line
I want to print all the lines from the file if the second position of the list has a value == 0.
I print the lines but after that the foll... | [
"Let me explain a little what you do here.\nIf you write:\nNumPFCs = eval(line[2])\n\nthe order of evaluation is:\n\ntake the second character of the string line, i.e. a quote '\"'\neval this quote as a python expression, which is an error.\n\nIf you write it instead as:\nNumPFCs = eval(line)[2]\n\nthen the order o... | [
1,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0000324506_python.txt |
Q:
Python 2.5.2 and Solaris 8 (gcc 3.4.2) build issues
I'm trying to build python 2.5.2 on Solaris 8 using gcc 3.4.2. I can't see any immediate errors in the ./configure step but, once built and i enter the python shell doing an import time errors with :
Python 2.5.2 (r252:60911, Nov 21 2008, 18:45:42)
[GCC 3.4.2] o... | Python 2.5.2 and Solaris 8 (gcc 3.4.2) build issues | I'm trying to build python 2.5.2 on Solaris 8 using gcc 3.4.2. I can't see any immediate errors in the ./configure step but, once built and i enter the python shell doing an import time errors with :
Python 2.5.2 (r252:60911, Nov 21 2008, 18:45:42)
[GCC 3.4.2] on sunos5
Type "help", "copyright", "credits" or "license"... | [
"The time module is not built by default in Python, if you build from a source distribution you need to explicitly enable all the modules you want to compile. \nOpen up Modules/Setup.dist in the python source tree and comment out the line which says:\n\n#time timemodule.c\n\nTo enable the build of time module. Also... | [
2
] | [] | [] | [
"build_process",
"environment_variables",
"gcc",
"python",
"solaris"
] | stackoverflow_0000314749_build_process_environment_variables_gcc_python_solaris.txt |
Q:
Packaging a Python library
I have a few Munin plugins which report stats from an Autonomy database. They all use a small library which scrapes the XML status output for the relevant numbers.
I'm trying to bundle the library and plugins into a Puppet-installable RPM. The actual RPM-building should be straightforwar... | Packaging a Python library | I have a few Munin plugins which report stats from an Autonomy database. They all use a small library which scrapes the XML status output for the relevant numbers.
I'm trying to bundle the library and plugins into a Puppet-installable RPM. The actual RPM-building should be straightforward; once I have a distutils-produ... | [
"You need to create a package to do what you want. You'd need a directory named idol7stats containing a file called __init__.py and any other library modules to package. Also, this will affect your scripts' imports; if you put idol7stats.py in a package called idol7stats, then your scripts need to \"import idol7s... | [
2
] | [] | [] | [
"distutils",
"packaging",
"python"
] | stackoverflow_0000326254_distutils_packaging_python.txt |
Q:
How can I dynamically get the set of classes from the current python module?
I have a python module that defines a number of classes:
class A(object):
def __call__(self):
print "ran a"
class B(object):
def __call__(self):
print "ran b"
class C(object):
def __call__(self):
prin... | How can I dynamically get the set of classes from the current python module? | I have a python module that defines a number of classes:
class A(object):
def __call__(self):
print "ran a"
class B(object):
def __call__(self):
print "ran b"
class C(object):
def __call__(self):
print "ran c"
From within the module, how might I add an attribute that gives me all ... | [
"import sys\ngetattr(sys.modules[__name__], 'A')\n\n",
"You can smash this into one for statement, but that'd have messy code duplication.\nimport sys\nimport types\nthis_module = sys.modules[__name__]\n[x for x in\n [getattr(this_module, x) for x in dir(this_module)]\n if type(x) == types.ClassType]\n\n",
... | [
10,
6,
3
] | [] | [] | [
"metaprogramming",
"python",
"reflection"
] | stackoverflow_0000326770_metaprogramming_python_reflection.txt |
Q:
Best language choice for a spam detection service
I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks a... | Best language choice for a spam detection service | I have around 20 or so active blogs that get quite a bit of spam. As I hate CAPCHA the alternative is very smart spam filtering. I want to build a simple REST api like spam checking service which I would use in all my blogs. That way I can consolidate IP blocks and offload spam detection to 3rd party such as Akisment... | [
"My first question - why don't you just use one of those three services you listed? It seems they do exactly what you want. Sorry for being cynical, but I doubt that you working alone could in a reasonable amount of time beat the software engineers designing the algorithms used at those websites, especially conside... | [
9,
2,
1,
1
] | [] | [] | [
"mysql",
"php",
"python",
"ruby",
"spam_prevention"
] | stackoverflow_0000326401_mysql_php_python_ruby_spam_prevention.txt |
Q:
using curses with raw_input in python
In my python linux console application I use curses to handle displaying of data. At the same time I'd like to have an input line to enter commands, pretty much in good ol' irssi-style. With default curses getch() I'd have to do a lot of coding just to get the basic funcionali... | using curses with raw_input in python | In my python linux console application I use curses to handle displaying of data. At the same time I'd like to have an input line to enter commands, pretty much in good ol' irssi-style. With default curses getch() I'd have to do a lot of coding just to get the basic funcionality of raw_input function - arrow keys to mo... | [
"Use curses.textpad\nhttp://www.python.org/doc/2.4.1/lib/module-curses.textpad.html\n"
] | [
1
] | [] | [] | [
"console_application",
"ncurses",
"python"
] | stackoverflow_0000326922_console_application_ncurses_python.txt |
Q:
How do you create a simple Google Talk Client using the Twisted Words Python library?
I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.
Has anybody... | How do you create a simple Google Talk Client using the Twisted Words Python library? | I am interested in making a Google Talk client using Python and would like to use the Twisted libraries Words module. I have looked at the examples, but they don't work with the current implementation of Google Talk.
Has anybody had any luck with this? Would you mind documenting a brief tutorial?
As a simple task, I'... | [
"wokkel is the future of twisted words. metajack wrote a really nice blog post on getting started.\nIf you want a nice, functional sample project to start with, check out my whatsup bot.\n",
"I have written a simple Jabber bot (and thus Google talk bot) using the xmpppy library, which works well. The examples on... | [
14,
7,
2
] | [
"As the Twisted libs seem to be out of date, you have two choices:\nImplement your own XMPP-handler or look for another library.\nI would suggest working with the raw XML; XMPP is not that complicated and you are bound to learn something.\n"
] | [
-2
] | [
"google_talk",
"python",
"twisted",
"xmpp"
] | stackoverflow_0000227279_google_talk_python_twisted_xmpp.txt |
Q:
How to call python2.5 function from x86asm/x64asm?
I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit:
What does a python object look like... | How to call python2.5 function from x86asm/x64asm? | I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit:
What does a python object look like in memory?
How can I call a python function?
How can I ... | [
"You will want to read and understand Extending and Embedding the Python Interpreter and the Python/C API Reference Manual. This describes how to interface with Python from C. Everything you can do in C you can equivalently do in assembly code too, but you're on your own for this as it is not directly described fro... | [
3,
1
] | [] | [] | [
"assembly",
"python"
] | stackoverflow_0000319232_assembly_python.txt |
Q:
how to draw lines on a picture background in pygame
I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.
Can anyone point me to some example code that does this?
A:
This should do what you're asking for:
# load the image
imag... | how to draw lines on a picture background in pygame | I would like to draw lines (of arbitrary position and length) onto a surface in pygame, which itself is an image loaded from a file on disk.
Can anyone point me to some example code that does this?
| [
"This should do what you're asking for:\n# load the image\nimage = pygame.image.load(\"some_image.png\")\n\n# draw a yellow line on the image\npygame.draw.line(image, (255, 255, 0), (0, 0), (100, 100))\n\nTypically you don't draw to the original image, since you'll have to reload the image to get the original back ... | [
3,
0
] | [] | [] | [
"drawing",
"pygame",
"python"
] | stackoverflow_0000327896_drawing_pygame_python.txt |
Q:
Is there a library similar to pyparsing in Java?
I need to quickly build a parser for a very simplified version of a html-like markup language in Java. In python, I would use pyparsing library to do this. Is there something similar for Java? Please, don't suggest libraries already out there for html parsing, my ap... | Is there a library similar to pyparsing in Java? | I need to quickly build a parser for a very simplified version of a html-like markup language in Java. In python, I would use pyparsing library to do this. Is there something similar for Java? Please, don't suggest libraries already out there for html parsing, my application is a school assignment which will demonstrat... | [
"Another good parser generator is ANTLR, that might be what you're looking for.\n",
"May be overkill for your use, but javacc is an excellent industrial-strength parser generator. I've used this program/library several times, its reliable and worth learning, particularly if you are going to work with languages a... | [
8,
3,
3,
2,
1
] | [] | [] | [
"java",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0000327569_java_parsing_pyparsing_python.txt |
Q:
wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object
If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to th... | wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object | If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to the SetNumberRows and SetNumberCols? Basically I am looking for guidance on how to work with th... | [
"Use a wxGrid with a wxGridTableBase instead\nHere is a simple example:\nimport wx, wx.grid\n\nclass GridData(wx.grid.PyGridTableBase):\n _cols = \"a b c\".split()\n _data = [\n \"1 2 3\".split(),\n \"4 5 6\".split(),\n \"7 8 9\".split()\n ]\n\n def GetColLabelValue(self, col):\n ... | [
4
] | [] | [] | [
"python",
"spreadsheet",
"wxpython",
"wxwidgets"
] | stackoverflow_0000328003_python_spreadsheet_wxpython_wxwidgets.txt |
Q:
Scripting language choice for initial performance
I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX.
The existin... | Scripting language choice for initial performance | I have a small lightweight application that is used as part of a larger solution. Currently it is written in C but I am looking to rewrite it using a cross-platform scripting language. The solution needs to run on Windows, Linux, Solaris, AIX and HP-UX.
The existing C application works fine but I want to have a single ... | [
"Lua is a scripting language that meets your criteria. It's certainly the fastest and lowest memory scripting language available.\n",
"Because of your requirement for fast startup time and a calling frequency greater than 1Hz I'd recommend either staying with C and figuring out how to make it portable (not always... | [
23,
9,
6,
5,
4,
3,
3,
2,
0,
0,
0,
0,
0
] | [] | [] | [
"bash",
"perl",
"python",
"ruby",
"scripting_language"
] | stackoverflow_0000328041_bash_perl_python_ruby_scripting_language.txt |
Q:
storing unbound python functions in a class object
I'm trying to do the following in python:
In a file called foo.py:
# simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for stora... | storing unbound python functions in a class object | I'm trying to do the following in python:
In a file called foo.py:
# simple function that does something:
def myFunction(a,b,c):
print "call to myFunction:",a,b,c
# class used to store some data:
class data:
fn = None
# assign function to the class for storage.
data.fn = myFunction
And then in a file called bar.... | [
"data.fn = staticmethod(myFunction)\n\nshould do the trick.\n",
"What you can do is:\nd = foo.data()\nd.fn = myFunction\n\nd.fn(1,2,3)\n\nWhich may not be exactly what you want, but does work.\n",
"Thanks to Andre for the answer - so simple!\nFor those of you who care, perhaps I should have included the entire ... | [
27,
1,
0
] | [] | [] | [
"function",
"python"
] | stackoverflow_0000327483_function_python.txt |
Q:
Monitoring a displays state in python?
How can I tell when Windows is changing a monitors power state?
A:
It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a WM_SYSCOMMAND to the topmost window with a wParam of SC_SCREENSAVE (to start the screen saver) or a wParam ... | Monitoring a displays state in python? | How can I tell when Windows is changing a monitors power state?
| [
"It seems that, when Windows wants to start the screen saver or turn the monitor off, it will send a WM_SYSCOMMAND to the topmost window with a wParam of SC_SCREENSAVE (to start the screen saver) or a wParam of SC_MONITORPOWER and a lParam of 1 or 2 (to turn the monitor off). This message will then be passed to Def... | [
7
] | [] | [] | [
"python",
"winapi"
] | stackoverflow_0000328490_python_winapi.txt |
Q:
python curses.ascii depending on locale?
The curses.ascii module has some nice functions defined, that allow for example to recognize which characters are printable (curses.ascii.isprint(ch)).
But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are cer... | python curses.ascii depending on locale? | The curses.ascii module has some nice functions defined, that allow for example to recognize which characters are printable (curses.ascii.isprint(ch)).
But, diffrent character codes can be printable depending on which locale setting is being used. For example, there are certain polish characters:
>>> ord('a')
97
>>> or... | [
"If you convert the character to a unicode then you can use unicodedata:\n>>> unicodedata.category(u'ą')[0] in 'LNPS'\nTrue\n\n",
"Well, it is called curses.ascii, so using ASCII rules for what's printable should not be a surprise. If you are using an ISO 8-bit code, or you are operating from a known code page, ... | [
4,
2
] | [] | [] | [
"locale",
"ncurses",
"python"
] | stackoverflow_0000328793_locale_ncurses_python.txt |
Q:
In Python, is there a concise way to use a list comprehension with multiple iterators?
Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code:
[(i,j) | i <- [1,2], j <- [1..4]]
which yields
[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2... | In Python, is there a concise way to use a list comprehension with multiple iterators? | Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following Haskell code:
[(i,j) | i <- [1,2], j <- [1..4]]
which yields
[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]
Can I obtain a similar behavior in Python in a concise way?
| [
"Are you asking about this?\n[ (i,j) for i in range(1,3) for j in range(1,5) ]\n\n",
"Cartesian product is in the itertools module (in 2.6).\n>>> import itertools\n>>> list(itertools.product(range(1, 3), range(1, 5)))\n[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]\n\n",
"Fun fact about the ne... | [
21,
8,
5,
2
] | [] | [] | [
"iterator",
"list_comprehension",
"python"
] | stackoverflow_0000329886_iterator_list_comprehension_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.