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:
Creating equivalent classes in Python?
I played around with overloading or masking classes in Python. Do the following code examples create equivalent classes?
class CustASample(object):
def __init__(self):
self.__class__.__name__ = "Sample"
def doSomething(self):
dummy = 1
and
class Sa... | Creating equivalent classes in Python? | I played around with overloading or masking classes in Python. Do the following code examples create equivalent classes?
class CustASample(object):
def __init__(self):
self.__class__.__name__ = "Sample"
def doSomething(self):
dummy = 1
and
class Sample(object):
def doSomething(self):
... | [
"No, they are still different.\na = CustASample()\nb = Sample()\na.__class__ is b.__class__\n-> False\n\nHere's how you could do it:\nclass A(object):\n def __init__(self):\n self.__class__ = B\n\nclass B(object):\n def bark(self):\n print \"Wuff!\"\n\na = A()\nb = B()\na.__class__ is b.__class__... | [
10,
0
] | [] | [] | [
"python"
] | stackoverflow_0001999551_python.txt |
Q:
is there a way to append the etag at the end of the static resources in django
In rails, if I import a css file or javascript file, the url will be like this
<script type="text/javascript" src="some.js?<ETag here>"></script>
if I upgrade the some.js the etag will be changed, so my browser can cache the static res... | is there a way to append the etag at the end of the static resources in django | In rails, if I import a css file or javascript file, the url will be like this
<script type="text/javascript" src="some.js?<ETag here>"></script>
if I upgrade the some.js the etag will be changed, so my browser can cache the static resource smartly and update the cache when necessary.
Is there a way to do it in django... | [
"Maybe django-static can help you on this ..\n\ndjango_static is a Django app that enables as various template tags for better serving your static content. It basically rewrites references to static files and where applicable it does whitespace optmization of the content.\nBy making references to static content uni... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002000306_django_python.txt |
Q:
Using Python csv module on updating file
I am using python's csv module to extract data from a csv that is constantly being updated by an external tool. I have run into a problem where when I reach the end of the file I get a StopIteration error, however, I would like the script to continue to loop waiting for mo... | Using Python csv module on updating file | I am using python's csv module to extract data from a csv that is constantly being updated by an external tool. I have run into a problem where when I reach the end of the file I get a StopIteration error, however, I would like the script to continue to loop waiting for more lines to be added by the external tool.
Wha... | [
"Your problem is not with the CSV reader, but with the file object itself. You may still have to do the crazy gyrations you're doing in your snippet above, but it would be better to create a file object wrapper or subclass that does it for you, and use that with your CSV reader. That keeps the complexity isolated... | [
4,
2,
0
] | [] | [] | [
"csv",
"file",
"python"
] | stackoverflow_0002001201_csv_file_python.txt |
Q:
Cannot understand how to get data from checklistbox in wxpython
I am trying to get either the strings checked or the integers from a check list. I cannot seem to get it anywhere. In the code below, you'll see a bunch of un-commented code, those are just different ways I've tried. I thought I would leave them in ca... | Cannot understand how to get data from checklistbox in wxpython | I am trying to get either the strings checked or the integers from a check list. I cannot seem to get it anywhere. In the code below, you'll see a bunch of un-commented code, those are just different ways I've tried. I thought I would leave them in case any one's suggestions have to do with it. I am very new to GUI-pro... | [
"checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]\n\ncitList.GetChecked() should have also completed the task for you. May the problem be that you are trying to get selected items in __init__?\nUpd.: You do not want to get checked items during __init__ - they cannot be checked by the us... | [
3
] | [] | [] | [
"python",
"user_interface",
"wxpython"
] | stackoverflow_0002001703_python_user_interface_wxpython.txt |
Q:
python, and unicode stderr
I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?
UPDATE 2010-01-03:
Thank you for the reply, but it seems the str.enc... | python, and unicode stderr | I used an anonymous pipe to capture all stdout,and stderr then print into a richedit, it's ok when i use wsprintf ,but the python using multibyte char that really annoy me. how can I convert all these output to unicode?
UPDATE 2010-01-03:
Thank you for the reply, but it seems the str.encode() only worked with print xxx... | [
"First, please remember that on Windows console may not fully support Unicode.\nThe example below does make python output to stderr and stdout using UTF-8. If you want you could change it to other encodings.\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport codecs, sys\n\nreload(sys)\nsys.setdefaultencoding('ut... | [
9,
0
] | [
"wsprintf?\nThis seems to be a \"C/C++\" question rather than a Python question.\nThe Python interpreter always writes bytestrings to stdout/stderr, rather than unicode (or \"wide\") strings. It means Python first encodes all unicode data using the current encoding (likely sys.getdefaultencoding()).\nIf you want to... | [
-1
] | [
"python",
"stderr",
"unicode"
] | stackoverflow_0001994157_python_stderr_unicode.txt |
Q:
python hebrew input\filesytem format
import os
import pprint
import subprocess
def Convert (dir):
curDir = dir
pathToBonk = "C:\\Program Files\\BonkEnc\\becmd.exe" #Where the becmd.exe file lives
problemFiles = [] #A list of files that failed conversion
#
for item in os.listdir(curDir):
... | python hebrew input\filesytem format | import os
import pprint
import subprocess
def Convert (dir):
curDir = dir
pathToBonk = "C:\\Program Files\\BonkEnc\\becmd.exe" #Where the becmd.exe file lives
problemFiles = [] #A list of files that failed conversion
#
for item in os.listdir(curDir):
if item.upper().endswith('.M4A'):
... | [
"Just use os.listdir(unicode(str)) instead of os.listdir(str) in order to be sure that str is Unicode, otherwise it will just fail.\nSame problem can be found on this question\n"
] | [
0
] | [] | [] | [
"hebrew",
"python",
"unicode"
] | stackoverflow_0001993402_hebrew_python_unicode.txt |
Q:
Launch script on any network connection
On linux (ubuntu), is it possible to execute a script upon any incoming network connection?
During long periods inactivity on my home server, I plan on stopping the software raid, parking the data disks and restarting the raid array upon encountering an incoming network con... | Launch script on any network connection | On linux (ubuntu), is it possible to execute a script upon any incoming network connection?
During long periods inactivity on my home server, I plan on stopping the software raid, parking the data disks and restarting the raid array upon encountering an incoming network connection.
I've been researching this problem a... | [
"Take a look at netfilter/iptables. You may be able to write code to use the userspace API libraries to detect incoming packet events.\n"
] | [
1
] | [] | [] | [
"linux",
"python",
"ubuntu"
] | stackoverflow_0002001174_linux_python_ubuntu.txt |
Q:
Python CGI transaction
I have a Python CGI handling a payment transaction. When the user submits the form, the CGI is called. After submission, the CGI takes a while to perform the credit card transaction. During that time, a user might hit the ESC or refresh button. Doing that will not "kill" the CGI, meaning, th... | Python CGI transaction | I have a Python CGI handling a payment transaction. When the user submits the form, the CGI is called. After submission, the CGI takes a while to perform the credit card transaction. During that time, a user might hit the ESC or refresh button. Doing that will not "kill" the CGI, meaning, the script will keep running c... | [
"Same as you should do with every POST: don't send output, but put the output in a session variable and redirect to a pure-GET request. This one looks in the session for messages, and clears+displays those.\n"
] | [
3
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0002002180_cgi_python.txt |
Q:
Python: Separating the GUI process from the core logic process
I'm developing a Python project for dealing with computer simulations, and I'm also developing a GUI for it. (The core logic itself does not require a GUI.) The GUI toolkit I use for is wxPython, but I think my question is general enough not to depend ... | Python: Separating the GUI process from the core logic process | I'm developing a Python project for dealing with computer simulations, and I'm also developing a GUI for it. (The core logic itself does not require a GUI.) The GUI toolkit I use for is wxPython, but I think my question is general enough not to depend on it.
The way that the GUI currently works is that it starts the co... | [
"You might find some inspiration here: http://wiki.wxpython.org/LongRunningTasks, however it is for multithreading, not multiprocessing.\nThe basic idea\n\nfor multithreading: use an event queue to communicate between the GUI and the processing thread.\nfor multiprocessing: maybe use the subprocess package, and use... | [
6,
2,
2,
1,
0
] | [] | [] | [
"multiprocessing",
"python",
"user_experience",
"user_interface"
] | stackoverflow_0001961203_multiprocessing_python_user_experience_user_interface.txt |
Q:
Why does it print funny characters? unicode problem?
The user entered the word
éclair
into the search box.
Showing results 1 - 10 of about 140 for �air.
Why does it show the weird question mark?
I'm using Django to display it:
Showing results 1 - 10 of about 140 for {{query|safe}}
A:
It's an encoding problem.... | Why does it print funny characters? unicode problem? | The user entered the word
éclair
into the search box.
Showing results 1 - 10 of about 140 for �air.
Why does it show the weird question mark?
I'm using Django to display it:
Showing results 1 - 10 of about 140 for {{query|safe}}
| [
"It's an encoding problem. Most likely your form or the output page is not UTF-8 encoded.\nThis article is very good reading on the issue: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)\nYou need to check the encoding of\n\nthe HTML page... | [
8,
1,
0,
0,
0
] | [] | [] | [
"django",
"encoding",
"python",
"unicode"
] | stackoverflow_0001998967_django_encoding_python_unicode.txt |
Q:
PyQt4 - Widget Is Not Shown
I've made this program in Python and Qt4.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
... | PyQt4 - Widget Is Not Shown | I've made this program in Python and Qt4.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
color = QtGui.QColor(99, 0, 0)
class colorButton(QtGui.QWidget):
def __init__(self, args):
QtGui.QWidget.__init__(self,args)
self.setGeometry(150, 22, 5... | [
"Your class colorButton inherits from QWidget, yet you are calling QPushButton.__init__() in the constructor. Maybe you want it to inherit from QPushButton?\nBy using the following class definition, your code works for me:\nclass colorButton(QtGui.QPushButton):\n def __init__(self, *args):\n QtGui.QPushBu... | [
4,
2,
0,
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"qwidget"
] | stackoverflow_0002000466_pyqt_pyqt4_python_qwidget.txt |
Q:
Creating an MS Office document-like file format to expose document properties
Our application's "documents" are single binary files.
Our customers have asked if we can add MS Office-like document properties to our document files so that they are easier for users to manage. By easier to manage, I mean the ability f... | Creating an MS Office document-like file format to expose document properties | Our application's "documents" are single binary files.
Our customers have asked if we can add MS Office-like document properties to our document files so that they are easier for users to manage. By easier to manage, I mean the ability for Windows Explorer to display common document properties in tooltips.
My research ... | [
"I'm pretty sure your best answer is to use the OLE compound document.\nMicrosoft may have stopped using this, but that is because they have gone to an XML file format. Unless you are willing to convert from your current file format to XML, I do not think that the new standard for tags will be interesting for you.... | [
3,
0
] | [] | [] | [
"file",
"file_properties",
"python",
"winapi"
] | stackoverflow_0001996162_file_file_properties_python_winapi.txt |
Q:
how can i use '__set__'
class A(object):
def __get__(self, instance, owner):#why i can't find argument 'key',where is 'key'
#print ower.instance
print instance,owner
def __set__(self,instance,value):
instance=value
class X(object):
a = A()
xx=X()
xx.a='aaa'
print xx.a#None
A:... | how can i use '__set__' | class A(object):
def __get__(self, instance, owner):#why i can't find argument 'key',where is 'key'
#print ower.instance
print instance,owner
def __set__(self,instance,value):
instance=value
class X(object):
a = A()
xx=X()
xx.a='aaa'
print xx.a#None
| [
"Hettinger's HowTo Guide for Descriptors covers this well. Quoting from it:\n\nDescriptor Protocol\ndescr.__get__(self, obj, type=None) --> value\ndescr.__set__(self, obj, value) --> None\ndescr.__delete__(self, obj) --> None\nThat is all there is to it.\n\nSo, you can name the arguments however you wish, but there... | [
4,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0002003284_python.txt |
Q:
Alternative to PyGObject?
Does anyone have an alternative to using PyGObject? I can't seem to get it to run at all in Mac OS X. I'm trying to use papyon, which fails amazingly well if GObject isn't around.
A:
By its description, it is used for async I/O only. You can try to rework the library to use any of the o... | Alternative to PyGObject? | Does anyone have an alternative to using PyGObject? I can't seem to get it to run at all in Mac OS X. I'm trying to use papyon, which fails amazingly well if GObject isn't around.
| [
"By its description, it is used for async I/O only. You can try to rework the library to use any of the other Python async libraries, like asyncore, Twisted, or any other.\nAlso, getting PyGObject on Mac OS X is hard, but you can try to use the one from macports, macports being the new name for darwinports\n",
"... | [
3,
0
] | [] | [] | [
"gobject",
"pygobject",
"python"
] | stackoverflow_0002002119_gobject_pygobject_python.txt |
Q:
Javascript lexer / tokenizer (in Python?)
Does anyone know of a Javascript lexical analyzer or tokenizer (preferably in Python?)
Basically, given an arbitrary Javascript file, I want to grab the tokens.
e.g.
foo = 1
becomes something like:
variable name : "foo"
whitespace
operator : equals
whitespace
integer : 1
... | Javascript lexer / tokenizer (in Python?) | Does anyone know of a Javascript lexical analyzer or tokenizer (preferably in Python?)
Basically, given an arbitrary Javascript file, I want to grab the tokens.
e.g.
foo = 1
becomes something like:
variable name : "foo"
whitespace
operator : equals
whitespace
integer : 1
| [
"http://code.google.com/p/pynarcissus/ has one.\nAlso I made one but it doesn't support automatic semicolon insertion so it is pretty useless for javascript that you have no control over (as almost all real life javascript programs lack at least one semicolon) :) Here is mine:\nhttp://bitbucket.org/santagada/jaspyo... | [
2
] | [] | [] | [
"javascript",
"lex",
"python",
"tokenize",
"yacc"
] | stackoverflow_0002001796_javascript_lex_python_tokenize_yacc.txt |
Q:
Should I use Lex or a home-brewed solution to parse a formula?
I'm in the process of writing a small, rule-based 'math' engine. I realize this is unclear, so I'll provide a small example.
Let's say you have some variable a, that holds an integer. You also have some functions you can apply to the number, i.e.
sqr ... | Should I use Lex or a home-brewed solution to parse a formula? | I'm in the process of writing a small, rule-based 'math' engine. I realize this is unclear, so I'll provide a small example.
Let's say you have some variable a, that holds an integer. You also have some functions you can apply to the number, i.e.
sqr - square the number
flp - flip the bits of the number
dec - decremen... | [
"If your grammar isn't super-complex and you don't mind doing it in Python, pyparsing could be just what the doctor ordered. I implemented something fairly similar for parsing chemical equations and it took me an hour or so to do it. I'd add the code here, but it wouldn't be particularly relevant. \n",
"Yes, seem... | [
3,
1,
0,
0
] | [
"If you have some free time and want to learn a new programming paradigm, give Prolog a spin!\n"
] | [
-1
] | [
"lex",
"ply",
"python"
] | stackoverflow_0002001504_lex_ply_python.txt |
Q:
How to force Python to ignore re.DOTALL in re.findall() statement?
I have been banging my head against the keyboard in search of enlightenment through Google and all Python docs I could get my hands on, but could not find an answer to an issue I'm encountering.
I have the following regex that I run against a websi... | How to force Python to ignore re.DOTALL in re.findall() statement? | I have been banging my head against the keyboard in search of enlightenment through Google and all Python docs I could get my hands on, but could not find an answer to an issue I'm encountering.
I have the following regex that I run against a website, but Python insists in setting re.DOTALL on it, even though my code d... | [
".+> should change to [^>]+> and\n.*?> to [^>]*>\nYou can try replacing others dots into [^\\r\\n] too, but above 2 changes should be enough.\n"
] | [
2
] | [] | [] | [
"flags",
"python",
"regex"
] | stackoverflow_0002003461_flags_python_regex.txt |
Q:
Convert a curl POST request to Python only using standard library
I would like to convert this curl command to something that I can use in Python for an existing script.
curl -u 7898678:X -H 'Content-Type: application/json' \
-d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json
TEXT is what i woul... | Convert a curl POST request to Python only using standard library | I would like to convert this curl command to something that I can use in Python for an existing script.
curl -u 7898678:X -H 'Content-Type: application/json' \
-d '{"message":{"body":"TEXT"}}' http://sample.com/36576/speak.json
TEXT is what i would like to replace with a message generated by the rest of the script.(W... | [
"\nI would like this to work with the standard library if possible.\n\nThe standard library provides urllib and httplib for working with URLs:\n>>> import httplib, urllib\n>>> params = urllib.urlencode({'apple': 1, 'banana': 2, 'coconut': 'yummy'})\n>>> headers = {\"Content-type\": \"application/x-www-form-urlencod... | [
24,
12,
2,
1
] | [] | [] | [
"curl",
"json",
"python"
] | stackoverflow_0001990976_curl_json_python.txt |
Q:
ImageFont's getsize() does not get correct text size?
I use the following two methods to to generate text preview image for a .ttf font file
PIL method:
def make_preview(text, fontfile, imagefile, fontsize=30):
try:
font = ImageFont.truetype(fontfile, fontsize)
text_width, text_height = font.ge... | ImageFont's getsize() does not get correct text size? | I use the following two methods to to generate text preview image for a .ttf font file
PIL method:
def make_preview(text, fontfile, imagefile, fontsize=30):
try:
font = ImageFont.truetype(fontfile, fontsize)
text_width, text_height = font.getsize(text)
img = Image.new('RGBA', (text_width, te... | [
"\n\nNot a programming solution, but when I regenerate your problem, its only happens on your fonts (other fonts like Arial is no problem at all), so I have fixed your font files (by changing ascent/decent metrics). you can download here, \nAnd sorry about Hanford Script Font, its not perfect as you see, height see... | [
5,
2,
1
] | [] | [] | [
"fonts",
"imagemagick",
"python",
"python_imaging_library"
] | stackoverflow_0001965466_fonts_imagemagick_python_python_imaging_library.txt |
Q:
where is the '__path__' comes from
i can't find who defined the '__path__',why '__path__' can be use.
import os
import sys
import warnings
import ConfigParser # ConfigParser is not a virtualenv module, so we can use it to find the stdlib
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(C... | where is the '__path__' comes from | i can't find who defined the '__path__',why '__path__' can be use.
import os
import sys
import warnings
import ConfigParser # ConfigParser is not a virtualenv module, so we can use it to find the stdlib
dirname = os.path.dirname
distutils_path = os.path.join(os.path.dirname(ConfigParser.__file__), 'distutils')
if o... | [
"You really need to read some Python documentation and learn the basics of the language.\nI checked, and you seem to speak Chinese. Here are Python documentation resources in Chinese:\nhttp://www6.uniovi.es/python/doc/NonEnglish.html#chinese\nNow, to answer your question. I wasn't sure what the answer was, so I u... | [
7,
3
] | [] | [] | [
"python"
] | stackoverflow_0002003859_python.txt |
Q:
Python ftplib: Overwriting a File doesn't work with STOR
I want to overwrite an existing file "test.txt" on my ftp server with this code:
from ftplib import FTP
HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
ftp = FTP(HOST)
ftp.login(FTP_NAME, FTP_PASS)
file = open('test.txt', 'r')
ftp.storlines('... | Python ftplib: Overwriting a File doesn't work with STOR | I want to overwrite an existing file "test.txt" on my ftp server with this code:
from ftplib import FTP
HOST = 'host.com'
FTP_NAME = 'username'
FTP_PASS = 'password'
ftp = FTP(HOST)
ftp.login(FTP_NAME, FTP_PASS)
file = open('test.txt', 'r')
ftp.storlines('STOR test.txt', file)
ftp.quit()
file.close()
I don't get any... | [
"nvm, it's my fault...\nI forgot to change the current working directory to /public_html\nthanks anyway!\n"
] | [
1
] | [
"I think you need to open the file in write mode\nfile = open('test.txt', 'w')\n\n"
] | [
-2
] | [
"file_upload",
"ftp",
"python"
] | stackoverflow_0002003863_file_upload_ftp_python.txt |
Q:
Ready-made Javascript library for modelling card games?
MVC 'architecture'. I would like a convenient way of specifying the rules of a card game including aspects such as hands or tricks, scoring, which cards from the deck or pack are used, and so on. Does anyone know of anything like this, preferably in Javascrip... | Ready-made Javascript library for modelling card games? | MVC 'architecture'. I would like a convenient way of specifying the rules of a card game including aspects such as hands or tricks, scoring, which cards from the deck or pack are used, and so on. Does anyone know of anything like this, preferably in Javascript?
Thanks for any guidance.
| [
"There's a good article here (and as a complement I suggest the companion article about displaying playing cards with CSS that's here). Nothing much to do with Python though!-) If you do want an example of handling a card game (including showing the cards as images in Tkinter) with Python, try this one (which howev... | [
3,
1
] | [] | [] | [
"game_engine",
"javascript",
"model_view_controller",
"playing_cards",
"python"
] | stackoverflow_0001996285_game_engine_javascript_model_view_controller_playing_cards_python.txt |
Q:
Python equivalent of PyErr_Print()
What is the Python API equivalent of PyErr_Print(), from the C interface?
I'm assuming a call in either the sys, or traceback modules, but can't find any functions therein that make calls to PyErr_Print().
Addendum
I'm after the Python call to get the same functionality as PyErr_... | Python equivalent of PyErr_Print() | What is the Python API equivalent of PyErr_Print(), from the C interface?
I'm assuming a call in either the sys, or traceback modules, but can't find any functions therein that make calls to PyErr_Print().
Addendum
I'm after the Python call to get the same functionality as PyErr_PrintEx(), described as:
Print a standar... | [
"There's no Python function that's exactly equivalent to PyErr_PrintEx (the real name of PyErr_Print;-), including for example setting sys.last_traceback and friends (which are only supposed to be set to help a post-mortem debugging from the interactive interpreter for exceptions which have not been caught). What ... | [
2
] | [] | [] | [
"c",
"cpython",
"python",
"sys",
"traceback"
] | stackoverflow_0002004400_c_cpython_python_sys_traceback.txt |
Q:
Nested Scopes and Lambdas
def funct():
x = 4
action = (lambda n: x ** n)
return action
x = funct()
print(x(2)) # prints 16
... I don't quite understand why 2 is assigned to n automatically?
A:
n is the argument of the anonymous function returned by funct. An exactly equivalent defintion of funct i... | Nested Scopes and Lambdas | def funct():
x = 4
action = (lambda n: x ** n)
return action
x = funct()
print(x(2)) # prints 16
... I don't quite understand why 2 is assigned to n automatically?
| [
"n is the argument of the anonymous function returned by funct. An exactly equivalent defintion of funct is \ndef funct():\n x = 4\n def action(n):\n return x ** n\n return action\n\nDoes this form make any more sense?\n",
"It's not assigned \"automatically\": it's assigned very explicitly and no... | [
5,
3
] | [] | [] | [
"lambda",
"nested",
"python"
] | stackoverflow_0002004398_lambda_nested_python.txt |
Q:
How to mimic vb's control array in python for win32com?
I need to dynamically create com objects from an activex dll and each of the objects can raise events which should be handled with event handlers.
I can do this easily with win32com.client.Dispatch and win32com.client.WithEvents and associate a "separate" cla... | How to mimic vb's control array in python for win32com? | I need to dynamically create com objects from an activex dll and each of the objects can raise events which should be handled with event handlers.
I can do this easily with win32com.client.Dispatch and win32com.client.WithEvents and associate a "separate" class of event handlers with each of the objects. Like so:
class... | [
"Control Arrays were removed in VB.NET so I don't think they would be supported in the win32com. \nNot sure if this would work for you but can you pass the index to the EventHandler class?\nclass MyEventHandler:\n def __init__(self, index):\n self.obj_index = index\n\n def OnEvent(self):\n print... | [
0,
0
] | [] | [] | [
"python",
"win32com"
] | stackoverflow_0001998186_python_win32com.txt |
Q:
Regex match of hexdigest in google app engine webapp WSGIApplication
application = webapp.WSGIApplication(
[(r'/main/profile/([a-f0-9]{40})', ProfileHandler)],
debug=True)
The regex in the above parameter will not recognize a 40 hex long hexdigest in Google App Engine.
I'm getting 404s instead of ProfileH... | Regex match of hexdigest in google app engine webapp WSGIApplication | application = webapp.WSGIApplication(
[(r'/main/profile/([a-f0-9]{40})', ProfileHandler)],
debug=True)
The regex in the above parameter will not recognize a 40 hex long hexdigest in Google App Engine.
I'm getting 404s instead of ProfileHandler being passed the matching 40 hex long profile ID. My app.yaml passe... | [
"I can not reproduce your problem. Here is an exact code I have:\nindex.py\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass ProfileHandler(webapp.RequestHandler): \n def get(self, *ar, **kw):\n self.response.out.write(\"PROFILE IS:\" + ar[0])\n\n... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python",
"regex",
"web_applications"
] | stackoverflow_0002004691_google_app_engine_python_regex_web_applications.txt |
Q:
How to debug Jinja2 template?
I am using jinja2 template system into django.
It is really fast and I like it a lot.
Nevertheless, I have some problem to debug templates :
If I make some errors into a template (bad tag, bad filtername, bad end of block...), I do not have at all information about this error.
For exa... | How to debug Jinja2 template? | I am using jinja2 template system into django.
It is really fast and I like it a lot.
Nevertheless, I have some problem to debug templates :
If I make some errors into a template (bad tag, bad filtername, bad end of block...), I do not have at all information about this error.
For example, In a django view, I write thi... | [
"After doing some more test, I found the answer :\nBy doing the same template test, directly under python, without using django, debug messages are present. So it comes from django.\nThe fix is in settings.py : One have to set DEBUG to True AND set TEMPLATE_DEBUG to False.\n",
"From the Jinja2 Documentation:\n\nM... | [
16,
7
] | [] | [] | [
"django",
"jinja2",
"python"
] | stackoverflow_0002002357_django_jinja2_python.txt |
Q:
Qt Python Calendar: selected day direct access
I have calendar that is working fine.
Here is the function that display the full date:
def selectDate(self,date):
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate
And here the code wi... | Qt Python Calendar: selected day direct access | I have calendar that is working fine.
Here is the function that display the full date:
def selectDate(self,date):
self.fullDate = str(date.day()) + " / " + str(date.month()) + " / " + str(date.year())
print "full date: %s" % self.fullDate
And here the code with the calendar:
def TabCalendar(self):
self.cal... | [
"I guess that the slot called by the selectdate signal shouldn't have any argument. You can access the selectedDate by the corresponding calendar method.\nSee the c++ docs: http://doc.trolltech.com/4.3/widgets-calendarwidget.html\nSo your code should be something like:\ndef selectDate(self):\n date = self.calend... | [
2
] | [] | [] | [
"calendar",
"date",
"python",
"qt",
"typeerror"
] | stackoverflow_0002004916_calendar_date_python_qt_typeerror.txt |
Q:
String manipulation in Python
I am trying to write a command but I do not want one long line that looks untidy. I am looking to add the strings together to be executed as on command. I have some code below which is part of an email function:
msg = MIMEText("The nightly build status was a SUCCESS\n\nBuild File: htt... | String manipulation in Python | I am trying to write a command but I do not want one long line that looks untidy. I am looking to add the strings together to be executed as on command. I have some code below which is part of an email function:
msg = MIMEText("The nightly build status was a SUCCESS\n\nBuild File: http://www.python.org\n\n Build Result... | [
"Try:\nmsg = MIMEText(\"\"\"The nightly build status was a SUCCESS\n\nBuild File:\nhttp://www.python.org\n\nBuild Results File: \nhttp://10.51.54.57/sandboxes/\"\"\", project, \"\\n\")\n\nIf the additional space at the beginning of each line is a problem, remove them with a regexp (r'^\\s+')\n",
"How about\nmsg =... | [
5,
5,
3,
1,
0
] | [
"Hmm, what exactly is the module are you using? I am guessing, that it is deprecated, because the modern interface is email (if I've guessed your intentions correctly). More specifically, to create a MIMEText object you use this class. The signature is \nemail.mime.text.MIMEText(_text[, _subtype[, _charset]])\n\n"
... | [
-1
] | [
"python"
] | stackoverflow_0002005345_python.txt |
Q:
Slow pyinotify.ThreadedNotifier.stop()
I have a wxPython application that uses pyinotify (via ThreadedNotifier) to check when a certain file gets modified. When this happens, the application stops watching the file and does some stuff. Everything works fine, except that often the call to ThreadedNotifier.stop() ta... | Slow pyinotify.ThreadedNotifier.stop() | I have a wxPython application that uses pyinotify (via ThreadedNotifier) to check when a certain file gets modified. When this happens, the application stops watching the file and does some stuff. Everything works fine, except that often the call to ThreadedNotifier.stop() takes a noticeable time, about 4 seconds... Ot... | [
"Could it be that it is a polling mechanism with a timeout of about 4 seconds? And that the thread is only really stopped when it is entering the run() stage?\nThat might have something to do with the threading library. \nYou could test that by using a notifier with a different timeout.\n"
] | [
1
] | [] | [] | [
"inotify",
"pyinotify",
"python"
] | stackoverflow_0002005443_inotify_pyinotify_python.txt |
Q:
Reading Alpha of a PNG Pixel. Fast way via pure Python?
I am having an issue with an embedded 64bit Python instance not liking PIL. Before i start exhausting more methods to get a compiled image editor to read the pixels for me (such as ImageMagick) i am hoping perhaps anyone here can think of a purely Python solu... | Reading Alpha of a PNG Pixel. Fast way via pure Python? | I am having an issue with an embedded 64bit Python instance not liking PIL. Before i start exhausting more methods to get a compiled image editor to read the pixels for me (such as ImageMagick) i am hoping perhaps anyone here can think of a purely Python solution that will be comparable in speeds to the compiled counte... | [
"Getting data out of a PNG requires unpacking data and decompressing it. These are likely going to be too slow in Python for your application. One possibility is to start with PyPNG and get rid of anything in it that you don't need. For example, it is probably storing all of the data it reads from the PNG, and s... | [
2,
0
] | [] | [] | [
"png",
"python"
] | stackoverflow_0001732761_png_python.txt |
Q:
Get original filename google app engine
When receiving a file upload on google app engine, the example assumes you're receiving a .png. However you only konw what the type of the image is by the extension on the filename.
How do you get the original filename uploaded on GAE?
A:
The filename of the file that is ... | Get original filename google app engine | When receiving a file upload on google app engine, the example assumes you're receiving a .png. However you only konw what the type of the image is by the extension on the filename.
How do you get the original filename uploaded on GAE?
| [
"The filename of the file that is being uploaded can be determined by looking at the filename property of the variable that holds the file. For example, let's say that your form has a field named content:\n<input type=\"file\" name=\"content\" />\n\nInside your Handler, you could find the name of the file with:\nfi... | [
8,
3
] | [] | [] | [
"google_app_engine",
"python",
"upload"
] | stackoverflow_0002004476_google_app_engine_python_upload.txt |
Q:
Visual module in python assign objects
I am a newb in Visual module in python, not really understand how does it assign a value to an objects.
say
from visual import *
stars=[]
galaxies=[]
for i in range(10):
stars+=[sphere('pos,radius,color.....')]
for j in range(20):
galaxies+=[sphere('pos,radius,color... | Visual module in python assign objects | I am a newb in Visual module in python, not really understand how does it assign a value to an objects.
say
from visual import *
stars=[]
galaxies=[]
for i in range(10):
stars+=[sphere('pos,radius,color.....')]
for j in range(20):
galaxies+=[sphere('pos,radius,color......')]
for k in range(30):
stars[k].po... | [
"First things first. Your code uses list concatenation to add stuff to the list. It is better to use the .append() method of lists. Also, the last loop could iterate directly on the objects instead of using an index. It is more elegant and easy to understand this way.\nThe pseudo-code below is equivalent to yours, ... | [
1
] | [] | [] | [
"python",
"python_visual"
] | stackoverflow_0002005759_python_python_visual.txt |
Q:
Python Debugging
I'm not sure if 'debugging' is the right word, but I'm looking for a tool/IDE that would show my which statement/block will be executed next in a particular module. This feature I remember was available in Turbo C++ years back so I assume something similar might be available in some Python IDE?
Th... | Python Debugging | I'm not sure if 'debugging' is the right word, but I'm looking for a tool/IDE that would show my which statement/block will be executed next in a particular module. This feature I remember was available in Turbo C++ years back so I assume something similar might be available in some Python IDE?
Thanks
| [
"pdb has this feature - there's a nice hands-on tutorial about it here.\npydev, the eclipse python plugin, might help if you're looking for an IDE solution.\n",
"Ulipad IDE's debugging feature is very good, its just works like Turbo C++ IDE's debugger.\n",
"At the commandline, there's pdb\nIn an IDE, Netbeans h... | [
2,
1,
0,
0
] | [] | [] | [
"breakpoints",
"debugging",
"ide",
"python"
] | stackoverflow_0002006034_breakpoints_debugging_ide_python.txt |
Q:
Executing python script in background in init.d
to interact with my iPhone, i have created a python script that sends and recives data through a socket, the script must be started after emule in order to work,
i have thought of something like this:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
... | Executing python script in background in init.d | to interact with my iPhone, i have created a python script that sends and recives data through a socket, the script must be started after emule in order to work,
i have thought of something like this:
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/local/bin/amuled
WEB=/usr/local/bin/amule... | [
"Put the su process in the background, not its child. For example:\nsu $USER -c \"$WEB --quiet\" &\n\nNotice that the ampersand is outside the quotes.\n",
"try launching with nohup process.py &\n"
] | [
5,
2
] | [] | [] | [
"bash",
"init.d",
"python",
"sysv"
] | stackoverflow_0002006483_bash_init.d_python_sysv.txt |
Q:
web2py Exception in sql rows
when i do the following code:
family_members =db(db.member.id == membership_id).select
(db.member.name,db.member.id)
family_members.colnames = ('Name','Membership ID')
It cause the following error...
Traceback (most recent call last):
File "/home/abeer/Desktop/web2py/New_version/web... | web2py Exception in sql rows | when i do the following code:
family_members =db(db.member.id == membership_id).select
(db.member.name,db.member.id)
family_members.colnames = ('Name','Membership ID')
It cause the following error...
Traceback (most recent call last):
File "/home/abeer/Desktop/web2py/New_version/web2py_src/web2py/gluon/
restricted.p... | [
"Do not use colnames. That attribute is internal to web2py. Use db.table.field.label='..' or SQLTABLE(rows, headers={...}) depending on what you need.\n"
] | [
0
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0002006259_python_web2py.txt |
Q:
Click overlay for html page with click stats
How would you setup click overlay for html page that has click stats with number of clicks stored. Is there a jquery example for something like this. The ideal click overlay will have have a little box on top on each link with how many times it was clicked.
A:
Not sur... | Click overlay for html page with click stats | How would you setup click overlay for html page that has click stats with number of clicks stored. Is there a jquery example for something like this. The ideal click overlay will have have a little box on top on each link with how many times it was clicked.
| [
"Not sure if you want to use a 3rd party service, but Crazy Egg does this exact thing: http://crazyegg.com/\nOr a tutorial here: http://css-tricks.com/tracking-clicks-building-a-clickmap-with-php-and-jquery/\n",
"I think this tutorial is perfect for you: http://celeryproject.org/tutorials/clickcounter.html\nYou c... | [
1,
0
] | [] | [] | [
"django",
"jquery",
"python"
] | stackoverflow_0002006320_django_jquery_python.txt |
Q:
google app engine jsonpickle
Has anyone got jsonpickle working on the google app engine? My logs say there is no module but there is a module as sure as you're born. i'm using jsonpickle 0.32.
<type 'exceptions.ImportError'>: No module named jsonpickle
Traceback (most recent call last):
File "/base/data/home/app... | google app engine jsonpickle | Has anyone got jsonpickle working on the google app engine? My logs say there is no module but there is a module as sure as you're born. i'm using jsonpickle 0.32.
<type 'exceptions.ImportError'>: No module named jsonpickle
Traceback (most recent call last):
File "/base/data/home/apps/xxxxx/xxxxxxxxxxxxxxxxx/main.py"... | [
"I have managed to make it work registering django.utils.simplejson as a json encoder/decoder. In this real file index.py class Pizza is encoded and decoded back:\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nimport jsonpickle\n\nclass Pizza:\n pass ... | [
4,
3
] | [] | [] | [
"google_app_engine",
"json",
"jsonpickle",
"python"
] | stackoverflow_0002003817_google_app_engine_json_jsonpickle_python.txt |
Q:
Multithreading python application hangs while running its threads
I am trying to create a MainObject which is availible as a DBus service. This MainObject should always stay responsive to other objects/processes and for this non-blocking even while processing its items. for that reason items are processed in a sep... | Multithreading python application hangs while running its threads | I am trying to create a MainObject which is availible as a DBus service. This MainObject should always stay responsive to other objects/processes and for this non-blocking even while processing its items. for that reason items are processed in a seperate thread one after another (queue-style). You can add items to the ... | [
"The gobject bindings by default aren't multithread-aware. Please try to do the following just after you have imported gobject:\ngobject.threads_init()\n\n",
"Threads in python can be a trap -- it is an open problem, actually.\nThe main problem is the GIL - Python's Global Interpreter Lock.\nOne of the ways they ... | [
2,
0
] | [] | [] | [
"blocking",
"loops",
"multithreading",
"python",
"sleep"
] | stackoverflow_0002006132_blocking_loops_multithreading_python_sleep.txt |
Q:
Python Encoding Issue
I am really lost in all the encoding/decoding issues with Python. Having read quite few docs about how to handle incoming perfectly, i still have issues with few languages, like Korean. Anyhow, here is the what i am doing.
korean_text = korean_text.encode('utf-8', 'ignore')
korean_text = unic... | Python Encoding Issue | I am really lost in all the encoding/decoding issues with Python. Having read quite few docs about how to handle incoming perfectly, i still have issues with few languages, like Korean. Anyhow, here is the what i am doing.
korean_text = korean_text.encode('utf-8', 'ignore')
korean_text = unicode(korean_text, 'utf-8')
... | [
"Even having read some docs, you seem to be confused on how unicode works.\n\nUnicode is not an encoding. Unicode is the absence of encodings.\nutf-8 is not unicode. utf-8 is an encoding. \nYou decode utf-8 bytestrings to get unicode. You encode unicode using an encoding, say, utf-8, to get an encoded bytestring.\n... | [
11,
0,
0
] | [] | [] | [
"encoding",
"python",
"utf_8"
] | stackoverflow_0002006115_encoding_python_utf_8.txt |
Q:
How to Use Mathematic Equations as Filters in SQLAlchemy
I'm using the SQLAlchemy ORM to construct the MySQL queries in my application, and am perfectly able to add basic filters to the query, like so:
query = meta.Session.query(User).filter(User.user_id==1)
Which gives me something basically equivalent to this:
... | How to Use Mathematic Equations as Filters in SQLAlchemy | I'm using the SQLAlchemy ORM to construct the MySQL queries in my application, and am perfectly able to add basic filters to the query, like so:
query = meta.Session.query(User).filter(User.user_id==1)
Which gives me something basically equivalent to this:
SELECT * FROM users WHERE user_id = 1
My question is how I wo... | [
"You can use literal SQL in your filter, see here: http://www.sqlalchemy.org/docs/05/ormtutorial.html?highlight=text#using-literal-sql\nFor example:\nclause = \"SQRT(POW(69.1 * (latitude - :lat),2) + POW(53.0 * (longitude - :long),2)) < 5\"\nquery = meta.Session.query(User).filter(clause).params(lat=my_latitude, lo... | [
5,
4
] | [] | [] | [
"mysql",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0002002024_mysql_orm_python_sqlalchemy.txt |
Q:
making undo in python
first of all .. sorry if my english was bad. its my 3rd language
im working on a paint software that draw over images and save them again ( for commenting propose ) i use pile and wxpython.
but im still having problems with some features ..
what is the ideal way to make the undo option ? ... | making undo in python | first of all .. sorry if my english was bad. its my 3rd language
im working on a paint software that draw over images and save them again ( for commenting propose ) i use pile and wxpython.
but im still having problems with some features ..
what is the ideal way to make the undo option ?
another question .. when t... | [
"The canonical strategy is to use the Command pattern. You'll represent the things you can do as Command objects, and each object is placed on a stack. The state of the application is then defined by an initial state plus everything that the stack has. Thus, the \"undo\" operation is then just popping the top stack... | [
13,
9
] | [] | [] | [
"image",
"python",
"python_imaging_library",
"undo",
"wxpython"
] | stackoverflow_0002006404_image_python_python_imaging_library_undo_wxpython.txt |
Q:
Why is Django's Meta an old-style class?
I noticed that in Django models, there is a class Meta which makes some additional definitions about the model.
My question is, why is this done as an old-style class? (i.e. not subclassing object?) Is there a reason for this or is this just a custom? Could I do it as a new... | Why is Django's Meta an old-style class? | I noticed that in Django models, there is a class Meta which makes some additional definitions about the model.
My question is, why is this done as an old-style class? (i.e. not subclassing object?) Is there a reason for this or is this just a custom? Could I do it as a new-style class in my projects?
| [
"I believe that there is no real reason (including history, since new-style classes exist since Python 2.2) and that not only can you choose to use a new-style class instead, but that it would probably be a good idea for you to do so (for all the usual reasons).\n",
"Since class Meta is never anything but a simpl... | [
16,
9
] | [] | [] | [
"class",
"django",
"python"
] | stackoverflow_0002005150_class_django_python.txt |
Q:
Why are django projects python packages?
Why aren't they simply directories? Any good advice says to keep as much as possible in the apps and not to couple them to the project. The very ability to import an app as project.application discourages this. Why does django-admin.py create the __init__.py at all? The pro... | Why are django projects python packages? | Why aren't they simply directories? Any good advice says to keep as much as possible in the apps and not to couple them to the project. The very ability to import an app as project.application discourages this. Why does django-admin.py create the __init__.py at all? The project is perfectly useful without it. What is t... | [
"We have a single project that we \"subclass\" of sorts for other projects. So we have other projects that import stuff from the main project. I guess for us it provides the common namespace that contains all the other apps.\nWe could move to a package with all our apps in it separate from the projects i guess. Our... | [
2,
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002003527_django_python.txt |
Q:
How to use C# client to consume Django/Python web service (all methods are returning null)?
I have a C# command-line client that I'm testing the consumption of SOAP/WSDL via Django/Python/soaplib created WSDL. I've managed to successfully connect to the web service by adding a service reference. I then call one of... | How to use C# client to consume Django/Python web service (all methods are returning null)? | I have a C# command-line client that I'm testing the consumption of SOAP/WSDL via Django/Python/soaplib created WSDL. I've managed to successfully connect to the web service by adding a service reference. I then call one of service's methods, and the service processes the data I send, but it returns null instead of the... | [
"One thing you can do is start by building a manual proxy using WebClient, or WebRequest/WebResponse. Construct your manual proxy to send the desired data to the WS for testing.\nCouple of things to check on the WSDL implementation:\n\nThe WSDL definition needs to match exactly, including case, for the C# proxy to ... | [
0,
0
] | [] | [] | [
"c#",
"django",
"python",
"soap",
"wsdl"
] | stackoverflow_0002007908_c#_django_python_soap_wsdl.txt |
Q:
How to share data between python processes without writing to disk
Helllo,
I would like to share small amounts of data (< 1K) between python and processes. The data is physical pc/104 IO data which changes rapidly and often (24x7x365). There will be a single "server" writing the data and multiple clients reading p... | How to share data between python processes without writing to disk | Helllo,
I would like to share small amounts of data (< 1K) between python and processes. The data is physical pc/104 IO data which changes rapidly and often (24x7x365). There will be a single "server" writing the data and multiple clients reading portions of it.
The system this will run on uses flash memory (CF card) r... | [
"An alternative to writing the data to file in the server process might be to directly write to the client processes:\nUse UNIX domain sockets (or TCP/IP sockets if the clients run on different machines) to connect each client to the server, and have the server write into those sockets. Depending on your particular... | [
8,
4,
2,
0
] | [] | [] | [
"ipc",
"json_rpc",
"mmap",
"pc104",
"python"
] | stackoverflow_0002006624_ipc_json_rpc_mmap_pc104_python.txt |
Q:
Lua vs PHP/Python/JSP/etc
I'm about to begin my next web development project and wanted to hear about the merits of Lua within the web-development space.
How does Lua compare to PHP/Python/JSP/etc.. for web development?
Any reason why Lua would be a poor choice for a web application language vs the others?
A:
In... | Lua vs PHP/Python/JSP/etc | I'm about to begin my next web development project and wanted to hear about the merits of Lua within the web-development space.
How does Lua compare to PHP/Python/JSP/etc.. for web development?
Any reason why Lua would be a poor choice for a web application language vs the others?
| [
"In brief:\n\nLua gives you a smaller, simpler system that you can understand in its entirety, but it is in a much smaller ecosystem; Kepler is all you get, and you will probably have to build some of your own stuff. I find this easy and fun (I make heavy use of the Lua bindings to the Expat parser and the Lua Obj... | [
21,
7,
4,
2,
1,
1
] | [] | [] | [
"lua",
"php",
"python",
"web_applications"
] | stackoverflow_0001303270_lua_php_python_web_applications.txt |
Q:
Can you recommend an Amazon AMI for Python?
I want to remove as much complexity as I can from administering Python in on Amazon EC2 following some truly awful experiences with hosting providers who claim support for Python. I am looking for some guidance on which AMI to choose so that I have a stable and easily m... | Can you recommend an Amazon AMI for Python? | I want to remove as much complexity as I can from administering Python in on Amazon EC2 following some truly awful experiences with hosting providers who claim support for Python. I am looking for some guidance on which AMI to choose so that I have a stable and easily managed environment which already included Python ... | [
"Try the Ubuntu EC2 images. Python 2.7 is installed by default. The rest you just apt-get install and optionally create an image when the baseline is the way you want it (or just maintain a script that installs all the pieces and run after you create the base Ubuntu instance).\n",
"If you can get by with using th... | [
4,
2
] | [] | [] | [
"amazon_ec2",
"python"
] | stackoverflow_0002008055_amazon_ec2_python.txt |
Q:
python struct pack double
I want to convert -123.456 into a C double for network transmission in python. So I tried this:
struct.pack('d', -123.456)
I get this as a result:
'w\xbe\x9f\x1a/\xdd^\xc0'
Obviously there is some hex in there, but what is with the w, /, and ^ sprinkled in there?
A:
They are, respecti... | python struct pack double | I want to convert -123.456 into a C double for network transmission in python. So I tried this:
struct.pack('d', -123.456)
I get this as a result:
'w\xbe\x9f\x1a/\xdd^\xc0'
Obviously there is some hex in there, but what is with the w, /, and ^ sprinkled in there?
| [
"They are, respectively, a \"w\", \"/\", and \"^\". Some byte sequences do correspond to ASCII characters.\n"
] | [
1
] | [] | [] | [
"networking",
"python",
"struct.pack"
] | stackoverflow_0002008871_networking_python_struct.pack.txt |
Q:
Any ideas on optimizing this script? (Python)
I'm working on a little script to help me learn the Japanese Kana (Hiragana/Katakana). In total, there are probably 100+ (+||-).
Basically, all it would do is take in the english version and convert it to the character.
ie. a = 'あ' which is 12354 in decimal
What I ha... | Any ideas on optimizing this script? (Python) | I'm working on a little script to help me learn the Japanese Kana (Hiragana/Katakana). In total, there are probably 100+ (+||-).
Basically, all it would do is take in the english version and convert it to the character.
ie. a = 'あ' which is 12354 in decimal
What I have so far is this:
hiraDict = { "a" : 12354, "i" : ... | [
"No need to check for presence, just get it and provide a default argument if you don't want an exception:\n# -*- coding: utf-8 -*-\nimport sys\nhiraDict = {'a': 'あ', 'i': 'い', }\nprint(hiraDict.get(sys.argv[1], None))\n\n... and for python 2.x:\n# -*- coding: utf-8 -*-\nimport sys\nhiraDict = {'a': u'あ', 'i': u'い'... | [
5,
3,
1,
1
] | [] | [] | [
"python",
"unicode"
] | stackoverflow_0002008891_python_unicode.txt |
Q:
Learn Go Or Improve My Python/Ruby Knowledge
I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: Learn Go or improve my Python or Ruby knowledge?
Years developing with Python: 1
Years developing with Ruby: 0.3
... | Learn Go Or Improve My Python/Ruby Knowledge | I was reading about Go, and I can see that it's very good and can be a language used by many developers in some months, but I want to decide a simple thing: Learn Go or improve my Python or Ruby knowledge?
Years developing with Python: 1
Years developing with Ruby: 0.3
| [
"If you're just looking to have fun and expand your horizons, then I'd learn Go, since you already know some Python.\nIf you're looking to improve as a developer, I'd personally recommend working on an actual project (using Python, as it's the language you have the most experience with):\n\nThis will take your (Pyt... | [
19,
9,
8,
3,
2,
2,
1,
1,
1,
1
] | [] | [] | [
"go",
"python",
"ruby"
] | stackoverflow_0002009194_go_python_ruby.txt |
Q:
How to debug dynamically defined functions in Python?
Is there a way to debug a function that is defined dynamically in run time?
Or at least is there an easy way to find out where this function is produced?
Update to give more detail:
I used inspect module:
ipdb> inspect.getmodule(im.get_thumbnail_url)
Out[0]: <... | How to debug dynamically defined functions in Python? | Is there a way to debug a function that is defined dynamically in run time?
Or at least is there an easy way to find out where this function is produced?
Update to give more detail:
I used inspect module:
ipdb> inspect.getmodule(im.get_thumbnail_url)
Out[0]: <module 'django.utils.functional' from 'C:\java\python\Pytho... | [
"Not sure, but you can get a function to print out the source file and line number it was defined in using the inspect module:\nimport inspect\nf = lambda: inspect.currentframe().f_code.co_filename + ':' + \\\n str(inspect.currentframe().f_lineno);\nprint f()\n\nIt prints:\nscript.py:2\n\n",
"Given a function f,... | [
1,
1
] | [] | [] | [
"debugging",
"dynamic",
"python"
] | stackoverflow_0002008496_debugging_dynamic_python.txt |
Q:
Display objects within a function, how to NOT terminate the program after close the display?
see the example:
from visual import *
def hello():
newyear=2010
sphere()
return newyear
my problem here is when I call function hello(), a sphere display window shows up, and also prints 2010, however if I clo... | Display objects within a function, how to NOT terminate the program after close the display? | see the example:
from visual import *
def hello():
newyear=2010
sphere()
return newyear
my problem here is when I call function hello(), a sphere display window shows up, and also prints 2010, however if I close the display window, the program terminates. That is not what I want, how can I avoid this?
also... | [
"You need to fork the process before hand.\n(Totally untested)\nimport os\nif os.fork() == 0: exit()\n\nPlacing that stanza at the start of your program should cause execution to continue in a forked process, detached from your tty. Someone can probably correct me though.\n"
] | [
0
] | [] | [] | [
"python",
"python_visual"
] | stackoverflow_0002008641_python_python_visual.txt |
Q:
Accessing py2exe program over network in Windows 98 throws ImportErrors
I'm running a py2exe-compiled python program from one server machine on a number of client machines (mapped to a network drive on every machine, say W:).
For Windows XP and later machines, have so far had zero problems with Python picking up ... | Accessing py2exe program over network in Windows 98 throws ImportErrors | I'm running a py2exe-compiled python program from one server machine on a number of client machines (mapped to a network drive on every machine, say W:).
For Windows XP and later machines, have so far had zero problems with Python picking up W:\python23.dll (yes, I'm using Python 2.3.5 for W98 compatibility and all th... | [
"This isn't a direct answer, but possibly some help. Are you familiar with the -v option in Python. Type python -h to learn more. Note the equivalent to the PYTHONVERBOSE environment variable for py2exe'd scripts is PY2EXE_VERBOSE, as described almost nowhere except in this post by its author. Apparently it can... | [
2
] | [] | [] | [
"importerror",
"py2exe",
"python",
"python_module",
"windows_98"
] | stackoverflow_0002009873_importerror_py2exe_python_python_module_windows_98.txt |
Q:
Python decorator with instantiation-time variable?
I want to make a decorator that creates a new function/method that makes use of an object obj. If the decorated object is a function, obj must be instantiated when the function is created. If the decorated object is a method, a new obj must be instantiated and bou... | Python decorator with instantiation-time variable? | I want to make a decorator that creates a new function/method that makes use of an object obj. If the decorated object is a function, obj must be instantiated when the function is created. If the decorated object is a method, a new obj must be instantiated and bound to each instance of the class whose method is decorat... | [
"Since a decorator is just syntactic sugar for saying\ndef func():\n ...\nfunc = decorator(func)\n\nWhy not do that in the object constructor?\nclass A(object):\n def __init__(self):\n # apply decorator at instance creation\n self.f = dec(self.f)\n\n def f(self, x):\n \"\"\"something\"\... | [
2,
1,
0,
0
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0002007786_decorator_python.txt |
Q:
How to get the difference between two list based on substrings withing each string in the seperate lists
I have two long list, one from a log file that contains lines formatted like
201001050843 blah blah blah <email@site.com> blah blah
and a second file in csv format. I need to generate a list of all the entries... | How to get the difference between two list based on substrings withing each string in the seperate lists | I have two long list, one from a log file that contains lines formatted like
201001050843 blah blah blah <email@site.com> blah blah
and a second file in csv format. I need to generate a list of all the entries in file2 that do not contain a email address in the log file, while maintaining the csv format.
Example
Log f... | [
"line.split() splits at whitespace. Use line.split(',') instead.\nAlso: Does the order of the lines matter? If not, then you should really use a set() instead of a list. That will make the code much faster.\n",
"You could create the set of emails as you do and then:\n# emails is a set of emails\nfor line in filei... | [
1,
1,
0
] | [] | [] | [
"list",
"list_manipulation",
"python",
"string"
] | stackoverflow_0002007755_list_list_manipulation_python_string.txt |
Q:
How to load modules dynamically on package import?
Given the following example layout:
test/
test.py
formats/
__init__.py
format_a.py
format_b.py
What I try to archive is, that whenever I import formats, the __init__.py looks for all available modules in the formats subdir, loads them and makes th... | How to load modules dynamically on package import? | Given the following example layout:
test/
test.py
formats/
__init__.py
format_a.py
format_b.py
What I try to archive is, that whenever I import formats, the __init__.py looks for all available modules in the formats subdir, loads them and makes them available (right now simply through a variable, suppo... | [
"There are two fixes you need to make to your code:\n\nYou should call __import__(m, globals(), locals()) instead of __import__(m). This is needed for Python to locate the modules within the package.\nYour code doesn't remove the .py extension properly since you call index() on the wrong string. If it will always b... | [
1,
1,
0,
0,
0
] | [] | [] | [
"dynamic",
"import",
"packaging",
"python"
] | stackoverflow_0002001940_dynamic_import_packaging_python.txt |
Q:
Cannot decode/encode in UTF-8
I have a text-box which allows users to enter a word.
The user enters: über
In the backend, I get the word like this:
def form_process(request):
word = request.GET.get('the_word')
word = word.encode('utf-8')
#word = word.decode('utf-8')
print word
For some reason, I ... | Cannot decode/encode in UTF-8 | I have a text-box which allows users to enter a word.
The user enters: über
In the backend, I get the word like this:
def form_process(request):
word = request.GET.get('the_word')
word = word.encode('utf-8')
#word = word.decode('utf-8')
print word
For some reason, I cannot decode or encode this!!
It g... | [
"Did you remember to put:\naccept-charset=\"utf-8\"\n\nin the form tag?\nEDIT: Is the DEFAULT_CHARSET in settings.py set to 'utf-8' ?\n",
"Solved!\nI had escape(word) ...in the javascript ...before I passed it to the server.\n",
"Is there any reason to use print word? If not, its should work without those lines... | [
1,
1,
0
] | [] | [] | [
"decoding",
"django",
"encoding",
"python",
"utf_8"
] | stackoverflow_0002010323_decoding_django_encoding_python_utf_8.txt |
Q:
the official name of this programming approach to compute the union and the intersection
I [surely re] invented this [wheel] when I wanted to compute the union and the intersection and diff of two sets (stored as lists) at the same time. Initial code (not the tightest):
dct = {}
for a in lst1:
dct[a] = 1
for b i... | the official name of this programming approach to compute the union and the intersection | I [surely re] invented this [wheel] when I wanted to compute the union and the intersection and diff of two sets (stored as lists) at the same time. Initial code (not the tightest):
dct = {}
for a in lst1:
dct[a] = 1
for b in lst2:
if b in dct:
dct[b] -= 1
else:
dct[b] = -1
union = [k for k in dct]
inter... | [
"Using an N bit integer to represent N booleans is a special case of the data structure known as a perfect hash table. Notice you're explicitly using dicts (which are general hash tables) in the idea that prompted you to think about bitsets. It's a hash table because you use hashes to find a value, and it's perfe... | [
7,
4,
2,
1
] | [] | [] | [
"algorithm",
"bit_fields",
"language_agnostic",
"python",
"set"
] | stackoverflow_0002010132_algorithm_bit_fields_language_agnostic_python_set.txt |
Q:
Python: why aren't variables updating?
A python program that I'm debugging has the following code (including print statements for debugging):
print "BEFORE..."
print "oup[\"0\"] = " + str(oup["0"])
print "oup[\"2008\"] = " + str(oup["2008"])
print "oup[\"2009\"] = " + str(oup["2009"])
oup0 = oup["0"]
oup2008 = ou... | Python: why aren't variables updating? | A python program that I'm debugging has the following code (including print statements for debugging):
print "BEFORE..."
print "oup[\"0\"] = " + str(oup["0"])
print "oup[\"2008\"] = " + str(oup["2008"])
print "oup[\"2009\"] = " + str(oup["2009"])
oup0 = oup["0"]
oup2008 = oup["2008"]
oup2009 = oup["2009"]
ouptotal = o... | [
"If the values are integers, then (oup2008 / ouptotal) will be zero, so they will be updated to their own value + 0, hence no change.\nConvert them to floats for the calculation, then back if required, and it should work as expected.\nExample:\noup[\"2008\"] = oup2008 + int(oup0 * (float(oup2008) / ouptotal))\n\n",... | [
6,
3,
1
] | [] | [] | [
"integer",
"python",
"variables"
] | stackoverflow_0002010566_integer_python_variables.txt |
Q:
draw text with GLUT / OpenGL in Python
I m drawing text with OpenGL in Python. It all works ok, however the font is really bad.
If I make it thick the letters start to look very occurred (especially the ones which are round like 'o' or 'g'. For the purpose of my program it must be thick. Is there any font I could... | draw text with GLUT / OpenGL in Python | I m drawing text with OpenGL in Python. It all works ok, however the font is really bad.
If I make it thick the letters start to look very occurred (especially the ones which are round like 'o' or 'g'. For the purpose of my program it must be thick. Is there any font I could use which does not look so bad when thicken... | [
"Try a more sophisticated text rendering solution. Perhaps something like pyftgl would get you better results, by rendering full-quality TrueType fonts.\n",
"http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=43\nAt the bottom is the python version of this lesson which shows you how to load freetype fonts wit... | [
1,
0
] | [] | [] | [
"draw",
"opengl",
"python",
"text"
] | stackoverflow_0000730952_draw_opengl_python_text.txt |
Q:
python crypto high level wrapper
I'm using PyCrypto (on google app engine) for AES encryption.
PyCrypto gives I guess a raw interface to AES--i need to pad my keys and my inputs to 16 byte multiples.
Is there a higher level library which takes care of this stuff for me?
A:
An easy, friendly wrapper on top of PyC... | python crypto high level wrapper | I'm using PyCrypto (on google app engine) for AES encryption.
PyCrypto gives I guess a raw interface to AES--i need to pad my keys and my inputs to 16 byte multiples.
Is there a higher level library which takes care of this stuff for me?
| [
"An easy, friendly wrapper on top of PyCrypto is ezPyCrypto.\n"
] | [
5
] | [] | [] | [
"aes",
"google_app_engine",
"pycrypto",
"python"
] | stackoverflow_0002010575_aes_google_app_engine_pycrypto_python.txt |
Q:
What's the suggested way of importing modules within a django project
This has always bothered me, and I've never really come up with my own preferred way of doing this.
When importing something from one of your own applications in a django project, do you import with:
from myproject.mymodule.model import SomeMode... | What's the suggested way of importing modules within a django project | This has always bothered me, and I've never really come up with my own preferred way of doing this.
When importing something from one of your own applications in a django project, do you import with:
from myproject.mymodule.model import SomeModel
from myproject.anotherone.model import AnotherModel
or, do you do:
from ... | [
"I would recommend using the second alternative:\nfrom mymodule.model import SomeModel\nfrom anotherone.model import AnotherModel\n\nIn Django, it's recommended to write reusable applications, that you may deploy in multiple projects. Specifying the name of the project would hinder this possibility. It would even... | [
5,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002010746_django_python.txt |
Q:
Cherrypy hanging on form post
I'm currently trying to remove a legacy python framework (webware 0.8.1) and layer cherrypy 3.1.2 on top of it. Instead of converting all the webware pages to cherrypy pages, I'm merely processing it through webware and passing it to cherrypy like so.
def default(self, url, *suburl, *... | Cherrypy hanging on form post | I'm currently trying to remove a legacy python framework (webware 0.8.1) and layer cherrypy 3.1.2 on top of it. Instead of converting all the webware pages to cherrypy pages, I'm merely processing it through webware and passing it to cherrypy like so.
def default(self, url, *suburl, **kwarg):
...snip...
strmout... | [
"I don't really have experience with Webware, but based on the appearance of your code, Webware is trying to use cgi.FieldStorage to retrieve your field variables, but FieldStorage can't get the length, or gets the length incorrectly (probably because whatever Webware does to get the Content-Length header doesn't w... | [
2
] | [] | [] | [
"cherrypy",
"python"
] | stackoverflow_0002010766_cherrypy_python.txt |
Q:
Python halts while iteratively processing my 1GB csv file
I have two files:
metadata.csv: contains an ID, followed by vendor name, a filename, etc
hashes.csv: contains an ID, followed by a hash
The ID is essentially a foreign key of sorts, relating file metadata to its hash.
I wrote this script to quickly extrac... | Python halts while iteratively processing my 1GB csv file | I have two files:
metadata.csv: contains an ID, followed by vendor name, a filename, etc
hashes.csv: contains an ID, followed by a hash
The ID is essentially a foreign key of sorts, relating file metadata to its hash.
I wrote this script to quickly extract out all hashes associated with a particular vendor. It craps ... | [
"\"Craps out\" is not a particularly good description. What does it do? Does it swap? Fill all memory? Or just eats CPU without appearing to do anything?\nHowever, just for a start, use a dictionnary rather than a list for stored_ids. Searching in a dictionnary is usually done in O(1) time while searching in a list... | [
3,
0,
0,
0
] | [] | [] | [
"csv",
"large_files",
"memory",
"python"
] | stackoverflow_0002010451_csv_large_files_memory_python.txt |
Q:
How to implement a voice chat functionality using Python?
My goal is a cross-platform voice chat application. The part I am a bit confused about it's the voice transferring one : )
What can you suggest? Maybe a binding to some low-level library or even a framework?
BTW, I don't have to use Python, so if you think ... | How to implement a voice chat functionality using Python? | My goal is a cross-platform voice chat application. The part I am a bit confused about it's the voice transferring one : )
What can you suggest? Maybe a binding to some low-level library or even a framework?
BTW, I don't have to use Python, so if you think that Python is not a good idea for this purpose, please show me... | [
"You should look into Telepathy:\nhttp://telepathy.freedesktop.org/wiki/\nThere are Python bindings available:\nhttp://telepathy.freedesktop.org/wiki/Telepathy%20Python\nSee also; the end of this presentation features an IM/Voip client in 20 lines:\nhttp://raphael.slinckx.net/files/telepathy-guadec-2007.pdf\n"
] | [
4
] | [] | [] | [
"chat",
"python",
"voice"
] | stackoverflow_0002011042_chat_python_voice.txt |
Q:
how to check the character count of a file in python
I have a python code which reads many files.
but some files are extremely large due to which i have errors coming in other codes.
i want a way in which i can check for the character count of the files so that i avoid reading those extremely large files.
Thanks.
... | how to check the character count of a file in python | I have a python code which reads many files.
but some files are extremely large due to which i have errors coming in other codes.
i want a way in which i can check for the character count of the files so that i avoid reading those extremely large files.
Thanks.
| [
"os.stat(filepath).st_size\n\nAssuming by ‘characters’ you mean bytes. ETA:\n\ni need total character count just like what the command 'wc filename' gives me unix\n\nIn which mode? wc on it own will give you a line, word and byte count (same as stat), not Unicode characters.\nThere is a switch -m which will use the... | [
7,
7,
5,
4,
2
] | [] | [] | [
"character",
"python",
"size"
] | stackoverflow_0002011048_character_python_size.txt |
Q:
Retrieve module object from stack frame
Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works:
import sys
from some_other_module import callers_module
assert sys.modules[__name__] is callers_module()
(That would be equivalent because I can gen... | Retrieve module object from stack frame | Given a frame object, I need to get the corresponding module object. In other words, implement callers_module so this works:
import sys
from some_other_module import callers_module
assert sys.modules[__name__] is callers_module()
(That would be equivalent because I can generate a stack trace in the function for this ... | [
"While inspect.getmodule works great, and I was indeed looking in the wrong place to find it, I found a slightly better solution for me:\ndef callers_module():\n module_name = inspect.currentframe().f_back.f_globals[\"__name__\"]\n return sys.modules[module_name]\n\nIt still uses inspect.currentframe (which I pre... | [
13,
7
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0002000861_introspection_python.txt |
Q:
Creating and deploying a python chat application using Twisted
I have created a chat server application using the Twisted framework. I am running it on my local machine and now I want to go global. The application is similar to omegle.com.
How can I develop on a third party commercial server so that it runs contin... | Creating and deploying a python chat application using Twisted | I have created a chat server application using the Twisted framework. I am running it on my local machine and now I want to go global. The application is similar to omegle.com.
How can I develop on a third party commercial server so that it runs continuously?
Do I need to get a dedicated server for it?
| [
"As per this SO answer,\n\nYou can deploy Twisted on any hosting\n provider who gives you a shell prompt\n and doesn't limit your long-running\n processes.\nSome examples that I've used include:\n Tummy ltd. and Slicehost.\n\nThe hosting server need not be dedicated, in other words, as long as those conditions ... | [
3,
0
] | [] | [] | [
"chat",
"hosting",
"python",
"twisted"
] | stackoverflow_0002011136_chat_hosting_python_twisted.txt |
Q:
X-Sendfile and VERY big files on Apache2
Any filesize over about 4GB is not going to work with the mod_xsendfile for Apache2 (as it sets the content length to a long).
I am willing to rewrite it to support this; however, I can find no documentation on how to set content length from the apache api to something larg... | X-Sendfile and VERY big files on Apache2 | Any filesize over about 4GB is not going to work with the mod_xsendfile for Apache2 (as it sets the content length to a long).
I am willing to rewrite it to support this; however, I can find no documentation on how to set content length from the apache api to something larger than a long and thus serve large files thro... | [
"Location of the Beta for mod_xsendfile on Apache2\n",
"I have discovered the answer. Use the BETA version provided. It seems to fix this issue.\n"
] | [
4,
1
] | [] | [] | [
"apache2",
"python",
"wsgi",
"x_sendfile"
] | stackoverflow_0001693564_apache2_python_wsgi_x_sendfile.txt |
Q:
How to use ipython's IPShellEmbed from within a running doctest
Please help me get an embedded ipython console to run inside a doctest. The example code demonstrates the problem and will hang your terminal. On bash shell I type ctrl-Z and then kill %1 to break out and kill, since ctrl-C won't work.
def some_func... | How to use ipython's IPShellEmbed from within a running doctest | Please help me get an embedded ipython console to run inside a doctest. The example code demonstrates the problem and will hang your terminal. On bash shell I type ctrl-Z and then kill %1 to break out and kill, since ctrl-C won't work.
def some_function():
"""
>>> some_function()
'someoutput'
"""
... | [
"I emailed the ipython user group and got some help. There is now a support ticket to get this feature fixed in future versions of ipython. Here is a code snippet with a workaround:\nimport sys\n\nfrom IPython.Shell import IPShellEmbed\n\nclass IPShellDoctest(IPShellEmbed):\n def __call__(self, *a, **kw):\n ... | [
0
] | [] | [] | [
"doctest",
"ipython",
"python",
"unit_testing"
] | stackoverflow_0001986805_doctest_ipython_python_unit_testing.txt |
Q:
Django dynamic number of filter for a objects request
How can I do something like this :
products_list = Product.objects.all()
for key in keywords:
products_list = products_list.filter(name__icontains=q)
This don't work.
A:
You are filtering the list with several AND statements, and you want OR statements.... | Django dynamic number of filter for a objects request | How can I do something like this :
products_list = Product.objects.all()
for key in keywords:
products_list = products_list.filter(name__icontains=q)
This don't work.
| [
"You are filtering the list with several AND statements, and you want OR statements. Try something like this:\nfrom django.db.models import Q\nproducts_list = Product.objects.all()\norq = None \nfor key in keywords:\n thisq = Q(name__icontains=q)\n if orq:\n orq = thisq | orq\n else:\n orq... | [
2
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0002011752_django_django_models_python.txt |
Q:
Display random choice (Python)
I have a list[] of items from which I'd like to display one randomly, but the displayed item must not repeat more than once in last x requests.
list1 = item1, item2, item3, item4,
item5, item6, item7, item8, item9,
item 10
Display a random selection
from the list above
list2 = st... | Display random choice (Python) | I have a list[] of items from which I'd like to display one randomly, but the displayed item must not repeat more than once in last x requests.
list1 = item1, item2, item3, item4,
item5, item6, item7, item8, item9,
item 10
Display a random selection
from the list above
list2 = store the last displayed item in list2... | [
"collections.deque is the only sequence type in python that naturally supports being bounded (and only in Python 2.6 and up.) If using python 2.6 or newer:\n# Setup\nfrom collections import deque\nfrom random import choice\nused = deque(maxlen=7)\n\n# Now your sampling bit\nitem = random.choice([x for x in list1 i... | [
7,
4,
2,
1,
1
] | [] | [] | [
"limit",
"list",
"python",
"random"
] | stackoverflow_0002011583_limit_list_python_random.txt |
Q:
pycurl module not available after installation on Snow Leopard
I'm running Python 2.6.4 on Mac Snow Leopard. I installed pycurl using:
sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1
The installation completes with no issues and says pycurl is installed in subsequent installation attemp... | pycurl module not available after installation on Snow Leopard | I'm running Python 2.6.4 on Mac Snow Leopard. I installed pycurl using:
sudo env ARCHFLAGS="-arch x86_64" easy_install setuptools pycurl==7.16.2.1
The installation completes with no issues and says pycurl is installed in subsequent installation attempts. However, when I try to "import pycurl" in a script, I get a mess... | [
"I would suspect you have 2 versions of python on your system. How about removing easy install and reinstalling it. \nRemove the current easy install script by typing which easy_install and then rm [easy install full path].\nTo install easy install\nwget http://peak.telecommunity.com/dist/ez_setup.py\npython ez_set... | [
2,
1,
0
] | [] | [] | [
"osx_snow_leopard",
"pycurl",
"python"
] | stackoverflow_0002011640_osx_snow_leopard_pycurl_python.txt |
Q:
Compiling Python 3.1.1 32-bit
We're using this configure script with an option we spotted in the configure help menu:
./configure --with-universal-archs=32-bit --prefix="$HOME/python"
make
make install
But when all the dust is settled and we check out what it gives us:
✔python-3.1.1⤿ file ~/python/bin/python3
pyt... | Compiling Python 3.1.1 32-bit | We're using this configure script with an option we spotted in the configure help menu:
./configure --with-universal-archs=32-bit --prefix="$HOME/python"
make
make install
But when all the dust is settled and we check out what it gives us:
✔python-3.1.1⤿ file ~/python/bin/python3
python/bin/python3: Mach-O 64-bit exec... | [
"There's no need to build your own. Use the Python 3.1.1 OS X installer from python.org. It's 32-bit only and will work just fine on OS X 10.4 through 10.6. If you need to install any packages with C extension modules on 10.6, you'll need to install the optional 10.4 SDK from the the Snow Leopard Xcode mpkg and ... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0002011295_python.txt |
Q:
how can i get the value '111'
def a():
w='www'
a.a='aaa'
print a.__dict__
a.__dict__={'1':'111','2':'222'}
print a.1#error
print a['1']#error
how can i get the value '111'
thanks
A:
You'll have to do
print a.__dict__['1']
or
print getattr(a, '1')
"1" is not a valid variable name in Python. If you did:
a.... | how can i get the value '111' | def a():
w='www'
a.a='aaa'
print a.__dict__
a.__dict__={'1':'111','2':'222'}
print a.1#error
print a['1']#error
how can i get the value '111'
thanks
| [
"You'll have to do \nprint a.__dict__['1']\n\nor\nprint getattr(a, '1')\n\n\"1\" is not a valid variable name in Python. If you did:\na.__dict__ = {'a1' : '111'}\nprint a.a1\n\nit would work.\n",
"Since you say are just a beginner, perhaps you're just looking for the even easier: \n a = {'1':'111','2':'222'}\n\ns... | [
10,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0002011568_python.txt |
Q:
How to write last 50 lines from one file to another Python
I am creating an email response to an overnight build, I want to get the last 50 lines from the results file and place it into a summary file. The code that I have done is below, can anyone help?
def email_success():
fp = open(results_file, 'r')
... | How to write last 50 lines from one file to another Python | I am creating an email response to an overnight build, I want to get the last 50 lines from the results file and place it into a summary file. The code that I have done is below, can anyone help?
def email_success():
fp = open(results_file, 'r')
sum_file = (fp.readlines()[-50:])
fp.close()
myfile = o... | [
"TypeError: coercing to Unicode: need string or buffer, tuple found\n\nError says its expect string or buffer but you are passing tuple, so just join it with \"\" to make it to string\nSo, Try\nsum_file = \"\".join(fp.readlines()[-50:])\n\nUPDATE: because OP updated the question\nif result_summary = (t, 'results_su... | [
5,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0002012118_python.txt |
Q:
Python + Facebook, getting info about a group easily
I have a need to display some basic info about a facebook group on a website i am building. All i am really looking to show is the total number of members, and maybe a list of the few most recent people who joined.
I would like to not have to login to FB to acc... | Python + Facebook, getting info about a group easily | I have a need to display some basic info about a facebook group on a website i am building. All i am really looking to show is the total number of members, and maybe a list of the few most recent people who joined.
I would like to not have to login to FB to accomplish this, is there an API for groups that allows anony... | [
"Use the Python Facebook module on Google Code.\n"
] | [
1
] | [] | [] | [
"django",
"facebook",
"python"
] | stackoverflow_0002008816_django_facebook_python.txt |
Q:
why my code error? I copied the 'memoize' function in django.utils.functional
my code:
a=[1,2,3,4]
b=a[:2]
c=[]
c[b]='sss'#error
memoize function:
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]#<------this
if mem_args in cache:
return cache[mem_a... | why my code error? I copied the 'memoize' function in django.utils.functional | my code:
a=[1,2,3,4]
b=a[:2]
c=[]
c[b]='sss'#error
memoize function:
def memoize(func, cache, num_args):
def wrapper(*args):
mem_args = args[:num_args]#<------this
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result#<-----and this
... | [
"In the memoize function, I'm assuming cache is a dict. Also, since a is a list, b will also be a list, and lists are not hashable. Use a tuple.\nTry\na = (1, 2, 3, 4) # Parens, not brackets\nb = a[:2]\nc = {} # Curly braces, not brackets\nc[b] = 'sss'\n\n",
"What has your question got to do with the memoize func... | [
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002011823_django_python.txt |
Q:
Parse a string with a date to a datetime object
How can I parse a string like "01-Jan-1995" to a Python datetime object?
A:
On the whole you'd parse date and time strings with the strptime functions in time or datetime modules. Your example could be parsed with:
import datetime
datetime.datetime.strptime("01-Jan... | Parse a string with a date to a datetime object | How can I parse a string like "01-Jan-1995" to a Python datetime object?
| [
"On the whole you'd parse date and time strings with the strptime functions in time or datetime modules. Your example could be parsed with:\nimport datetime\ndatetime.datetime.strptime(\"01-Jan-1995\", \"%d-%b-%Y\")\n\nNote that parsing month names is locale-dependent. This table shows the directives for parsing va... | [
24,
10,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0001713594_datetime_python.txt |
Q:
Standalone Python applications in Linux
How can I distribute a standalone Python application in Linux?
I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy,... | Standalone Python applications in Linux | How can I distribute a standalone Python application in Linux?
I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and... | [
"Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.\n",
"You can use cx_Freeze to do this. It's just like py2exe (bundles together the interpreter and and startup script and all required librarie... | [
23,
13,
10,
7,
7,
3
] | [
"I think you can fairly safely take for granted python support on most modern Linux distributions - for the ones without it as long as a sane error message is given, users should probably be able to work how to get it on their own (you can use a simple bash startup script for this):\n#!/bin/bash\nif [ -e /usr/bin/p... | [
-1,
-9
] | [
"linux",
"python"
] | stackoverflow_0000193077_linux_python.txt |
Q:
Changing schema using cx_Oracle
Well, I hope this is not a duplicate, the search did not yield anything useful.
I have been toying with cx_Oracle for the past few days, installing and using it. Everything went fine until I reached my current problem: I'd like to change my schema. If I were using sqlplus a simple '... | Changing schema using cx_Oracle | Well, I hope this is not a duplicate, the search did not yield anything useful.
I have been toying with cx_Oracle for the past few days, installing and using it. Everything went fine until I reached my current problem: I'd like to change my schema. If I were using sqlplus a simple 'alter session set current_schema=toto... | [
"Okay, I finally, after much trying and error, followed fn suggestion and investigated inside cx_Oracle to find what was wrong.\nIt turns out that a number of arguments and methods are only available through some flags:\n\nWITH_UNICODE activates encoding and nencoding attributes\nORACLE_10G activates action, module... | [
10,
2
] | [] | [] | [
"cx_oracle",
"oracle",
"python"
] | stackoverflow_0002012035_cx_oracle_oracle_python.txt |
Q:
Django, create_user giving error, manually creating user gives different error
Working with Django 1.1 on Python 2.6.4, trying to execute the following:
user = User.objects.create_user(username, email, password)
The three values are from form.cleaned_data, and have already been validated. i get this error:
'dict'... | Django, create_user giving error, manually creating user gives different error | Working with Django 1.1 on Python 2.6.4, trying to execute the following:
user = User.objects.create_user(username, email, password)
The three values are from form.cleaned_data, and have already been validated. i get this error:
'dict' object has no attribute 'strip'
Traceback:
File "/usr/lib/pymodules/python2.6/djang... | [
"Seems like email_address is not really a string ('dict' object has no attribute 'strip'), can you dump for us the values of username, email and password?\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0002013230_django_python.txt |
Q:
Is it possible to use KHTMLPart completely from console?
I'm using the KHTMLPart component from the PyKDE (in Python) library to download some webpages in the background and return sizes of certain elements in pixels. I don't really need any visual output from this script, indeed I will probably run it on a server... | Is it possible to use KHTMLPart completely from console? | I'm using the KHTMLPart component from the PyKDE (in Python) library to download some webpages in the background and return sizes of certain elements in pixels. I don't really need any visual output from this script, indeed I will probably run it on a server without X installed. The problem is that when I tell my appli... | [
"If all else fails, you could try using the X Virtual Framebuffer to provide a fake X display to your application, allowing it to run without displaying anywhere.\n",
"I doubt it. Most browsers separate the download, the creation of the DOM model and the rendering in different parts of the code. This allows them ... | [
1,
1
] | [] | [] | [
"kde_plasma",
"pykde",
"python"
] | stackoverflow_0002013795_kde_plasma_pykde_python.txt |
Q:
PNG optimisation tools
A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...
I want to implement a similar optimisation feature as part of my website's image upload process; does any... | PNG optimisation tools | A while back I used a PNG optimisation service called (I think) "smush it". You fed it a weblink and it returned a zip of all the PNG images with their filesizes nicely, well, smushed...
I want to implement a similar optimisation feature as part of my website's image upload process; does anyone know of a pre-existing l... | [
"Execute with PHP this command line tools\n pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB -brute -l 9 -max -reduce -m 0 -q IMAGE\n optipng -o7 -q pngout.png\n pngout pngout.png -q -y -k0 -s0\n advpng -z -4 pngout.png > /dev/null\n\n\npngcrush\nOptiPNG\npngout\nadvpng\n\n",
"As long as your PHP is compiled ... | [
14,
4,
3,
2
] | [] | [] | [
"optimization",
"php",
"png",
"python"
] | stackoverflow_0001993678_optimization_php_png_python.txt |
Q:
Python: How do you format a string % number with str.format()
How can I format a string like this
"%01.2f" % pr"%01.2f" % some_number
but using the str.format() style? I'm used to this:
'{0} {1}'.format(somevalue1, somevalue2)
Is there a way to use that function style vs the old % style, and still achieve this d... | Python: How do you format a string % number with str.format() | How can I format a string like this
"%01.2f" % pr"%01.2f" % some_number
but using the str.format() style? I'm used to this:
'{0} {1}'.format(somevalue1, somevalue2)
Is there a way to use that function style vs the old % style, and still achieve this decimal formatting?
| [
"It would be like {0:01.2f}, I believe. See http://docs.python.org/library/string.html#format-string-syntax.\nEdit: added in your zero-padding.\n"
] | [
4
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002014012_python_string.txt |
Q:
attribute assignment order in class definition
I want to define a class in this way:
class List(Base):
hp = Column(int,...)
name = Column(str,...)
This class represents a list, I can define/modify/code the Base and the Column class.
There's a way to know the order in which I defined the attributes hp/name... | attribute assignment order in class definition | I want to define a class in this way:
class List(Base):
hp = Column(int,...)
name = Column(str,...)
This class represents a list, I can define/modify/code the Base and the Column class.
There's a way to know the order in which I defined the attributes hp/names?
For example I want to define a method that can do... | [
"Internally, attribute definitions are stored in a dictionary, which does not retain the order of the elements. You could probably change the attribute handling in the Base class, or you store the creation order, like this:\nclass Column:\n creation_counter = 0\n\n def __init__(self):\n self.creati... | [
7,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002013067_python.txt |
Q:
Vim Python indentation not working?
I have Vim 7 (enhanced) on CentOS 5, and it comes with all the usual Vim plugins/scripts ready to go.
$ find /usr/share/vim/vim70/ -name \*python\*
/usr/share/vim/vim70/syntax/python.vim
/usr/share/vim/vim70/ftplugin/python.vim
/usr/share/vim/vim70/indent/python.vim
/usr/share/v... | Vim Python indentation not working? | I have Vim 7 (enhanced) on CentOS 5, and it comes with all the usual Vim plugins/scripts ready to go.
$ find /usr/share/vim/vim70/ -name \*python\*
/usr/share/vim/vim70/syntax/python.vim
/usr/share/vim/vim70/ftplugin/python.vim
/usr/share/vim/vim70/indent/python.vim
/usr/share/vim/vim70/autoload/pythoncomplete.vim
I w... | [
"My understanding is that the python.vim file is just a syntax-highlighting file possibly, because Python files can be indented multiple ways. PEP8 prescribes four spaces, but legacy files could be different including using tabs.\nSome of our legacy Python files actually use two spaces per indent. So I leave Python... | [
5,
2
] | [] | [] | [
"python",
"vim",
"vim_plugin"
] | stackoverflow_0002011589_python_vim_vim_plugin.txt |
Q:
zooming pictures with wx.image
im doing a software that paints over images and save them ( for commenting propose ) .
i used the code below to display image to be drown upon.
the problem is:
how can i zoom in and out ? .
or should i use another way to display that image ?
bitmap=wx.bitmap(path,wx.BITMAP_TYPE_AN... | zooming pictures with wx.image | im doing a software that paints over images and save them ( for commenting propose ) .
i used the code below to display image to be drown upon.
the problem is:
how can i zoom in and out ? .
or should i use another way to display that image ?
bitmap=wx.bitmap(path,wx.BITMAP_TYPE_ANY)
buffer =wx.EmptyBitmap(500,500,3... | [
"Try dc.SetUserScaling\n"
] | [
3
] | [] | [] | [
"image",
"python",
"wxpython",
"zooming"
] | stackoverflow_0002014209_image_python_wxpython_zooming.txt |
Q:
Is it possible to create an end-user facing site using Django admin alone?
I'm very new to Django, having never developed on it.
I'm trying to develop a site which has functionality exposed only to authenticated users (typical enterprise thing: for this discussion, let's say it's a private blogging platform).
Th... | Is it possible to create an end-user facing site using Django admin alone? | I'm very new to Django, having never developed on it.
I'm trying to develop a site which has functionality exposed only to authenticated users (typical enterprise thing: for this discussion, let's say it's a private blogging platform).
The functionality I'm looking for is:
Users can create a new blog.
each user can ... | [
"Revised. Up until you want per-object permission, the answer is yes.\nAs soon as you want permission on a Blog, where a blog is just a row, you're going to have to do some coding.\nYou can totally reuse the admin interface elements. You have all the source, which you can read. \nMuch of what you want is done wi... | [
2,
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0002013736_django_django_admin_python.txt |
Q:
How to move into multiple directories Python
I am creating several directories a day. After seven days I am going to drop a sandbox in these directories and delete them. I use a time stamp to name them. I have got some code below to show you what I have got.
today = datetime.date.today() # Today's date Binary
toda... | How to move into multiple directories Python | I am creating several directories a day. After seven days I am going to drop a sandbox in these directories and delete them. I use a time stamp to name them. I have got some code below to show you what I have got.
today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.today().isoformat() # Todays ... | [
"\nold_folders = minus_seven + '*'\n\nThis does not do what you think it does. This gives you the name of a folder that literally ends in a *. Later, os.path.exists() will return False.\nWhat you need to do is loop through the directories:\nfor d in os.listdir(os.getcwd()):\n if not os.path.isdir(d) or not d.s... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0002013204_python.txt |
Q:
PHP Bayesian Classifier
I'm looking for a Naive Bayesian Classifier for PHP, ideally something equivalent to the Reverend Bayes version written in Python. Does anyone know of such a library?
Basically I need to be able to train it with a set of labels and words i.e. GOOD = okay, happy, fun; BAD = wrong, rubbish, a... | PHP Bayesian Classifier | I'm looking for a Naive Bayesian Classifier for PHP, ideally something equivalent to the Reverend Bayes version written in Python. Does anyone know of such a library?
Basically I need to be able to train it with a set of labels and words i.e. GOOD = okay, happy, fun; BAD = wrong, rubbish, awful etc and then pass it a s... | [
"This looks like a nice set of tutorials on the subject. A similar question has been asked previously and the only real answer pointed to the same resource.\nBayesian filtering is a general approach. Even if examples you find are medical, the techniques are pretty much the same and can be applied anywhere.\n"
] | [
3
] | [] | [] | [
"php",
"python"
] | stackoverflow_0002014432_php_python.txt |
Q:
Polluting a class's environment
I have an object that holds lots of ids that are accessed statically. I want to split that up into another object which holds only those ids without the need of making modifications to the already existen code base. Take for example:
class _CarType(object):
DIESEL_CAR_ENGINE = 0... | Polluting a class's environment | I have an object that holds lots of ids that are accessed statically. I want to split that up into another object which holds only those ids without the need of making modifications to the already existen code base. Take for example:
class _CarType(object):
DIESEL_CAR_ENGINE = 0
GAS_CAR_ENGINE = 1 # lots of the... | [
"Although this is not exactly what subclassing is made for, it accomplishes what you describe:\nclass _CarType(object):\n DIESEL_CAR_ENGINE = 0\n GAS_CAR_ENGINE = 1 # lots of these ids\n\nclass Car(_CarType):\n types = _CarType\n\n",
"Something like:\nclass Car(object):\n for attr, value in _CarType._... | [
4,
3,
2,
2,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0002012698_oop_python.txt |
Q:
Forcing tuples within tuples?
I've got a python function that should loop through a tuple of coordinates and print their contents:
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
When y is run through the function, it outputs (5,5) and (4,4), the desired result. Ho... | Forcing tuples within tuples? | I've got a python function that should loop through a tuple of coordinates and print their contents:
def do(coordList):
for element in coordList:
print element
y=((5,5),(4,4))
x=((5,5))
When y is run through the function, it outputs (5,5) and (4,4), the desired result. However, running x through the functi... | [
"Use a trailing comma for singleton tuples.\nx = ((5, 5),)\n\n",
"x=((5,5),)\n\n(x) is an expression (x,) is a singleton tuple.\n",
"This is an old and infuriating quirk of python syntax. You have to include a trailing comma to make Python see a tuple:\nx = ((5,5),)\n\n",
"You need to add a comma after your f... | [
10,
6,
3,
2,
2
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0002014767_list_python_tuples.txt |
Q:
assertRaises just catches base exception
I'm running into a strange problem when using unittest.assertRaises. When executing the code below I get the following output:
E
======================================================================
ERROR: testAssertRaises (__main__.Test)
----------------------------------... | assertRaises just catches base exception | I'm running into a strange problem when using unittest.assertRaises. When executing the code below I get the following output:
E
======================================================================
ERROR: testAssertRaises (__main__.Test)
----------------------------------------------------------------------
Traceback... | [
"As mentioned, the issue is modules __main__ and derived are not one and the same; this answer is about how you fix that.\nDon't mix module code and script code. Start to think of if __name__ == \"__main__\" code as a hack. (It's still very convenient at times and I use it often for debugging, etc., but view it a... | [
2,
1,
0
] | [] | [] | [
"assertraises",
"python",
"unit_testing"
] | stackoverflow_0002013018_assertraises_python_unit_testing.txt |
Q:
How does this formatting code work?
I always have to know why, rather than just how, so here I go:
How does this work:
'{0:01.2f}'.format(5.555) #returns '5.55'
'{0:01.1f}'.format(5.555) #returns '5.5'
'{0:1.2f}'.format(5.555) #returns '5.55' again
'{0:1.1f}'.format(5.555) #returns '5.5' again
Why does t... | How does this formatting code work? | I always have to know why, rather than just how, so here I go:
How does this work:
'{0:01.2f}'.format(5.555) #returns '5.55'
'{0:01.1f}'.format(5.555) #returns '5.5'
'{0:1.2f}'.format(5.555) #returns '5.55' again
'{0:1.1f}'.format(5.555) #returns '5.5' again
Why does this not add zero padding by returning '05... | [
"Its because the 0 character enables zero-padding, but you have a width of 1 set. Set the width to 2 (like '{0:02.1f}' and you will see a leading 0.\nEdit - actually, I'm not sure if 2 will suffice, because I don't know how it behaves with more digits after the decimal point. So to be safe, make it something like... | [
6,
2
] | [] | [] | [
"python",
"string"
] | stackoverflow_0002015117_python_string.txt |
Q:
python gtk module opens display on import
I'm using the trick "python -c 'import myscript.py'" to perform a syntax check on a script which uses 'import gtk'.
I get the following error when performing the syntax check, which implies that the gtk module is executing a check for the X display, even though all that's ... | python gtk module opens display on import | I'm using the trick "python -c 'import myscript.py'" to perform a syntax check on a script which uses 'import gtk'.
I get the following error when performing the syntax check, which implies that the gtk module is executing a check for the X display, even though all that's being done at this point is to import the modul... | [
"Importing modules in Python executes their code!\nWell-behaved modules use the if __name__ == '__main__' trick to avoid side effects, but they can still fail - as happened to you.\n[BTW, getting to ImportError means the whole file already has correct syntax.]\nIf you just want to check syntax, without running at a... | [
3,
0,
0,
0,
0
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0001841949_gtk_python.txt |
Q:
How to create class instance inside that class method?
I want to create class instance inside itself. I tried to it by this way:
class matrix:
(...)
def det(self):
(...)
m = self(sz-1, sz-1)
(...)
(...)
but I got error:
m = self(sz-1, sz-1)
AttributeError: matrix instance has... | How to create class instance inside that class method? | I want to create class instance inside itself. I tried to it by this way:
class matrix:
(...)
def det(self):
(...)
m = self(sz-1, sz-1)
(...)
(...)
but I got error:
m = self(sz-1, sz-1)
AttributeError: matrix instance has no __call__ method
So, I tried to do it by this way:
class... | [
"m = self.__class__(sz-1, sz-1)\n\nor\nm = type(self)(sz-1, sz-1)\n\n"
] | [
15
] | [] | [] | [
"class",
"instance",
"python"
] | stackoverflow_0002015306_class_instance_python.txt |
Q:
What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP?
I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:
SyntaxError: Non-ASCII character '\xa3' in file dbscan.... | What encoding do I need to display a GBP sign (pound sign) using python on cygwin in Windows XP? | I have a python (2.5.4) script which I run in cygwin (in a DOS box on Windows XP). I want to include a pound sign (£) in the output. If I do so, I get this error:
SyntaxError: Non-ASCII character '\xa3' in file dbscan.py on line 253, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details
OK... | [
"The Unicode for a pound sign is 163 (decimal) or A3 in hex, so the following should work regardless of the encoding of your script, as long as the output encoding is working correctly.\nprint u\"\\xA3\"\n\n",
"try the encoding :\n# -*- coding: utf-8 -*-\nand then to display the '£' sign: \nprint unichr(163)\n\n"... | [
11,
4,
2
] | [] | [] | [
"encoding",
"python",
"python_2.5"
] | stackoverflow_0000705434_encoding_python_python_2.5.txt |
Q:
Using a list objects to look up items in a dictionary in Python
I have a a wxPython checklist box that returns a list of integers. I want to use the integers to look up items in a dictionary. I am not really sure the best way to do this. Any suggestions?
A:
Are you asking for
[ someDict[k] for k in someList ]
?... | Using a list objects to look up items in a dictionary in Python | I have a a wxPython checklist box that returns a list of integers. I want to use the integers to look up items in a dictionary. I am not really sure the best way to do this. Any suggestions?
| [
"Are you asking for\n[ someDict[k] for k in someList ]\n\n?\n"
] | [
7
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0002015385_dictionary_list_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.