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:
Print set() item fill with python generator
I have a generator:
foundUnique = set()
def unique_items(myList, index, clearFlag):
for item in myList:
if clearFlag is True:
foundUnique.clear()
clearFlag = False
if item[index] not in foundUnique:
yield item
... | Print set() item fill with python generator | I have a generator:
foundUnique = set()
def unique_items(myList, index, clearFlag):
for item in myList:
if clearFlag is True:
foundUnique.clear()
clearFlag = False
if item[index] not in foundUnique:
yield item
foundUnique.add(item[index])
And I am us... | [
"The problem is that unique_items is a generator so that \nsenderDupSend = unique_items(ip, 4, True)\n\nis a generator that needs to be iterated over. When you run\nfor item in foundUnique:\n print item\n\nthe generator has not actually run yet so foundUnique is still empty.\nWhen you later go on to do\nfor item... | [
4
] | [] | [] | [
"generator",
"python"
] | stackoverflow_0004104208_generator_python.txt |
Q:
AS3 RemoteObject with XMLRPC Python Server : "NetConnection.Call.BadVersion" problem
I want to use XMLRPC mechanism between my Flex app and my XMLRPC Python Server.
My server :
class ServerMockUp(SimpleXMLRPCRequestHandler):
# Services path declaration
rpc_paths = ()
myServer = SimpleXMLRPCServer(("localhost", 80... | AS3 RemoteObject with XMLRPC Python Server : "NetConnection.Call.BadVersion" problem | I want to use XMLRPC mechanism between my Flex app and my XMLRPC Python Server.
My server :
class ServerMockUp(SimpleXMLRPCRequestHandler):
# Services path declaration
rpc_paths = ()
myServer = SimpleXMLRPCServer(("localhost", 80),
requestHandler=ServerMockUp,
logRequest... | [
"Maybe it has something to do with objectEncoding.\nTry to set it to AMF0 with :\nnc.defaultObjectEncoding = ObjectEncoding.AMF0;\n\nJust before connecting.\n"
] | [
0
] | [] | [] | [
"actionscript_3",
"python",
"remoteobject",
"simplexmlrpcserver"
] | stackoverflow_0004101419_actionscript_3_python_remoteobject_simplexmlrpcserver.txt |
Q:
TRAC 0.12 buildout error - no attribute 'env_open'
I am trying to use Tarek Ziadé's Trac buildout recipe from PyPi (and his book 'Expert Python Programming', which I don't have access to.)
It worked fine the first time round, however upon creating a new (Python 2.6 virtualenv) environment I got the following error... | TRAC 0.12 buildout error - no attribute 'env_open' | I am trying to use Tarek Ziadé's Trac buildout recipe from PyPi (and his book 'Expert Python Programming', which I don't have access to.)
It worked fine the first time round, however upon creating a new (Python 2.6 virtualenv) environment I got the following error on buildout.
File "/usr/local/Plone/buildout-cache/eggs... | [
"pbp.recipe.trac 0.4.0 was just released and add full support of Trac 0.12: http://pypi.python.org/pypi/pbp.recipe.trac/0.4.0 .\n",
"The error appears to be caused by a change made between Trac 0.11 and 0.12.\nSetting the following in the buildout file, will result in a successful build.\n[buildout]\nversions = v... | [
1,
0,
0
] | [] | [] | [
"buildout",
"python",
"trac"
] | stackoverflow_0003460757_buildout_python_trac.txt |
Q:
Problem with Django site on a shared hosting
I have a problem when i try to install a Django website, on a Mocha hosting, and their technical support is so much uninformed... (I strongly don't recomment Mocha hosting for a django hosting)
They have mod_wsgi support, and mod_python installed, but when i am uploadin... | Problem with Django site on a shared hosting | I have a problem when i try to install a Django website, on a Mocha hosting, and their technical support is so much uninformed... (I strongly don't recomment Mocha hosting for a django hosting)
They have mod_wsgi support, and mod_python installed, but when i am uploading the site as in their tutorial
http://www.mocha... | [
"Do you double check that you upload a django in \n\n/home/youraccount/webapps/django\n\nMost likely the hosting provieder has harcode (width you account) \nthat path in the apache configuration for the mod_python approach.\nOr\nWhy don't you use mod_wsgi and in the wsgi script add your django, like this.\nimport ... | [
2,
1
] | [] | [] | [
"django",
"hosting",
"python",
"shared"
] | stackoverflow_0004103814_django_hosting_python_shared.txt |
Q:
Python ternary operator
Possible Duplicate:
Ternary conditional operator in Python
var foo = (test) ? "True" : "False";
What would this look like in Python?
Using Python 2.7 if that makes a difference.
A:
PEP 308 adds a ternary operator:
foo = "True" if test else "False"
It's been implemented since Python 2... | Python ternary operator |
Possible Duplicate:
Ternary conditional operator in Python
var foo = (test) ? "True" : "False";
What would this look like in Python?
Using Python 2.7 if that makes a difference.
| [
"PEP 308 adds a ternary operator:\nfoo = \"True\" if test else \"False\"\n\nIt's been implemented since Python 2.5\n"
] | [
94
] | [
"This one looks a bit more like original ternary:\nfoo=a and b or c\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0004103667_python.txt |
Q:
Python 2 to 3 bytes/string error
I'm trying to convert a Python library made for Python 2 to Python 3, here is the code.
I have an error at line 152. In the Py2 version, the function is:
def write(self, data):
self._write_buffer += data
The error is:
TypeError: Can't convert 'bytes'
object to str implici... | Python 2 to 3 bytes/string error | I'm trying to convert a Python library made for Python 2 to Python 3, here is the code.
I have an error at line 152. In the Py2 version, the function is:
def write(self, data):
self._write_buffer += data
The error is:
TypeError: Can't convert 'bytes'
object to str implicitly
I found that I've to decode the v... | [
"You need to be clear about where you want bytes and where you want strings. If you simply add decode and encode where the errors appear, you will be playing whack-a-mole. In your case, you are writing a socket implementation. Sockets deal with bytes, not strings. So I would think your _write_buffer should be a... | [
5
] | [] | [] | [
"byte",
"python",
"string"
] | stackoverflow_0004104485_byte_python_string.txt |
Q:
Python mechanize module proxy setting question
It seems like these codes would work:
MechBrowser = mechanize.Browser()
MechBrowser.set_proxies({"http": "111.11.11.11"})
response = MechBrowser.open("http://google.com")
But as you see "111.11.11.11" is just a random ip I came up with to test if the proxy setting wo... | Python mechanize module proxy setting question | It seems like these codes would work:
MechBrowser = mechanize.Browser()
MechBrowser.set_proxies({"http": "111.11.11.11"})
response = MechBrowser.open("http://google.com")
But as you see "111.11.11.11" is just a random ip I came up with to test if the proxy setting works, and it's not a valid proxy. The weird thing is ... | [
"Syntax is ok, and its working on my machine as it should do.\n------> print(mechanize.__version__)\n(0, 2, 1, None, None)\n\n>python -V\nPython 2.6.5\n\nWhen proxy is unavailable, for example, it will raise URLError. I can recommend you to check the version of mechanize+python you`re using at the moment and run th... | [
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0004102919_mechanize_python.txt |
Q:
Python Reflection and callable objects
I have a two part question.
>>> class One(object):
... pass
...
>>> class Two(object):
... pass
...
>>> def digest(constr):
... c = apply(constr)
... print c.__class__.__name__
... print constr.__class__.__name__
...
>>> digest(Two)
Two
type
How would ... | Python Reflection and callable objects | I have a two part question.
>>> class One(object):
... pass
...
>>> class Two(object):
... pass
...
>>> def digest(constr):
... c = apply(constr)
... print c.__class__.__name__
... print constr.__class__.__name__
...
>>> digest(Two)
Two
type
How would one create object 'Two'? Neither constr() or... | [
"Classes are high level objects, so you can simply pass them like this:\ndef createMyClass ( myClass ):\n obj = myClass()\n return obj\n\nclass A ( object ):\n pass\n\n>>> x = createMyClass( A )\n>>> type( x )\n<class '__main__.A'>\n\n",
"Just another one example:\ndef InstanceFactory(classname):\n cls... | [
5,
1,
1,
0
] | [] | [] | [
"class",
"oop",
"python",
"reflection"
] | stackoverflow_0004104156_class_oop_python_reflection.txt |
Q:
Best Practice for dealing with app engine cold start problem
After a period of inactivity the first request takes about 5 to 10 secs to come through.
Is there any best practice solutions to overcome this problem?
I'm using Python version of App Engine.
A:
Reduce the set of libraries you require in order to serve... | Best Practice for dealing with app engine cold start problem | After a period of inactivity the first request takes about 5 to 10 secs to come through.
Is there any best practice solutions to overcome this problem?
I'm using Python version of App Engine.
| [
"\nReduce the set of libraries you require in order to serve requests as much as you can.\nFor expensive libraries that are only used in some places, put the import statement inside the function that uses them. This way, the library is only imported the first time it's needed.\nIf your framework supports it, do jus... | [
6
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004104751_google_app_engine_python.txt |
Q:
Remove duplicate entries from nested dictionary, if two values are the same, in Python
Consider this dictionary format.
{1:{'name':'chrome', 'author':'google', 'url':'http://www.google.com/' },
2:{'name':'firefox','author':'mozilla','url':'http://www.mozilla.com/'}}
I want to remove all items which have the same... | Remove duplicate entries from nested dictionary, if two values are the same, in Python | Consider this dictionary format.
{1:{'name':'chrome', 'author':'google', 'url':'http://www.google.com/' },
2:{'name':'firefox','author':'mozilla','url':'http://www.mozilla.com/'}}
I want to remove all items which have the same name and author.
I can easily remove duplicate entries based on keys by putting all keys in... | [
"Iterate through the dictionary, keeping track of encountered (name, author) tuples as you go and remove those that you have already encountered:\ndef remove_duplicates(d):\n encountered_entries = set()\n for key, entry in d.items():\n if (entry['name'], entry['author']) in encountered_entries:\n ... | [
3,
1
] | [] | [] | [
"dictionary",
"python",
"python_2.5"
] | stackoverflow_0004104957_dictionary_python_python_2.5.txt |
Q:
PyQt QTableWidget keyboard events while editing
I want to navigate QTableWidget in a similar way to MS Excel.
For example, when the user presses the right arrow key while editing a cell, the editing will finish and the next cell to the right will be selected. I have searched the Qt docs, but can't seem to find ou... | PyQt QTableWidget keyboard events while editing | I want to navigate QTableWidget in a similar way to MS Excel.
For example, when the user presses the right arrow key while editing a cell, the editing will finish and the next cell to the right will be selected. I have searched the Qt docs, but can't seem to find out how.
| [
"from PyQt4.QtCore import QEvent, Qt\nfrom PyQt4.QtGui import QTableWidget, QWidget, QVBoxLayout, QApplication\n\n\nclass MyTableWidget(QTableWidget):\n def __init__(self):\n QTableWidget.__init__(self)\n\n self.keys = [Qt.Key_Left,\n Qt.Key_Right]\n\n # We need this to a... | [
5
] | [] | [] | [
"pyqt",
"pyside",
"python",
"qt"
] | stackoverflow_0003901829_pyqt_pyside_python_qt.txt |
Q:
problem using Python to increase virtual memory for my java application
I have created a java application in Eclipse which when I increase the VM arguments to -Xmx1024m runs fine. When I try to run the application via the command promt using the following path:
c:\python27\python c:\jars2run\run.py c:\jars2run\myo... | problem using Python to increase virtual memory for my java application | I have created a java application in Eclipse which when I increase the VM arguments to -Xmx1024m runs fine. When I try to run the application via the command promt using the following path:
c:\python27\python c:\jars2run\run.py c:\jars2run\myown\ClassTree.jar LiveSimulator2/Live_PairsEngine3 java -Xmx1024m
I get the fo... | [
"Change this line:\ncmd='java -classpath \"%s\" %s' % (cp, classfile)\n\nto\ncmd='java -Xmx1024m -classpath \"%s\" %s' % (cp, classfile)\n\nBTW: some pointers on Python:\n\nYou don't need semicolons on the ends of lines, and you don't need to wrap the if condition in parentheses.\nIf your format string is only \"%s... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0004105193_python.txt |
Q:
Advice for Python programmer writing C#
I've seen this question about advice for C# programmers writing Python code but I am going the opposite direction.
What are some tips, tricks, caveats for a Python programmer writing C# code?
A:
Here are some examples I meant by my question:
enumerate() in C#
another poss... | Advice for Python programmer writing C# | I've seen this question about advice for C# programmers writing Python code but I am going the opposite direction.
What are some tips, tricks, caveats for a Python programmer writing C# code?
| [
"Here are some examples I meant by my question:\n\nenumerate() in C#\nanother possibility:\n\"abc\".Where((x,i) => true).Select((x, i) => string.Format(\"{0}: {1}\", i, x))\n\n0: a\n1: b\n2: c\n\nlist comprehension in C#\nList<Foo> fooList = new List<Foo>();\nIEnumerable<Foo> extract = from foo in fooList where foo... | [
2
] | [] | [] | [
"c#",
"python"
] | stackoverflow_0004104885_c#_python.txt |
Q:
IDE don't see all the functions
i'm using Elcipse+PyDev and Pyscripter sometimes for Python 2.7
Yesterday i installed PyTables from compiled binaries and :
import tables
h5f = tables.openFile(r'D:\sample.h5','w')
h5f.createGroup('/','Box')
h5f.
So, when I type "h5f." IDE don't show me all the methods, only a few!... | IDE don't see all the functions | i'm using Elcipse+PyDev and Pyscripter sometimes for Python 2.7
Yesterday i installed PyTables from compiled binaries and :
import tables
h5f = tables.openFile(r'D:\sample.h5','w')
h5f.createGroup('/','Box')
h5f.
So, when I type "h5f." IDE don't show me all the methods, only a few!
Can't do anything with It, installed... | [
"The thing with Pydev and Eclipse is that when you install a new package or library and if you want to use the auto-complete with it, you will have to recreate the system PYTHONPATH in eclipse.\nFor that go to: Window -> Preferences -> Pydev -> Interpreted Python and in the tab libraries, in System PYTHONPATH you w... | [
2
] | [] | [] | [
"eclipse",
"pyscripter",
"python"
] | stackoverflow_0004104345_eclipse_pyscripter_python.txt |
Q:
wxpython filebrowsedialog button in Control Desk from dSPACE
iam working on a project and need to add a filebrowserdialog to my programm in control desk from dSPACE...
there is a way to do this in wxpython, but the problem is:
i dont know how to implement this in my control desk program..
i need to be able to add ... | wxpython filebrowsedialog button in Control Desk from dSPACE | iam working on a project and need to add a filebrowserdialog to my programm in control desk from dSPACE...
there is a way to do this in wxpython, but the problem is:
i dont know how to implement this in my control desk program..
i need to be able to add a button, when i click on it, it should show a filebrowserdialog a... | [
"You can create a FileDialog like so:\n import os\n\n dlg = wx.FileDialog(\n self, message=\"Choose a file\",\n defaultDir=os.getcwd(),\n defaultFile=\"\",\n style=wx.OPEN | wx.CHANGE_DIR\n )\n\n if dlg.ShowModal() == wx.ID_OK:\n ... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004104535_python_wxpython.txt |
Q:
Archives for Model in python to appengine
I'm a noob in python, and i'm creating a app into appengine with python.
I define class form Model's bug i don't know how order archives, normally, i create diferrent archives with all entities of my model, buy i don't know if in python is normal do the same think.
I think... | Archives for Model in python to appengine | I'm a noob in python, and i'm creating a app into appengine with python.
I define class form Model's bug i don't know how order archives, normally, i create diferrent archives with all entities of my model, buy i don't know if in python is normal do the same think.
I think is normal define Model for all app in one file... | [
"I found a \"simple\" project of google, with a example:\nhttp://code.google.com/p/google-app-engine-samples/source/browse/#svn/trunk/overheard\n"
] | [
0
] | [] | [] | [
"data_modeling",
"google_app_engine",
"python"
] | stackoverflow_0004105793_data_modeling_google_app_engine_python.txt |
Q:
BeautifulSoup not working
i am trying to import the content of my blog using BeautifulSoup,using the the syntax as given below
import urllib2
from BeautifulSoup import BeautifulSoup
response=urllib2.urlopen('http://www.bugsandbrains.blogspot.com')
html=response.read()
soup=Beautif... | BeautifulSoup not working | i am trying to import the content of my blog using BeautifulSoup,using the the syntax as given below
import urllib2
from BeautifulSoup import BeautifulSoup
response=urllib2.urlopen('http://www.bugsandbrains.blogspot.com')
html=response.read()
soup=BeautifulSoup(html)
Every thing worke... | [
"I just tried your code on Windows with:\n\nPython: 2.6 (same as yours)\nBeautiSoup: 3.0.8.1 (latest)\n\nI can't reproduce this. Are you using the latest code 3.0 series which is meant for Python 2.6, not 3.1 series which is for Python 3 [0]. Sorry, but can't think of any other clues right now.\n[0] http://www.crum... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"html",
"python"
] | stackoverflow_0004105377_beautifulsoup_html_python.txt |
Q:
Is there a way to group several keys which points to the same value in a dictionary?
Is there a way to group several keys which points to the same value in a dictionary?
A:
from collections import defaultdict
newdict = defaultdict(list)
for k,v in originaldict.items():
newdict[v].append(k)
A:
Not exactly ... | Is there a way to group several keys which points to the same value in a dictionary? | Is there a way to group several keys which points to the same value in a dictionary?
| [
"from collections import defaultdict\n\nnewdict = defaultdict(list)\nfor k,v in originaldict.items():\n newdict[v].append(k)\n\n",
"Not exactly sure you want the result structured, but here's one guess:\nfrom collections import defaultdict\n\nmydict = {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 4, 'f': 2, 'g': 4}\n\... | [
3,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004105376_dictionary_python.txt |
Q:
Manage #TODO (lots of files) with VIM
I use VIM/GVIM to develop my python projects and I randomly I leave #TODO comments in my code.
Is there any way to manage (search, list and link) all the #TODO occurrences inside VIM? I tried the tasklist plugin, it's almost what I need, but it only lists the current file #TO... | Manage #TODO (lots of files) with VIM | I use VIM/GVIM to develop my python projects and I randomly I leave #TODO comments in my code.
Is there any way to manage (search, list and link) all the #TODO occurrences inside VIM? I tried the tasklist plugin, it's almost what I need, but it only lists the current file #TODO occurrences. Generally my projects has s... | [
"If you just want a list of the occurences of \"TODO\" in .py files in the working directory, you can just use :vimgrep like so:\n:vimgrep TODO **/*.py\n\nThen open the quickfix window with:\n:cw\n\n(it might open it automatically anyway, not sure) and just scroll through the results, hitting Enter to go to each oc... | [
52
] | [] | [] | [
"comments",
"python",
"todo",
"vim"
] | stackoverflow_0004106137_comments_python_todo_vim.txt |
Q:
Read a number of random lines from a file in Python
Could someone show me how I could read a random number of lines from a file in Python?
A:
Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else):
from random import random
lines = [line for line in open("/... | Read a number of random lines from a file in Python | Could someone show me how I could read a random number of lines from a file in Python?
| [
"Your requirement is a bit vague, so here's another slightly different method (for inspiration if nothing else):\nfrom random import random\nlines = [line for line in open(\"/some/file\") if random() >= .5]\n\nCompared with the other solutions, the number of lines varies less (distribution around half the total num... | [
17,
15,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004105778_python.txt |
Q:
Getting NppExec to understand path of the current file in Notepad++ (for Python scripts)
Using windows for the first time in quite awhile and have picked up notepad++ and am using the nppexec plugin to run python scripts. However, I noticed that notepad++ doesn't pick up the directory that my script is saved in. ... | Getting NppExec to understand path of the current file in Notepad++ (for Python scripts) | Using windows for the first time in quite awhile and have picked up notepad++ and am using the nppexec plugin to run python scripts. However, I noticed that notepad++ doesn't pick up the directory that my script is saved in. For example, I place "script.py" in 'My Documents' however os.getcwd() prints "Program Files \ ... | [
"Notepad++ >nppexec >follow $(current directory)\n",
"You could put something like this at the beginning of your script:\nimport os\nos.chdir(os.path.dirname(__file__))\n\n"
] | [
15,
2
] | [] | [] | [
"notepad++",
"nppexec",
"python"
] | stackoverflow_0004103085_notepad++_nppexec_python.txt |
Q:
intermittent smtp broken pipe (errno 32)
I have a python script that sends out a few sets of emails (to different addresses with different contents) using smtplib periodically throughout the day. Somewhat frequently (say about 1 in 5 times when sending out batches of more than one email at the same time), I get a... | intermittent smtp broken pipe (errno 32) | I have a python script that sends out a few sets of emails (to different addresses with different contents) using smtplib periodically throughout the day. Somewhat frequently (say about 1 in 5 times when sending out batches of more than one email at the same time), I get a IOError (errno: broken pipe). I try resetin... | [
"Also would it be safer to use /usr/sbin/sendmail rather than smtplib?\nFrom the point of view of handling a message queue and a queue-runner for retries. Yes, sendmail or another local MTA could handle this for you.\nAny thoughts on how to proceed debugging this?\nPacket capture. Use wireshark to capture the smtp ... | [
1
] | [] | [] | [
"python",
"smtp",
"smtplib"
] | stackoverflow_0004106141_python_smtp_smtplib.txt |
Q:
How to use property of object... Python!
In a module I defined a class with the following __init__ method:
class RMLoader(object):
def __init__(self):
self.now=datetime.datetime.now()
then I'm importing that module in console:
>>> from video.remmedia.loader import RMLoader
>>> loader=RMLoader()
>>> lo... | How to use property of object... Python! | In a module I defined a class with the following __init__ method:
class RMLoader(object):
def __init__(self):
self.now=datetime.datetime.now()
then I'm importing that module in console:
>>> from video.remmedia.loader import RMLoader
>>> loader=RMLoader()
>>> loader.now
datetime.datetime(2010, 11, 4, 17, 40... | [
"It is a standard datetime object all the time. The difference is that loader.now will invoke repr, and print loader.now will invoke str. The first one is designed to give an accurate representation of the object, ideally one that would evaluate to an identical object. The second one is designed to provide a readab... | [
8
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0004106308_datetime_python.txt |
Q:
How can store a file on Google Storage from URL on Google App Engine?
I want to create a service on Google App Engine (Python) that will receive a URL of an image and store it on Google Storage. I managed to upload from a local file using boto or gsutil command line, but not by retrieving the file via URL. I tried... | How can store a file on Google Storage from URL on Google App Engine? | I want to create a service on Google App Engine (Python) that will receive a URL of an image and store it on Google Storage. I managed to upload from a local file using boto or gsutil command line, but not by retrieving the file via URL. I tried doing it using the HTTP requests (PUT) and I'm getting error responses for... | [
"Have you read the docs on how to sign requests? The string to sign must include the Content-MD5, Content-Type and Date headers, in addition to the custom headers and the resource path.\n",
"Content-MD5 header is optional for PUT requests. Try leaving this out for a test.\nAlso, required headers are Authorization... | [
1,
1
] | [] | [] | [
"boto",
"google_app_engine",
"google_cloud_storage",
"python"
] | stackoverflow_0004105901_boto_google_app_engine_google_cloud_storage_python.txt |
Q:
HTML Generator, Gallery Generator or Templating?
SMALL VERSION OF THE QUESTION: " I need a lib for python or program (pref. for Linux) that receives a list of urls for images and gives me the hmtl for a table (maybe easy to configure(rows and look))
LONG VERSION OF THE QUESTION:
I have and array with a list of url... | HTML Generator, Gallery Generator or Templating? | SMALL VERSION OF THE QUESTION: " I need a lib for python or program (pref. for Linux) that receives a list of urls for images and gives me the hmtl for a table (maybe easy to configure(rows and look))
LONG VERSION OF THE QUESTION:
I have and array with a list of url's for images, and I want to make a table (I don't kno... | [
"I think the easiest way to achieve this would be to use a template language like Mako, Cheetah or Jinja. Personally i'd choose Jinja, because it is very similar to the Django template language, but they are all very powerful.\nA very simple example of what you want, using Jinja, would look like this:\nfrom jinja2 ... | [
4,
0
] | [] | [] | [
"html",
"python",
"templating_engine"
] | stackoverflow_0004106367_html_python_templating_engine.txt |
Q:
In Google App Engine, how do you select entities where an attribute does not exist?
Using the python version of GAE and extending models from db.Model, how do you fetch entities where an attribute equals None or does not exist?
#This works
#Fetch 10 entities where duration == 0.0
entities = MyModel.all().filter(... | In Google App Engine, how do you select entities where an attribute does not exist? | Using the python version of GAE and extending models from db.Model, how do you fetch entities where an attribute equals None or does not exist?
#This works
#Fetch 10 entities where duration == 0.0
entities = MyModel.all().filter('duration = ', 0.0).fetch(10)
#This doesn't. How can I do the equivalent?
#Fetch 10 enti... | [
"You have entities without duration property (can't be filtered because index can't refer to them) and entities with duration set to None (can be filtered).\nSince you have changed MyModel schema, you should fix the entities stored without duration property with something like this:\nentities = MyModel.all()\nfor e... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004106500_google_app_engine_python.txt |
Q:
passing boolean condition as parameter
I have these
def MsgBox1_YesChosen(sender,e):
if e.Key != "A": function0()
else:
function1()
function2()
function3()
def MsgBox1_NoChosen(sender,e):
if e.Key == "A": function0()
else:
function1()
function2()
... | passing boolean condition as parameter | I have these
def MsgBox1_YesChosen(sender,e):
if e.Key != "A": function0()
else:
function1()
function2()
function3()
def MsgBox1_NoChosen(sender,e):
if e.Key == "A": function0()
else:
function1()
function2()
function3()
can both def be merged togethe... | [
"Yes, in a very generalized fashion - you just need to wrap your head around the facts that (1) functions are first-class values and (2) operators are just functions with special syntactic treatment. For example:\ndef make_handler(predicate)\n def handler(sender, e):\n if predicate(e.Key, 'A'):\n ... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004106723_python.txt |
Q:
startswith on a constant in sqlalchemy
I'm trying to do something like this:
Session.query(some_table).filter("/some/path/to/element".startswith(some_table.path)).all()
That is, get all "parent" elements of a certain path. I tried doing it like this:
Session.query(some_table).filter(sqlalchemy.sql.expression.lite... | startswith on a constant in sqlalchemy | I'm trying to do something like this:
Session.query(some_table).filter("/some/path/to/element".startswith(some_table.path)).all()
That is, get all "parent" elements of a certain path. I tried doing it like this:
Session.query(some_table).filter(sqlalchemy.sql.expression.literal("/some/path/to/element").startswith(some... | [
"i don't understand what you are try to do, because it not that filter just get a boolean filter should get an expression that will loop over it to filter data.\nlook at this example (i don't think you want this one but maybe it can give you some Hint):\nSession.query(some_table).filter(some_table.path.like('%/some... | [
0,
0
] | [] | [] | [
"python",
"sql",
"sqlalchemy",
"startswith"
] | stackoverflow_0004106499_python_sql_sqlalchemy_startswith.txt |
Q:
Collecting, storing, and retrieving large amounts of numeric data
I am about to start collecting large amounts of numeric data in real-time (for those interested, the bid/ask/last or 'tape' for various stocks and futures). The data will later be retrieved for analysis and simulation. That's not hard at all, but ... | Collecting, storing, and retrieving large amounts of numeric data | I am about to start collecting large amounts of numeric data in real-time (for those interested, the bid/ask/last or 'tape' for various stocks and futures). The data will later be retrieved for analysis and simulation. That's not hard at all, but I would like to do it efficiently and that brings up a lot of questions... | [
"\nOptimizing for disk space and IO speed is the same thing - these days, CPUs are so fast compared to IO that it's often overall faster to compress data before storing it (you may actually want to do that). I don't really see memory playing a big role (though you should probably use a reasonably-sized buffer to en... | [
3,
1,
1,
1,
0,
0
] | [] | [] | [
"c++",
"java",
"python",
"simulation",
"storage"
] | stackoverflow_0004098509_c++_java_python_simulation_storage.txt |
Q:
Dictionary acting weird, and how to pack into binary
I have the code
from struct import pack
self.data = {'SYNC' : 0x16, 'SOH' : 0x01,
'FnCode' : 0x55, 'pacingState' : 0,
'pacingMode' : 6, 'hysteresis' : 0,
'hysteresisInterval' : 300, 'lowrateInterval' : 1... | Dictionary acting weird, and how to pack into binary | I have the code
from struct import pack
self.data = {'SYNC' : 0x16, 'SOH' : 0x01,
'FnCode' : 0x55, 'pacingState' : 0,
'pacingMode' : 6, 'hysteresis' : 0,
'hysteresisInterval' : 300, 'lowrateInterval' : 1000,
'vPaceAmp' : 3500, 'vPaceWidth' : 4,... | [
"Dictionaries do not maintain insertion order of keys, as they are hash tables and do not keep track of key insertion order. If you need an ordered dictionary, Python 2.7 and 3.1 has collections.OrderedDict. If you are using an older Python version, check out this ActiveState recipe.\nAs to why your pack is complai... | [
3,
3
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0004107008_python_struct.txt |
Q:
Django Annotations For Group By Through Another Model
I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
class Store(models.Model):
nam... | Django Annotations For Group By Through Another Model | I'm having a hard time trying to figure out how to use annotations in the Django ORM to achieve grouping through a model.
from django.db import models
class Customer(models.Model):
name = models.CharField(max_length=255)
class Store(models.Model):
name = models.CharField(max_length=255)
class Order(models.Mo... | [
"Define a ManyToMany field on either Customer or Store, pointing to the other model, with Order as the through table. For example:\nclass Store(models.Model):\n name = models.CharField(max_length=255)\n orders = models.ManyToManyField(Customer, through=Order)\n\nNow you can do:\nfrom django.db.models import C... | [
0
] | [] | [] | [
"annotations",
"django",
"group_by",
"orm",
"python"
] | stackoverflow_0004107070_annotations_django_group_by_orm_python.txt |
Q:
Amend a csv file in Python
So I have a CSV file with a bunch on IP's in it:
192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4,192.168.0.5,192.168.0.6,192.168.0.7,192.168.0.8,192.168.0.9,192.168.0.10
And I would like to add a new ip to the end of this csv file. Currently I am using this code to read in the data:
req... | Amend a csv file in Python | So I have a CSV file with a bunch on IP's in it:
192.168.0.1,192.168.0.2,192.168.0.3,192.168.0.4,192.168.0.5,192.168.0.6,192.168.0.7,192.168.0.8,192.168.0.9,192.168.0.10
And I would like to add a new ip to the end of this csv file. Currently I am using this code to read in the data:
requests = csv.reader(open("file.cs... | [
"Why don't you just append a new row?\nfd = open('file.csv','a')\nfd.write(yourCsvRowWithNewIP)\nfd.close()\n\n"
] | [
9
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004107096_csv_python.txt |
Q:
Logging strategy for GUI program
I'm thinking it may be beneficial to sprinkle some debug logging throughout my app (a painting-type program), and to have this info written to a file. My current debugging strategy is to hook up a custom exception listener (sys.excepthook) and to allow the user to e-mail me a copy ... | Logging strategy for GUI program | I'm thinking it may be beneficial to sprinkle some debug logging throughout my app (a painting-type program), and to have this info written to a file. My current debugging strategy is to hook up a custom exception listener (sys.excepthook) and to allow the user to e-mail me a copy of the stack trace that caused the cra... | [
"As said before you can use the logger module. You can set a default level of logging (for example Warning) and put all kind of messages in you code, since debug until critical. As humble explanation, if you set your logging level as Warning, even if your code log debug messages they will not appear in the file (or... | [
6,
0
] | [] | [] | [
"logging",
"python",
"user_interface"
] | stackoverflow_0004004353_logging_python_user_interface.txt |
Q:
Python: Write 1,000,000 ints to file
What is the most compact way to write 1,000,000 ints (0, 1, 2...) to file using Python without zipping etc? My answer is: 1,000,000 * 3 bytes using struct module, but it seems like interviewer expected another answer...
Edit. Numbers from 1 to 1,000,000 in random order (so tran... | Python: Write 1,000,000 ints to file | What is the most compact way to write 1,000,000 ints (0, 1, 2...) to file using Python without zipping etc? My answer is: 1,000,000 * 3 bytes using struct module, but it seems like interviewer expected another answer...
Edit. Numbers from 1 to 1,000,000 in random order (so transform like 5, 6, 7 -> 5-7 can be applied i... | [
"Actually, you can do A LOT better than 2.5MB, since not all orderings are possible. One might argue that beating 5% would involve compression, since one is not storing the sequence itself. Basically, you would want to store the canonical sequence number. 8 numbers from 0-7 in random order normally takes 24 bits... | [
4,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004104898_python.txt |
Q:
Python - Iteration Testing a SOAP service; need to use different variables per iteration
Ok here's my scenario (be kind, only been using Python for a short while):
I have a service I'm calling and need to run several iterations of the same test with a different variable passed to the method. I am able to run iter... | Python - Iteration Testing a SOAP service; need to use different variables per iteration | Ok here's my scenario (be kind, only been using Python for a short while):
I have a service I'm calling and need to run several iterations of the same test with a different variable passed to the method. I am able to run iterations against a single method just fine but I need the variable to change per each test and w... | [
"There's a lot we could talk about regarding automated testing in Python, but the problem here is that you don't seem to be invoking your Data method.\nIf you change your code like this:\ndef Run(self)\n self.Data()\n client = Client(wsdl)\n ...\n\ndoes it do what you need?\n"
] | [
1
] | [] | [] | [
"automated_tests",
"iteration",
"python",
"testing"
] | stackoverflow_0004107132_automated_tests_iteration_python_testing.txt |
Q:
Wx.Widgets AUIMananger Toggle Panes
I'm having trouble toggling panes with the AUIManager.
Here's basically what I'm doing:
class foo(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=wx.Size(800,600))
self.menubar = wx.MenuBar()
self._mgr... | Wx.Widgets AUIMananger Toggle Panes | I'm having trouble toggling panes with the AUIManager.
Here's basically what I'm doing:
class foo(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self,parent,wx.ID_ANY,title,size=wx.Size(800,600))
self.menubar = wx.MenuBar()
self._mgr = wx.aui.AuiManager(self)
self._... | [
"This method works fine for me. It should for you too if you call Update() on your window manager after you show or hide your pane.\n def togglePane(self,event):\n if self._mgr.GetPane('Widget Name').IsShown():\n self._mgr.GetPane('Widget Name').Hide()\n else:\n self._mgr.GetPane('Widget Name... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0001875396_python_wxpython.txt |
Q:
Django Question
Can you take things like the poll app from the tutorial and display them in an iframe or frameset? The tutorial is great and the app is very nice, but, how often do you go to a site with a whole page dedicated to a poll? I was trying to think about how you do it using the urls.py file, but couldn't... | Django Question | Can you take things like the poll app from the tutorial and display them in an iframe or frameset? The tutorial is great and the app is very nice, but, how often do you go to a site with a whole page dedicated to a poll? I was trying to think about how you do it using the urls.py file, but couldn't wrap my head around ... | [
"Placing poll data in an extra iframe won't be necessary. You can write a templatetag, to display it on everywhere you need to.\nedit\nThe chapter \"inclusion tags\" refers to the poll example app.\nSee http://docs.djangoproject.com/en/1.2/howto/custom-template-tags/\n",
"Put the poll page in its own view, connec... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004107644_django_python.txt |
Q:
Understanding objects in Python
I am a little confused by the object model of Python. I have two classes, one inherits from the other.
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
What I am trying to do is not to over... | Understanding objects in Python | I am a little confused by the object model of Python. I have two classes, one inherits from the other.
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
What I am trying to do is not to override the __init__() method, but to cr... | [
">>> class Node(object):\n... def __init__(self, id_):\n... self.id_ = id_\n... \n>>> class Atom(Node):\n... def __init__(self, symbol, id_):\n... super(Atom, self).__init__(id_)\n... self.symbol = symbol\n... \n>>> a = Atom(\"FE\", 1)\n>>> a.symbol\n'FE'\n>>> a.id_\n1\n>... | [
7,
6,
3,
2,
1,
1
] | [] | [] | [
"object",
"object_model",
"python"
] | stackoverflow_0004107740_object_object_model_python.txt |
Q:
Access to class attributes of parent classes
I would like to know what is the best way to get all the attributes of a class when I don't know the name of them.
Let's say I have:
#!/usr/bin/python2.4
class A(object):
outerA = "foobar outerA"
def __init__(self):
self.innerA = "foobar innerA"
class ... | Access to class attributes of parent classes | I would like to know what is the best way to get all the attributes of a class when I don't know the name of them.
Let's say I have:
#!/usr/bin/python2.4
class A(object):
outerA = "foobar outerA"
def __init__(self):
self.innerA = "foobar innerA"
class B(A):
outerB = "foobar outerB"
def __init_... | [
"I think you're looking for dir() - it works just as well within code as in the shell.\n",
"Try dir(b). The resulting list includes inherited attributes.\n"
] | [
2,
1
] | [] | [] | [
"attributes",
"inheritance",
"oop",
"python"
] | stackoverflow_0004107996_attributes_inheritance_oop_python.txt |
Q:
Overwrite property using Python
How do you overwrite the getter of the property in Python ?
I've tried to do:
class Vehicule(object):
def _getSpatials(self):
pass
def _setSpatials(self, newSpatials):
pass
spatials = property(_getSpatials, _setSpatials)
class Car(Vehicule)
def _... | Overwrite property using Python | How do you overwrite the getter of the property in Python ?
I've tried to do:
class Vehicule(object):
def _getSpatials(self):
pass
def _setSpatials(self, newSpatials):
pass
spatials = property(_getSpatials, _setSpatials)
class Car(Vehicule)
def _getSpatials(self):
spatials =... | [
"It looks like you want Car's spatial property's getter to call Vehicule's\nspatial property's getter. You can achieve that with\nclass Vehicule(object):\n def __init__(self):\n self._spatials = 1\n def _getSpatials(self):\n print(\"Calling Vehicule's spatials getter\")\n return self._spa... | [
3,
2
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0004107988_inheritance_python.txt |
Q:
Why are some callable attributes not listed by the dir() function?
How come the dir() function in Python doesn't show all of the callable attributes?
import win32com.client
iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
currentTrack = win32com.client.CastTo(iTunes.CurrentTrack,"IITFileOrCD... | Why are some callable attributes not listed by the dir() function? | How come the dir() function in Python doesn't show all of the callable attributes?
import win32com.client
iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
currentTrack = win32com.client.CastTo(iTunes.CurrentTrack,"IITFileOrCDTrack")
print dir(currentTrack)
Result:
['AddArtworkFromFile', 'CLSID'... | [
"In python, an object can have a __getattr__ method. It will be invoked for any attribute access for a non-existent attribute. It looks like this object is using _prop_map_get_ as part of its implementation of __getattr__.\nSince __getattr__ can do arbitrary computation to satisfy the attribute request, and can r... | [
7,
4
] | [] | [] | [
"itunes",
"python",
"win32com"
] | stackoverflow_0004108298_itunes_python_win32com.txt |
Q:
Python: Adding Dictionary Items.
When we add dictionary Items,
we use x.items()+y.items(), but there was something I don't understand.
for example
if x={2:2,1:3} and y={1:3,3:1} x.items()+y.items() gives {3:1,2:2,1:3}
so, as you can see, the answer mathematically could have been 6x+2x^2+x^3,
but the dictionary ... | Python: Adding Dictionary Items. | When we add dictionary Items,
we use x.items()+y.items(), but there was something I don't understand.
for example
if x={2:2,1:3} and y={1:3,3:1} x.items()+y.items() gives {3:1,2:2,1:3}
so, as you can see, the answer mathematically could have been 6x+2x^2+x^3,
but the dictionary gives x^3+2x^2+3x,
can any one tell me... | [
"Let's be clear what's going on here!\nIn [7]: x.items()\nOut[7]: [(1, 3), (2, 2)]\n\nIn [8]: y.items()\nOut[8]: [(1, 3), (3, 1)]\n\nIn [9]: x.items() + y.items()\nOut[9]: [(1, 3), (2, 2), (1, 3), (3, 1)]\n\nIn [10]: dict(x.items() + y.items())\nOut[10]: {1: 3, 2: 2, 3: 1}\n\nitems() produces a list of (key, value... | [
5,
3,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004106896_dictionary_python.txt |
Q:
Create shortcut to .pyw file from within python
I was wondering how to create a shortcut in python to .pyw extensions and .exe's.
A:
You need to create and use a IShellLink via COM.
| Create shortcut to .pyw file from within python | I was wondering how to create a shortcut in python to .pyw extensions and .exe's.
| [
"You need to create and use a IShellLink via COM.\n"
] | [
2
] | [] | [] | [
"python",
"pywin32",
"shortcut",
"windows"
] | stackoverflow_0004108336_python_pywin32_shortcut_windows.txt |
Q:
exception handling with NameError
I want to append new input to list SESSION_U without erasing its content. I try this:
...
try:
SESSION_U.append(UNIQUES)
except NameError:
SESSION_U = []
SESSION_U.append(UNIQUES)
...
I would think that at first try I would get... | exception handling with NameError | I want to append new input to list SESSION_U without erasing its content. I try this:
...
try:
SESSION_U.append(UNIQUES)
except NameError:
SESSION_U = []
SESSION_U.append(UNIQUES)
...
I would think that at first try I would get the NameError and SESSION_U list would... | [
"It appears that the code you posted is probably contained within a request handler. What are your requirements regarding this SESSION_U list? Clearly you want it to be preserved across requests, but there are several ways to do this and the best choice depends on your requirements.\nI suspect you want to store S... | [
0
] | [] | [] | [
"exception_handling",
"google_app_engine",
"python"
] | stackoverflow_0004107698_exception_handling_google_app_engine_python.txt |
Q:
Generating an ascending list of numbers of arbitrary length in python
Is there a function I can call that returns a list of ascending numbers? I.e., function(10) would return [0,1,2,3,4,5,6,7,8,9]?
A:
You want range().
A:
range(10) is built in.
A:
If you want an iterator that gives you a series of indetermin... | Generating an ascending list of numbers of arbitrary length in python | Is there a function I can call that returns a list of ascending numbers? I.e., function(10) would return [0,1,2,3,4,5,6,7,8,9]?
| [
"You want range().\n",
"range(10) is built in.\n",
"If you want an iterator that gives you a series of indeterminate length, there is itertools.count(). Here I am iterating with range() so there is a limit to the loop.\n>>> import itertools\n>>> for x, y in zip(range(10), itertools.count()):\n... print x, y... | [
33,
12,
9
] | [] | [] | [
"list",
"python",
"range"
] | stackoverflow_0004108341_list_python_range.txt |
Q:
Using a .net regex in Python
I have some regular expressions written for the Microsoft's .net regex format and I want to use them in a python program on a Linux machine. Is there a compatibly library or a method of covering them? If I have to do it by hand, do you know of a cheat sheet or a guide?
A:
Most of... | Using a .net regex in Python | I have some regular expressions written for the Microsoft's .net regex format and I want to use them in a python program on a Linux machine. Is there a compatibly library or a method of covering them? If I have to do it by hand, do you know of a cheat sheet or a guide?
| [
"Most of the features in .NET regexes are available in Python; however there are a few things missing:\n\nPython doesn't support variable repetition inside lookbehinds, only fixed-length.\nPython uses a different syntax for named captures.\nPython matches Unicode characters differently.\nPython doesn't have atomic ... | [
6,
1,
1,
0
] | [] | [] | [
".net",
"pcre",
"python",
"regex"
] | stackoverflow_0004108542_.net_pcre_python_regex.txt |
Q:
How to exclude a character from a regex group?
I want to strip all non-alphanumeric characters EXCEPT the hyphen from a string (python).
How can I change this regular expression to match any non-alphanumeric char except the hyphen?
re.compile('[\W_]')
Thanks.
A:
You could just use a negated character class inst... | How to exclude a character from a regex group? | I want to strip all non-alphanumeric characters EXCEPT the hyphen from a string (python).
How can I change this regular expression to match any non-alphanumeric char except the hyphen?
re.compile('[\W_]')
Thanks.
| [
"You could just use a negated character class instead:\nre.compile(r\"[^a-zA-Z0-9-]\")\n\nThis will match anything that is not in the alphanumeric ranges or a hyphen. It also matches the underscore, as per your current regex.\n>>> r = re.compile(r\"[^a-zA-Z0-9-]\")\n>>> s = \"some#%te_xt&with--##%--5 hy-phens *#\"... | [
42,
9
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004108561_python_regex.txt |
Q:
How to query for a row with a specific DateTime value using GQL?
I tried just using the date's string representation but it didn't work (i.e. no results):
gql = "SELECT * from Shout where when='2010-11-05 16:57:45.675612'"
This is my Shout class:
class Shout(db.Model):
message= db.StringProperty(required=True)... | How to query for a row with a specific DateTime value using GQL? | I tried just using the date's string representation but it didn't work (i.e. no results):
gql = "SELECT * from Shout where when='2010-11-05 16:57:45.675612'"
This is my Shout class:
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringPr... | [
"gql = \"SELECT * FROM Shout WHERE when = DATETIME('2010-11-05 16:57:45')\"\n\nPer documentation, use the following for date/time literals: \n\nDATETIME() with timestamps, \nDATE() with dates, \nTIME() with times\n\nAn alternative syntax is:\nSELECT * FROM Shout WHERE when = DATETIME(2010,11,5,16,57,45)\n\n"
] | [
1
] | [] | [] | [
"datetime",
"google_app_engine",
"gql",
"python"
] | stackoverflow_0004108581_datetime_google_app_engine_gql_python.txt |
Q:
Split Regular expression after each repetition
I'm experimenting arround with template engines lately and am stuck in a very early stage at a regular expression.
The first Step in my template engine should be to extract all template constructs. So I wrote following regular expression:
# Split all relevant parts a... | Split Regular expression after each repetition | I'm experimenting arround with template engines lately and am stuck in a very early stage at a regular expression.
The first Step in my template engine should be to extract all template constructs. So I wrote following regular expression:
# Split all relevant parts apart to merger them later on.
exp_tags = re.compile(... | [
"Regular expression quantifiers are greedy by default. Either use the non-greedy variant of * by appending ? to it:\nr'({[%|{](.*?)[}|%]})'\n\nOr use a negated character class to exclude the end delimiters.\nBy the way: The character class [a|b] does not mean either a or b but one of the set of {a, |, b} as the | i... | [
3
] | [] | [] | [
"python",
"regex",
"templates"
] | stackoverflow_0004108674_python_regex_templates.txt |
Q:
Difference between '' and "" in Python
What is the difference between apostrophes and quotation marks in Python?
So far I've only been able to find one difference
print "'"
print '"'
print '''
print """
The first print statement will output ' while the second ". However the third statement starts a comment blo... | Difference between '' and "" in Python | What is the difference between apostrophes and quotation marks in Python?
So far I've only been able to find one difference
print "'"
print '"'
print '''
print """
The first print statement will output ' while the second ". However the third statement starts a comment block.
Any other differences I should be aware... | [
"print 'Hello' and print \"Hello\" are the same and what you use is your personal preference. \"\"\" and ''' are for multiline strings. \n>>> print \"\"\"First\nSecond\nThird\"\"\"\n\nFirst\nSecond\nThird\n\n",
"\nPython has a facility multiline string that starts with triple quotes.\n\nThey are also commonly use... | [
14,
8,
5,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0004108743_python.txt |
Q:
Django's introspecting administrator: How does it work?
I don't really want to know Django I am actually more interested in the administrator. The thing that interests me is how they introspect the models to create the administrator back-end.
I browsed through the Django source code and found a little info but sin... | Django's introspecting administrator: How does it work? | I don't really want to know Django I am actually more interested in the administrator. The thing that interests me is how they introspect the models to create the administrator back-end.
I browsed through the Django source code and found a little info but since it's such a big project I was wondering if there are small... | [
"With Django it's a bit more than introspection actually. The models use a metaclass to register themselves, I will spare you the complexities of everything involved but the admin does not introspect the models as you browse through it.\nInstead, the registering process creates a _meta object on the model with all ... | [
4,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004108852_django_python.txt |
Q:
How can I test if a list contains another list with particular items in Python?
I have a list of lists and want to check if it already contains a list with particular items.
Everything should be clear from this example:
list = [[1,2],[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
if test in list:
print ... | How can I test if a list contains another list with particular items in Python? | I have a list of lists and want to check if it already contains a list with particular items.
Everything should be clear from this example:
list = [[1,2],[3,4],[4,5],[6,7]]
for test in [[1,1],[1,2],[2,1]]:
if test in list:
print True
else:
print False
#Expected:
# False
# True
# True
... | [
"What you want to use is a set:\nset([1,2]) == set([2,1])\nreturns True.\nSo\nlist = [set([1,2]),set([3,4]),set([4,5]),set([6,7])]\nset([2,1]) in list\n\nalso returns True.\n",
"If they're really sets, use the set type\n# This returns True \nset([2,1]) <= set([1,2,3])\n\n<= means 'is a subset of' when dealing wit... | [
6,
5,
1
] | [] | [] | [
"list",
"python",
"sorting"
] | stackoverflow_0004108950_list_python_sorting.txt |
Q:
Django - Customising the display of FormSet objects?
I have a formset with can_delete set, i.e. I want to allow people to be able to delete the objects. I want to customise the layout of each of the forms, like this: http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template . I can add the f... | Django - Customising the display of FormSet objects? | I have a formset with can_delete set, i.e. I want to allow people to be able to delete the objects. I want to customise the layout of each of the forms, like this: http://docs.djangoproject.com/en/dev/topics/forms/#customizing-the-form-template . I can add the fields for each form with {{ form.name_of_field }}, etc. Ho... | [
"{{ form.DELETE }}\n\n"
] | [
4
] | [] | [] | [
"django",
"django_forms",
"django_templates",
"python"
] | stackoverflow_0004107534_django_django_forms_django_templates_python.txt |
Q:
Google App Engine Data Store Model Reference Another Class
So that you can understand the data model, I basically have cities and within each one I'll have categories and then inside each category I'll have listings. Here's what I have so far.
from google.appengine.ext import db
class City(db.Model):
name = ... | Google App Engine Data Store Model Reference Another Class | So that you can understand the data model, I basically have cities and within each one I'll have categories and then inside each category I'll have listings. Here's what I have so far.
from google.appengine.ext import db
class City(db.Model):
name = db.StringProperty(required=True)
connections = db.ListProper... | [
"You want to look at a custom property named KeyListProperty in App Engine Patch. That will give you the sort of many-to-many relationship you want.\n",
"You need to throw the categories property from your City and use a ReferenceProperty in your Category class:\nclass Category(db.Model)\n name = db.StringProp... | [
1,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004107660_google_app_engine_google_cloud_datastore_python.txt |
Q:
How do I make Selenium RC to not move the browser window?
Is there a way to specify where Selenium RC spawns the browser window?
When I run my test script, Selenium RC opens 2 windows in the browser, the Selenium RC window and the AUT, and the Selenium RC window takes up most of my screen space. Ideally, I want to... | How do I make Selenium RC to not move the browser window? | Is there a way to specify where Selenium RC spawns the browser window?
When I run my test script, Selenium RC opens 2 windows in the browser, the Selenium RC window and the AUT, and the Selenium RC window takes up most of my screen space. Ideally, I want to control where their location and size separately, but if not, ... | [
"This works from java:\nselenium.getEval(\"this.browserbot.getCurrentWindow().moveTo((\" + h + \"),(\" + v + \"))\");\nselenium.getEval(\"this.browserbot.getCurrentWindow().resizeTo(\" + w + \",\" + h + \")\");\n\n"
] | [
1
] | [] | [] | [
"python",
"selenium",
"selenium_rc",
"window"
] | stackoverflow_0003962832_python_selenium_selenium_rc_window.txt |
Q:
Finding usb gps in cross platform python
I'm working on a python app that's reading from a gps usb dongle. This far everything has been running in ubuntu/debian based systems where I communicated with the gps in a rather blunt way of scanning all of /dev/ttyUSB0-9 with pySerial for something speaking NMEA sentence... | Finding usb gps in cross platform python | I'm working on a python app that's reading from a gps usb dongle. This far everything has been running in ubuntu/debian based systems where I communicated with the gps in a rather blunt way of scanning all of /dev/ttyUSB0-9 with pySerial for something speaking NMEA sentences on 38400 baud. Now I have been asked to get ... | [
"You could use the comports function from the scanwin32.py module provided in the pySerial documentation to figure out which COM ports are available, and then, using the returned informations about the open ports, find which one is your GPS dongle.\nEdit: The documentation also provides a scan.py module which conta... | [
2,
0
] | [] | [] | [
"cross_platform",
"gps",
"pyserial",
"python",
"usb"
] | stackoverflow_0004106065_cross_platform_gps_pyserial_python_usb.txt |
Q:
How would I use a South migration to load data into Django's auth_group table?
I have some new groups that I'd like to add to Django's "auth_group" table and I'd prefer to use South to "migrate" that data into the database. Unfortunately, I'm not sure what steps I should take to create the migration file and then ... | How would I use a South migration to load data into Django's auth_group table? | I have some new groups that I'd like to add to Django's "auth_group" table and I'd prefer to use South to "migrate" that data into the database. Unfortunately, I'm not sure what steps I should take to create the migration file and then have it load my fixture.
Any thoughts?
| [
"The South docs have a section about fixtures that includes this sample:\ndef forwards(self, orm):\n from django.core.management import call_command\n call_command(\"loaddata\", \"my_fixture.json\")\n\n"
] | [
8
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0004109186_django_django_south_python.txt |
Q:
simplejson not escaping single quote on app engine server
I'm trying to generate a properly formatted json object to use in javascript. I've tried simplejson.dumps(string), but it behaves differently on my local machine (in the python shell) vs. on the server (running google app engine). For example, locally i'll... | simplejson not escaping single quote on app engine server | I'm trying to generate a properly formatted json object to use in javascript. I've tried simplejson.dumps(string), but it behaves differently on my local machine (in the python shell) vs. on the server (running google app engine). For example, locally i'll get:
>>> s= {u'hello': u"Hi, i'm here"}
>>> simplejson.dumps(s... | [
"I think you are being confused by the repr behaviour vs the actual output.\n>>> s= {u'hello': u\"Hi, i'm here\"}\n>>> simplejson.dumps(s)\n'{\"hello\": \"Hi, i\\'m here\"}'\n>>> print simplejson.dumps(s)\n{\"hello\": \"Hi, i'm here\"}\n\nWhen you simply ask for the result of the simplejson call, the Python shell p... | [
2,
1
] | [] | [] | [
"javascript",
"python",
"simplejson"
] | stackoverflow_0004109047_javascript_python_simplejson.txt |
Q:
Why doesn't my GQL query return any results in my GAE App?
I have mostly followed a tutorial about how to build a gustbook using GAE and Python. Now I only want to show the entries from a particular day, but the GQL query doesn't return anything (although there are entries from that day):
class Shout(db.Model):
... | Why doesn't my GQL query return any results in my GAE App? | I have mostly followed a tutorial about how to build a gustbook using GAE and Python. Now I only want to show the entries from a particular day, but the GQL query doesn't return anything (although there are entries from that day):
class Shout(db.Model):
message= db.StringProperty(required=True)
when = db.Da... | [
"There might be another way around this, but I think that because your when property is a datetime you would be better served with something like this:\nshouts = db.GqlQuery(\"\"\"SELECT * \n FROM Shout \n WHERE when >= DATE('2010-11-05')\n ... | [
2,
1
] | [] | [] | [
"google_app_engine",
"gql",
"python"
] | stackoverflow_0004109272_google_app_engine_gql_python.txt |
Q:
Python/Tikinter: Can't use a button to update a graph?
Simplified question: For some reason the plot isn't updating when I hit my generate plots button.
global f
master = Tk()
plotFrame = Frame(master)
plotFrame.pack(side=TOP)
f = Figure()
canvas = FigureCanvasTkAgg(f, plotFrame)
canvas.get_tk_widget().pack()
... | Python/Tikinter: Can't use a button to update a graph? | Simplified question: For some reason the plot isn't updating when I hit my generate plots button.
global f
master = Tk()
plotFrame = Frame(master)
plotFrame.pack(side=TOP)
f = Figure()
canvas = FigureCanvasTkAgg(f, plotFrame)
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2TkAgg(canvas,master)
toolbar.pac... | [
"Add this line:\ndef grph():\n graph1 = f.add_subplot(111)\n graph1.plot([1,2,3])\n canvas.draw()\n\n"
] | [
1
] | [] | [] | [
"button",
"python",
"tkinter"
] | stackoverflow_0004106546_button_python_tkinter.txt |
Q:
Python dictionary isn't updating
def mergeDict(object):
dict1 = {}
for i in range(len(object)):
dict1.update({'id': object[i].id, 'name': object[i].name, 'age': object[i].age, 'location': object[i].location})
return dict1
merged_dict = mergeDict(details_sorted)
But this doesn't work.
I wan... | Python dictionary isn't updating | def mergeDict(object):
dict1 = {}
for i in range(len(object)):
dict1.update({'id': object[i].id, 'name': object[i].name, 'age': object[i].age, 'location': object[i].location})
return dict1
merged_dict = mergeDict(details_sorted)
But this doesn't work.
I want to get something like this:
{1: {'id... | [
"It looks like the return statement is in the for loop, which means it will only ever return the update of the first dict.\n",
"You don't want to update the dict; you just want to insert a value on key i. Also, the return goes after the for, not in it. Here is a modified version:\ndef mergeDict(object):\n dict... | [
5,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004109712_python.txt |
Q:
Where should I put configuration details? [Python]
I'm fairly new to Python and Django, and I'm working on a webapp now that will be run on multiple servers. Each server has it's own little configuration details (commands, file paths, etc.) that I would like to just be able to store in a settings file, and then h... | Where should I put configuration details? [Python] | I'm fairly new to Python and Django, and I'm working on a webapp now that will be run on multiple servers. Each server has it's own little configuration details (commands, file paths, etc.) that I would like to just be able to store in a settings file, and then have a different copy of the file on each system.
I know ... | [
"This page discusses yours and several other situations involving configurations on Django servers: http://code.djangoproject.com/wiki/SplitSettings\n",
"It's for any type of settings, but it's better to put local settings in a separate file so that version upgrades don't clobber them. Have the global settings fi... | [
2,
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004109532_django_python.txt |
Q:
Plugging values into ModelForm fields at __init__ time
I want to add first_name, last_name, and email fields to the UserProfile admin page. So you can change all the user's details from within the UserProfile admin instead of having to go to a different page to change email and some other fields.
This is what my c... | Plugging values into ModelForm fields at __init__ time | I want to add first_name, last_name, and email fields to the UserProfile admin page. So you can change all the user's details from within the UserProfile admin instead of having to go to a different page to change email and some other fields.
This is what my custom form looks like:
class CustomProfileForm(forms.ModelFo... | [
"To set the initial values in the init method you can use the fields dictionary.\ndef __init__(self, *a, **k):\n # < snip >\n self.fields[ 'email' ].initial = self.user_instance.email\n # ... and any others\n\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"django_forms",
"python"
] | stackoverflow_0004108822_django_django_admin_django_forms_python.txt |
Q:
pygtk FileChooserDialog slows down interpreter
I'm trying to use FileChooserDialog to get a native gnome dialog box in a python script. After the script executes, my ipython -pylab prompt experiences a significant slow down. This problem also exists from a plain python prompt. I've isolated the problem to the d... | pygtk FileChooserDialog slows down interpreter | I'm trying to use FileChooserDialog to get a native gnome dialog box in a python script. After the script executes, my ipython -pylab prompt experiences a significant slow down. This problem also exists from a plain python prompt. I've isolated the problem to the dialog box. The following example (which has been po... | [
"From running this in the IDLE, here's the steps I can see going on for me -\n\nThe script starts and the file chooser loads\nThe interpreter locks as it waits for FileChooserDialog.run()\nThe interpreter resumes when I click to remove it\n\nWhich is nothing what like you describe, so I can only assume it is some ... | [
0
] | [] | [] | [
"ipython",
"pygtk",
"python"
] | stackoverflow_0004020745_ipython_pygtk_python.txt |
Q:
What features does Django have that Pylons doesn't?
From what I understand, Pylons is more of a 'bare bones' framework (where you can choose your ORM and template engine), and Django is a little more rich in nature.
What exactly are the features/frameworky elements that Django has that Pylons doesn't?
(other than ... | What features does Django have that Pylons doesn't? | From what I understand, Pylons is more of a 'bare bones' framework (where you can choose your ORM and template engine), and Django is a little more rich in nature.
What exactly are the features/frameworky elements that Django has that Pylons doesn't?
(other than its own ORM, and its auto-admin page generation)
| [
"This question overlaps heavily with \"Pros/Cons of Django vs Pylons,\" and I think that part of the answer you're looking for is in Ben Bangeret's answer to that question. Pylons addresses a larger problem domain than Django does, so there are web apps that are so nontrivial to build in Django that you might as w... | [
3,
1,
1
] | [] | [] | [
"django",
"pylons",
"python"
] | stackoverflow_0003718695_django_pylons_python.txt |
Q:
Design of a python pickleable object that describes a file
I would like to create a class that describes a file resource and then pickle it. This part is straightforward. To be concrete, let's say that I have a class "A" that has methods to operate on a file. I can pickle this object if it does not contain a fi... | Design of a python pickleable object that describes a file | I would like to create a class that describes a file resource and then pickle it. This part is straightforward. To be concrete, let's say that I have a class "A" that has methods to operate on a file. I can pickle this object if it does not contain a file handle. I want to be able to create a file handle in order t... | [
"The question isn't too clear; what it looks like is that:\n\nyou have a third-party module which has picklable classes\nthose classes may contain references to files, which makes the classes themselves not picklable because open files aren't picklable.\n\nEssentially, you want to make open files picklable. You ca... | [
6,
1,
1
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0004109848_pickle_python.txt |
Q:
Build Boost and Exempi on a Mac
In order to install Python XMP Toolkit,
I
need to install Exempi on my Mac, but doing this is becoming a real nightmare...
After a lot of trouble, i finally made it with boost, and had the fantastic
The Boost C++ Libraries were successfully built!
The following directo... | Build Boost and Exempi on a Mac | In order to install Python XMP Toolkit,
I
need to install Exempi on my Mac, but doing this is becoming a real nightmare...
After a lot of trouble, i finally made it with boost, and had the fantastic
The Boost C++ Libraries were successfully built!
The following directory should be added to compiler includ... | [
"I'm assuming that you installed Boost manually, given that it's in /usr/local. I was able to install both Boost and Exempi through MacPorts.\n",
"Looks like you didn't build the boost test library when you built boost. You need to add --with-test to your bjam invokation:\n./bjam --with-test\n"
] | [
1,
0
] | [] | [] | [
"boost",
"boost_python",
"macos",
"python"
] | stackoverflow_0004019243_boost_boost_python_macos_python.txt |
Q:
Can I improve on the current Python code?
I am just starting out with Python and decided to try this little project from Python Wiki:
Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have been denied access. and termina... | Can I improve on the current Python code? | I am just starting out with Python and decided to try this little project from Python Wiki:
Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have been denied access. and terminate the program. If the password is correct, pri... | [
"You can replace your while loop with the following function:\ndef login():\n for i in range(3):\n password = raw_input('Please enter a password: ')\n if password != 'SecretPassword':\n print 'You have entered invalid password {0} times.'.format(i + 1)\n else:\n print '... | [
7,
3,
2,
0
] | [] | [] | [
"conditional",
"loops",
"python"
] | stackoverflow_0004110477_conditional_loops_python.txt |
Q:
Using pipes to redirect a function-generated SQL query to the psql command
I have a script that generates an SQL query as text e.g.
...
return "SELECT COUNT(*) FROM important_table"
which I would then like to run on a PostgreSQL database. I can do this in two lines like this:
python SQLgeneratingScript.py param... | Using pipes to redirect a function-generated SQL query to the psql command | I have a script that generates an SQL query as text e.g.
...
return "SELECT COUNT(*) FROM important_table"
which I would then like to run on a PostgreSQL database. I can do this in two lines like this:
python SQLgeneratingScript.py parameters > temp.sql
psql -f temp.sql -d my_database
But seems like I should be a... | [
"python SQLgeneratingScript.py parameters|psql -d my_database\n\n",
"i don't know why you are not using a python postgresql connector like psycopg2 ,but well if you want to do what you are trying to do using Unix command redirection you will have to do it like this in your code\n...\nprint \"SELECT COUNT(*) FROM ... | [
2,
0
] | [] | [] | [
"pipe",
"postgresql",
"python",
"sql"
] | stackoverflow_0004110511_pipe_postgresql_python_sql.txt |
Q:
Generic iterator over the values (instead of over the keys) of any iterable
Is there a generic way of getting an iterator that always iterates over the values (preferably, although it may work iterating the keys too) of either dictionaries or other iterables (lists, sets...)?
Let me elaborate: When you execute "it... | Generic iterator over the values (instead of over the keys) of any iterable | Is there a generic way of getting an iterator that always iterates over the values (preferably, although it may work iterating the keys too) of either dictionaries or other iterables (lists, sets...)?
Let me elaborate: When you execute "iter(list)" you get an iterator over the values (not the indexes, which sound prett... | [
"I don't know of anything built in that does this. I suppose you could do something like:\ndef itervalues(x):\n if hasattr(x, 'itervalues'): return x.itervalues()\n if hasattr(x, 'values'): return iter(x.values())\n return iter(x)\n\n",
"Most collections have no concept or \"keys\" or \"values\". They just sto... | [
3,
3,
0
] | [] | [] | [
"coding_style",
"iterator",
"python"
] | stackoverflow_0004110544_coding_style_iterator_python.txt |
Q:
Redirect print in Python: val = print(arg) to output mixed iterable to file
So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?
val = print(arg)
gets a SyntaxError.
Is there a way to access... | Redirect print in Python: val = print(arg) to output mixed iterable to file | So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?
val = print(arg)
gets a SyntaxError.
Is there a way to access stdinput?
And why does print take forever with massive strings? Bad programming... | [
"You could look into the logging module of Python. Perhaps that's the perfect match in this case.\n",
"Seeing how you're using print as function, docs say that you can redirect to file like this:\nprint(arg, file=open('fname', 'w'))\n\n",
"In Python 3.*, to redirect one print call to an open file object destina... | [
2,
1,
1,
1,
0
] | [] | [] | [
"dictionary",
"iterable",
"list",
"python"
] | stackoverflow_0002476931_dictionary_iterable_list_python.txt |
Q:
Python regex: string does not contain "jpg" and must have "-" and lowercase
I'm having troubles figuring out a python regex for django urls. I have a certain criteria, but can't seem to come up with the magic formula. In the end its so I can identify which page is a CMS page and pass to the django function the ali... | Python regex: string does not contain "jpg" and must have "-" and lowercase | I'm having troubles figuring out a python regex for django urls. I have a certain criteria, but can't seem to come up with the magic formula. In the end its so I can identify which page is a CMS page and pass to the django function the alias url it should load.
Here are some examples of valid strings which would match:... | [
"I'm puzzled as to why several of the commentators find that this is hard to do in a regex. This is exactly what regular expressions are good at.\nif re.match(\n r\"\"\"^ # match start of the string\n (?=.*-) # assert that there is a dash\n (?!.*\\.(?:jpg|gif|png|css|js)) # assert th... | [
9,
0
] | [] | [] | [
"django",
"django_urls",
"python",
"regex"
] | stackoverflow_0004109088_django_django_urls_python_regex.txt |
Q:
Using RPC over email?
Can someone tell me how they have done this in some form, be it XML-RPC, SOAP, bespoke etc. Not too worried on the packet format.
I am interested in doing some sort of RPC over email, setting up a program to receive commands via email from another application(s) or even from users on a subscr... | Using RPC over email? | Can someone tell me how they have done this in some form, be it XML-RPC, SOAP, bespoke etc. Not too worried on the packet format.
I am interested in doing some sort of RPC over email, setting up a program to receive commands via email from another application(s) or even from users on a subscription list. Basically the ... | [
"You could use fetchmail like this:\n#!/bin/bash\nwhile sleep 1\ndo\n fetchmail --idle --mda python program_that_accepts_email_with_headers_on_stdin.py\ndone\n\nThen Your program can do various things from querying database, through using some http services, to sending an email to someone. The way it works is fi... | [
2,
2
] | [] | [] | [
"asynchronous",
"email",
"python",
"web_services"
] | stackoverflow_0004066513_asynchronous_email_python_web_services.txt |
Q:
how to use python xml.etree.ElementTree to parse eBay API response?
I am trying to use xml.etree.ElementTree to parse responses from eBay finding API, findItemsByProduct. After lengthy trial and error, I came up with this code which prints some data:
import urllib
from xml.etree import ElementTree as ET
appID = '... | how to use python xml.etree.ElementTree to parse eBay API response? | I am trying to use xml.etree.ElementTree to parse responses from eBay finding API, findItemsByProduct. After lengthy trial and error, I came up with this code which prints some data:
import urllib
from xml.etree import ElementTree as ET
appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
isbn = '3868731342'
namespace = '{... | [
"You can use ElementTree. If you want to get the items you can use findall and the path to the items, then iterate over the list of items:\nitems = root.findall(namespace+'searchResult/'+namespace+'item')\nfor item in items: \n item.find(namespace+'itemId').text\n item.find(namespace+'title').text\n\nTo get... | [
4
] | [] | [] | [
"ebay_api",
"python",
"xml",
"xmlhttprequest"
] | stackoverflow_0004110440_ebay_api_python_xml_xmlhttprequest.txt |
Q:
Parse a datetime string from amazon mechanical turk to django orm
Mechanical turk provides strings like this:
'Wed Nov 03 17:14:17 PDT 2010'
Django datetime model fields require
YYYY-MM-DD HH:MM[:ss[.uuuuuu]]
What's the right way to take in the 1st string and create the 2nd?
A:
t = time.strptime("Wed No... | Parse a datetime string from amazon mechanical turk to django orm | Mechanical turk provides strings like this:
'Wed Nov 03 17:14:17 PDT 2010'
Django datetime model fields require
YYYY-MM-DD HH:MM[:ss[.uuuuuu]]
What's the right way to take in the 1st string and create the 2nd?
| [
"t = time.strptime(\"Wed Nov 03 17:14:17 PDT 2010\", \"%a %b %d %H:%M:%S %Z %Y\") \ntime.strftime(\"%Y-%m-%d %H:%M:%S\", t)\n\n",
"Sounds like a job for time.strptime() and time.strftime() !\n"
] | [
3,
0
] | [] | [] | [
"datetime",
"django_models",
"mechanicalturk",
"python"
] | stackoverflow_0004110725_datetime_django_models_mechanicalturk_python.txt |
Q:
How do I use Python 3.1.2 in Textmate?
TextMate 1.5.9 seems to use Python 2.6.1. How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I want to use TextMate now. I've already seen the post that directs you to define a project variable (... | How do I use Python 3.1.2 in Textmate? | TextMate 1.5.9 seems to use Python 2.6.1. How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I want to use TextMate now. I've already seen the post that directs you to define a project variable (TM_PYTHON : interpreter path). I tried this,... | [
"I assume you are referring to this post. It should work but make sure you are using the right path to the Python 3.1 you installed. Check with:\n$ which python3\n/usr/local/bin/python3\n\nIf you used the python.org 3.1 installer, it should be available at /usr/local/bin/python3. Other methods may vary, for inst... | [
1,
1
] | [] | [] | [
"python",
"textmate"
] | stackoverflow_0003581802_python_textmate.txt |
Q:
Enable python support while installing opencv using mac ports
I installed opencv in my mac using mac ports by the following command
sudo port install opencv
It took around 2 hours and it installed properly. But the problem is that the python bindings are not enabled.
So please let me know how to install opencv in ... | Enable python support while installing opencv using mac ports | I installed opencv in my mac using mac ports by the following command
sudo port install opencv
It took around 2 hours and it installed properly. But the problem is that the python bindings are not enabled.
So please let me know how to install opencv in mac using ports and also enable the python bindings. Thanks
PS: I t... | [
"be sure to have py26-numpy installed to have support for basic functions such as cv.fromarray :\nsudo port install py26-numpy\n\nopencv will compile silently without numpy (it's not strictly a dependency).\nsudo port install -v opencv +python26\n\nthere you can check that the binding to numpy is effective.\n",
"... | [
2,
0,
0
] | [] | [] | [
"macos",
"macports",
"opencv",
"python"
] | stackoverflow_0003184128_macos_macports_opencv_python.txt |
Q:
Flex Regular Expression Conversion Help
I'm having a problem converting a regular expression from Python into Flex. My string is something like this:
SELECT "col", othercol,\n "othercol3" FROM doesn'tmatter...
Python matches just fine:
>>> re.search('select(.*?)from', 'SELECT "col", othercol,\n "othercol3" FROM d... | Flex Regular Expression Conversion Help | I'm having a problem converting a regular expression from Python into Flex. My string is something like this:
SELECT "col", othercol,\n "othercol3" FROM doesn'tmatter...
Python matches just fine:
>>> re.search('select(.*?)from', 'SELECT "col", othercol,\n "othercol3" FROM doesn\'tmatter...', re.DOTALL|re.IGNORECASE).g... | [
"Try one of the many Flex regular expression testers out there:\nhttp://www.idsklijnsma.nl/regexps/\nFor one thing, you're using dotall, etc., so you might want to know that Flex use the \"s\" flag for that. And the \"x\" flag ignores whitespace, etc. For example,\npattern:RegExp = /select.+?from/gis;\nworks for me... | [
0
] | [] | [] | [
"apache_flex",
"python",
"regex"
] | stackoverflow_0004111096_apache_flex_python_regex.txt |
Q:
Python how to iterate through a list and compare lists of strings found within
If I have a nested list that looks like this:
bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]
How do I iterate through this list and extract a list of names that appear... | Python how to iterate through a list and compare lists of strings found within | If I have a nested list that looks like this:
bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]
How do I iterate through this list and extract a list of names that appear in all the nested lists? i.e.:
finallist = ['sam', 'angie']
Would this be better a... | [
"reduce(set.intersection, map(set , bigstringlist))\n\n",
"A variation on singularity's solution, maybe a little faster:\nbigstringiter = iter(bigstringlist)\nreduce(set.intersection, bigstringiter, set(next(bigstringiter)))\n\n"
] | [
11,
0
] | [] | [] | [
"iteration",
"nested_lists",
"python"
] | stackoverflow_0004111129_iteration_nested_lists_python.txt |
Q:
Python Eclipse type casting intellisense work-around
Say I have the following two classes.
class TopClass:
def __init__(self):
self.items = []
class ItemClass:
def __init__(self):
self.name = None
And I want to use that in the following way:
def do_something():
myTop = TopClass()
#... | Python Eclipse type casting intellisense work-around | Say I have the following two classes.
class TopClass:
def __init__(self):
self.items = []
class ItemClass:
def __init__(self):
self.name = None
And I want to use that in the following way:
def do_something():
myTop = TopClass()
# create two items
item1 = ItemClass()
item1.name =... | [
"\nI could have misspelled something and not found out until I actually ran the script.\n\nShort-sighted and false.\nYou could have misspelled something and never found out until you endured a lawsuit because you did no unit testing.\n\"actually ran the script\" is not the time when you learn if you did it right.\n... | [
1,
1,
0
] | [] | [] | [
"eclipse",
"instance_variables",
"intellisense",
"python"
] | stackoverflow_0004110975_eclipse_instance_variables_intellisense_python.txt |
Q:
c system() return from python script - confusing!
I need to call through to a python script from C and be able to catch return values from it. it doesn't particularly matter what the values are, they may as well be an enum, but the values I got out of a test case confused me, and I wanted to get to the bottom of w... | c system() return from python script - confusing! | I need to call through to a python script from C and be able to catch return values from it. it doesn't particularly matter what the values are, they may as well be an enum, but the values I got out of a test case confused me, and I wanted to get to the bottom of what I was seeing.
So, here is the C:
#include <stdlib.h... | [
"From the Linux documentation on system():\n\n... return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status) ...\n\nFrom following the link on wait, we get the following:\n\nWEXITSTATUS(status): returns the exit status of the child. ... This macro should only... | [
2,
1
] | [] | [] | [
"c",
"python",
"return_value"
] | stackoverflow_0004111279_c_python_return_value.txt |
Q:
Python/Tkinter: Building a toolbar that provides edit cut, copy, paste commands
I'm looking for suggestions on how one might implement a toolbar that provides edit cut, copy, paste commands using the Tkinter framework. I understand how to build a toolbar and bind the toolbar commands, but I'm confused over how the... | Python/Tkinter: Building a toolbar that provides edit cut, copy, paste commands | I'm looking for suggestions on how one might implement a toolbar that provides edit cut, copy, paste commands using the Tkinter framework. I understand how to build a toolbar and bind the toolbar commands, but I'm confused over how the toolbar button bound commands will know which widget to apply the cut, copy, or past... | [
"You don't have to maintain a big framework, you can create a single binding on the root widget for <FocusIn> and put all the logic in that binding. Or, use focus_class and bind to the class all. \nBinding on the root will only affect children of the root, binding to all will affect all widgets in the entire app. ... | [
2,
1
] | [] | [] | [
"clipboard",
"python",
"tkinter",
"toolbar"
] | stackoverflow_0004111049_clipboard_python_tkinter_toolbar.txt |
Q:
How to explore a package in python
import pkg
dir(pkg)
such a statement in python won't show all the classes / functions / subpackages in the package pkg because some of them might be loaded just in time.So what is the best way to explore a package in python?
A:
Have you try pydoc
pydoc package
Is the same a... | How to explore a package in python | import pkg
dir(pkg)
such a statement in python won't show all the classes / functions / subpackages in the package pkg because some of them might be loaded just in time.So what is the best way to explore a package in python?
| [
"Have you try pydoc\n\npydoc package\n\nIs the same as calling the help function but you can do it from the command line,\nand of course you can browse to a module, class or function level with the dot notation.\n",
"You can use help(pkg), or obviously doc if it's available.\n",
"Read the source, read the modu... | [
4,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004110849_python.txt |
Q:
Python Struct, size changed by alignment.
Here's the hex code I am trying to unpack.
b'ABCDFGHa\x00a\x00a\x00a\x00a\x00\x00\x00\x00\x00\x00\x01' (it's not supposed to make any sense)
labels = unpack('BBBBBBBHHHHH5sB', msg)
struct.error: unpack requires a bytes argument of length 24
From what I counted, both of th... | Python Struct, size changed by alignment. | Here's the hex code I am trying to unpack.
b'ABCDFGHa\x00a\x00a\x00a\x00a\x00\x00\x00\x00\x00\x00\x01' (it's not supposed to make any sense)
labels = unpack('BBBBBBBHHHHH5sB', msg)
struct.error: unpack requires a bytes argument of length 24
From what I counted, both of those are length = 23, both the format in my unpa... | [
"Most processors access data faster when the data is on natural boundaries, meaning data of size 2 should be on even addresses, data of size 4 should be accessed on addresses divisible by four, etc.\nstruct by default maintains this alignment. Since your structure starts out with 7 'B', a padding byte is added to ... | [
5,
3
] | [] | [] | [
"python",
"struct"
] | stackoverflow_0004110378_python_struct.txt |
Q:
Python: conditionally delete elements from list
Suppose I have a list of tuples:
x = [(1,2), (3,4), (7,4), (5,4)]
Of all tuples that share the second element, I want to preserve the tuple with the largest first element:
y = [(1,2), (7,4)]
What is the best way to achieve this in Python?
Thanks for the answers.
... | Python: conditionally delete elements from list | Suppose I have a list of tuples:
x = [(1,2), (3,4), (7,4), (5,4)]
Of all tuples that share the second element, I want to preserve the tuple with the largest first element:
y = [(1,2), (7,4)]
What is the best way to achieve this in Python?
Thanks for the answers.
The tuples could be two-element lists instead, if tha... | [
"use collections.defaultdict\nimport collections\n\nmax_elements = collections.defaultdict(tuple)\n\nfor item in x:\n if item > max_elements[item[1]]:\n max_elements[item[1]] = item\n\ny = max_elements.values()\n\n",
"Similar to Aaron's answer\n>>> from collections import defaultdict\n>>> x = [(1,2), (3... | [
5,
5,
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004111207_list_python.txt |
Q:
Having some kind of XML/Json file to compile into Graphiz / Finite State Automaton. Any suggestions?
I have a task where I need to take some existing pictures[ which show some automata (DFA, NFA, Turing machines)] and somehow convert them into a format, which enables me to use the data to represent it as an automa... | Having some kind of XML/Json file to compile into Graphiz / Finite State Automaton. Any suggestions? | I have a task where I need to take some existing pictures[ which show some automata (DFA, NFA, Turing machines)] and somehow convert them into a format, which enables me to use the data to represent it as an automata as well as compile it into some graphical representation. Has any of you done something similar before?... | [
"Graphviz can provide a solution. The data representation for a Directed Acyclic Graph (DAG) is direct and simple from the picture. It can readily be \"read\" off the diagram if you are doing it by hand as your comment suggests. The representation of a complex diagram (several distinct panels each containing an ind... | [
1
] | [] | [] | [
"automata",
"depth_first_search",
"python",
"turing_machines"
] | stackoverflow_0004077117_automata_depth_first_search_python_turing_machines.txt |
Q:
Sneaking unsigned values from Jython, through Java, to C and back again
I'm involved in a project where we're binding a C API into Jython (through Java). We've run into issues with unsigned values (since Java doesn't support them). We can use casting between Java and C, but moving from Jython to Java is a harder t... | Sneaking unsigned values from Jython, through Java, to C and back again | I'm involved in a project where we're binding a C API into Jython (through Java). We've run into issues with unsigned values (since Java doesn't support them). We can use casting between Java and C, but moving from Jython to Java is a harder task.
I wrote some 'casting' functions in Python. They convert a bit pattern r... | [
"The struct module is a natural fit for this\nimport struct\n\ndef u2s(v):\n return struct.unpack(\"i\", struct.pack(\"I\", v))[0]\n\ndef s2u(v):\n return struct.unpack(\"I\", struct.pack(\"i\", v))[0]\n\nTo support all the common widths\nimport struct\n\ndef u2s(v, width=32):\n fmt = {8: \"B\", 16: \"H\",... | [
4
] | [] | [] | [
"java",
"java_native_interface",
"jython",
"python"
] | stackoverflow_0004111595_java_java_native_interface_jython_python.txt |
Q:
Python Setuptools, easy_install setup mac
Okay, so I'm not sure at all what is going on here. I just got my MAC, and I am trying to download and install setuptools, so I can download different python packages (using easy_install). So, following the instructions here (http://pypi.python.org/pypi/setuptools):
I c... | Python Setuptools, easy_install setup mac | Okay, so I'm not sure at all what is going on here. I just got my MAC, and I am trying to download and install setuptools, so I can download different python packages (using easy_install). So, following the instructions here (http://pypi.python.org/pypi/setuptools):
I currently have version 2.6
I downloaded the foll... | [
"edit Try this from a command line\nHere is an easier thing to do that might work better for you. Open a terminal (Applications->Utilities->Terminal) and run this as a shell script. You can also run the individual commands.\n#!/bin/sh\n\ncd ~\n\n# Downloads python setuptools for 2.6\ncurl -o setuptools-0.6c11-py2.6... | [
6,
1
] | [] | [] | [
"python"
] | stackoverflow_0004111737_python.txt |
Q:
Convert datetime fields in Chrome history file (sqlite) to readable format
Working on a script to collect users browser history with time stamps ( educational setting).
Firefox 3 history is kept in a sqlite file, and stamps are in UNIX epoch time... getting them and converting to readable format via a SQL command ... | Convert datetime fields in Chrome history file (sqlite) to readable format | Working on a script to collect users browser history with time stamps ( educational setting).
Firefox 3 history is kept in a sqlite file, and stamps are in UNIX epoch time... getting them and converting to readable format via a SQL command in python is pretty straightforward:
sql_select = """ SELECT datetime(moz_histor... | [
"Try this:\nsql_select = \"\"\" SELECT datetime(last_visit_time/1000000-11644473600,'unixepoch','localtime'),\n url \n FROM urls\n ORDER BY last_visit_time DESC\n \"\"\"\nget_hist = list(cursor.execute (sql_select))\n\nOr something along those lines... | [
16,
4,
1,
1
] | [] | [] | [
"datetime",
"python",
"sqlite"
] | stackoverflow_0002141537_datetime_python_sqlite.txt |
Q:
What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python?
In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'
I need to add a new value onto the end and remove the first value,
e.g.
'5,22,7,814,3,4' -> '22,7,814,3,4,1'
Cur... | What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python? | In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'
I need to add a new value onto the end and remove the first value,
e.g.
'5,22,7,814,3,4' -> '22,7,814,3,4,1'
Currently, I do this as follows:
mystr = '5,22,7,814,3,4'
latestValue='1'
mylist = mystr.split(',')
mystr = ''
for i in ... | [
"Use this:\nif mystr == '':\n mystr = latestValue\nelse:\n mystr = mystr[mystr.find(\",\")+1:] + \",\" + latestValue\n\nThis should be much faster than any solution which splits the list. It only finds the first occurrence of , and \"removes\" the beginning of the string. Also, if the list is empty, then myst... | [
9,
6,
6,
4,
2,
2
] | [] | [] | [
"algorithm",
"concatenation",
"python"
] | stackoverflow_0004111711_algorithm_concatenation_python.txt |
Q:
How to zip lists in a list
I want to zip the following list of lists:
>>> zip([[1,2], [3,4], [5,6]])
[[1,3,5], [2,4,6]]
This could be achieved with the current zip implementation only if the list is split into individual components:
>>> zip([1,2], [3,4], [5,6])
(1, 3, 5), (2, 4, 6)]
Can't figure out how to sp... | How to zip lists in a list | I want to zip the following list of lists:
>>> zip([[1,2], [3,4], [5,6]])
[[1,3,5], [2,4,6]]
This could be achieved with the current zip implementation only if the list is split into individual components:
>>> zip([1,2], [3,4], [5,6])
(1, 3, 5), (2, 4, 6)]
Can't figure out how to split the list and pass the indivi... | [
"Try this:\n>>> zip(*[[1,2], [3,4], [5,6]])\n[(1, 3, 5), (2, 4, 6)]\n\nSee Unpacking Argument Lists:\n\nThe reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expe... | [
176
] | [] | [] | [
"functional_programming",
"python"
] | stackoverflow_0004112265_functional_programming_python.txt |
Q:
How to find the max object as per some custom criterion?
I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function, something like:
currmax = 0
def mymax(s):
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax el... | How to find the max object as per some custom criterion? | I can do max(s) to find the max of a sequence. But suppose I want to compute max according to my own function, something like:
currmax = 0
def mymax(s):
for i in s :
#assume arity() attribute is present
currmax = i.arity() if i.arity() > currmax else currmax
Is there a clean pythonic way of doing this?
| [
"max(s, key=operator.methodcaller('arity'))\n\nor\nmax(s, key=lambda x: x.arity())\n\n",
"For instance,\nmax (i.arity() for i in s)\n\n",
"You can still use the max function:\nmax_arity = max(s, key=lambda i: i.arity())\n\n",
"I think the generator expression of doublep is better, but we seldom get to use met... | [
40,
12,
9,
2
] | [] | [] | [
"python"
] | stackoverflow_0002931985_python.txt |
Q:
Strange urllib2.urlopen() behavior on Ubuntu 10.10
I am experiencing strange behavior with urllib2.urlopen() on Ubuntu 10.10. The first request to a url goes fast but the second takes a long time to connect. I think between 5 and 10 seconds. On windows this just works normal?
Does anybody have an idea what could c... | Strange urllib2.urlopen() behavior on Ubuntu 10.10 | I am experiencing strange behavior with urllib2.urlopen() on Ubuntu 10.10. The first request to a url goes fast but the second takes a long time to connect. I think between 5 and 10 seconds. On windows this just works normal?
Does anybody have an idea what could cause this issue?
Thanks, Onno
| [
"5 seconds sounds suspiciously like the DNS resolving timeout. \nA hunch, It's possible that it's cycling through the DNS servers in your /etc/resolv.conf and if one of them is broken, the default timeout is 5 seconds on linux, after which it will try the next one, looping back to the top when it's tried them all.\... | [
3,
1
] | [] | [] | [
"python",
"ubuntu",
"ubuntu_10.10",
"urllib2"
] | stackoverflow_0004110992_python_ubuntu_ubuntu_10.10_urllib2.txt |
Q:
Cannot resolve Django "NoReverseMatch" exception with kwargs
I have am unable to get Django to reverse-resolve the following named url -
URLconf entry :
url(r'^shotmanager/(?P<shotid>\d+)/$', 'ctac.views.shotManager', {'message': "", 'errors': []}, name = 'shot-manager')
HttpResponseRedirect call:
return HttpResp... | Cannot resolve Django "NoReverseMatch" exception with kwargs | I have am unable to get Django to reverse-resolve the following named url -
URLconf entry :
url(r'^shotmanager/(?P<shotid>\d+)/$', 'ctac.views.shotManager', {'message': "", 'errors': []}, name = 'shot-manager')
HttpResponseRedirect call:
return HttpResponseRedirect(reverse("shot-manager", kwargs={'shotid': id, 'messag... | [
"reverse returns a URL populated with the values you pass in the args or kwargs. But the URL you are trying to generate hasn't got a space for message. Where would it go in the generated URL?\nEdit in response to comment\nIf you want to pass messages between page views, the correct way to do it is not via the URL, ... | [
4
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0004111403_django_django_views_python.txt |
Q:
"compiler" module py3k
I am trying to port a codebase which uses the "compiler" module from 2.x over to 3.1 ; I get an ImportError at
import compiler
as the module does not exist in Python3.x ; Has the same functionality been integrated into another module within the standard library?
Or has it been completely ... | "compiler" module py3k | I am trying to port a codebase which uses the "compiler" module from 2.x over to 3.1 ; I get an ImportError at
import compiler
as the module does not exist in Python3.x ; Has the same functionality been integrated into another module within the standard library?
Or has it been completely removed?
[EDIT]
I require an... | [
"According to the docs, the module has been deprecated since 2.6 and been completely removed in 3.0.\nFrom PEP 3108:\n\nHaving to maintain both the built-in compiler and the stdlib package is redundant (24).\nThe AST created by the compiler is available (23).\nMechanism to compile from an AST needs to be added.\n\n... | [
7,
5
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004112458_python_python_3.x.txt |
Q:
Python memory problem
i started programming on python but i have a memory problem (sorry for my bad english).
I made a while loop on my algorithm, but on every cicle, the program consummes a lot of memory. I have 3Gb of RAM an AMD 64 x2 processor, and Windows 7 64 bits.
For every cicle, it consummes about 800 Mb o... | Python memory problem | i started programming on python but i have a memory problem (sorry for my bad english).
I made a while loop on my algorithm, but on every cicle, the program consummes a lot of memory. I have 3Gb of RAM an AMD 64 x2 processor, and Windows 7 64 bits.
For every cicle, it consummes about 800 Mb of RAM, it's too much i thin... | [
"It's a little tricky to follow the code without context, seeing as you've apparently used numpy in multiple places (both as np and without prefix), and evalf might be from sympy.. but we don't see your imports.\nAt a very vague guess, some of your list comprehensions build temporary lists that stick around longer ... | [
1,
0,
0
] | [] | [] | [
"memory",
"python"
] | stackoverflow_0004110423_memory_python.txt |
Q:
class definition inside a class?
class ItemForm(djangoforms.ModelForm):
class Meta:
model = Item
exclude = ['added_by']
i can not understand what this piece of code is doing .i understood that ItemForm is inheriting Modelform but then a class definition inside a class ??
The Item class is : ... | class definition inside a class? | class ItemForm(djangoforms.ModelForm):
class Meta:
model = Item
exclude = ['added_by']
i can not understand what this piece of code is doing .i understood that ItemForm is inheriting Modelform but then a class definition inside a class ??
The Item class is :
class Item(db.Model):
name = db.S... | [
"It's part of Django's magic. The metaclass for ModelForm (among other classes) looks for an inner Meta class and uses it to make various changes to the outer class. It's one of the deeper parts of Python that most people will never have to deal with first-hand.\n",
"In Python you can define classes within other ... | [
3,
1,
0
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0004112524_django_forms_python.txt |
Q:
I change python code, but python doesn't seem to read the changes
So, I've been programming in python and I've run into this really annoying issue. I wrote a small matrix library and started using it in another module (eg, import matrixlib). I'd find a bug, fix it and run the program again. Bug still there.
I... | I change python code, but python doesn't seem to read the changes | So, I've been programming in python and I've run into this really annoying issue. I wrote a small matrix library and started using it in another module (eg, import matrixlib). I'd find a bug, fix it and run the program again. Bug still there.
I'd throw in a few print statements to see what's going on, but they wou... | [
"i think that when you have installed your package the first time you did:\npython setup.py install\n\nrather than:\npython setup.py develop\n\nbecause when you do setup.py install the setup.py just copy the package files in the system path so every time you do a change in the package file you have to rerun setup.p... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0004110733_python.txt |
Q:
How do I derive from hashlib.sha256 in Python?
A naive attempt fails miserably:
import hashlib
class fred(hashlib.sha256):
pass
-> TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Well, it turns out that hashlib.sha256 is a callable, not a class. ... | How do I derive from hashlib.sha256 in Python? | A naive attempt fails miserably:
import hashlib
class fred(hashlib.sha256):
pass
-> TypeError: Error when calling the metaclass bases
cannot create 'builtin_function_or_method' instances
Well, it turns out that hashlib.sha256 is a callable, not a class. Trying something a bit more creative doesn't work e... | [
"Make a new class, derive from object, create a hashlib.sha256 member var in init, then define methods expected of a hash class and proxy to the same methods of the member variable.\nSomething like:\nimport hashlib\n\nclass MyThing(object):\n def __init__(self):\n self._hasher = hashlib.sha256()\n\n de... | [
7,
6,
2,
0
] | [] | [] | [
"cryptography",
"python",
"security"
] | stackoverflow_0004029632_cryptography_python_security.txt |
Q:
Boost.Python: Ownership of pointer variables
I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method
void add_child(Node *node)
The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets cal... | Boost.Python: Ownership of pointer variables | I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method
void add_child(Node *node)
The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets called.
I'm exposing the add_child method as:
.def("a... | [
"Answering my own question:\nI've missed an FAQ entry in the Boost.Python documentation that gave me the right hint:\n//The node class should be held by std::auto_ptr\nclass_<Node, std::auto_ptr<Node> >(\"Node\")\n\nCreate a thin wrapper function for the add_child method:\nvoid node_add_child(Node& n, std::auto_ptr... | [
4
] | [] | [] | [
"boost",
"boost_python",
"c++",
"python"
] | stackoverflow_0004112561_boost_boost_python_c++_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.