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: osx python setup.py will not install xattr-0.6.1 application I'm new to svn and python, but I really want to use a more recent version of xattr that includes more useful features than the original that came with the OS. On OSX 10.5.6, I'm having trouble installing xattr-0.6.1. From the local machine in Terminal: $...
osx python setup.py will not install xattr-0.6.1 application
I'm new to svn and python, but I really want to use a more recent version of xattr that includes more useful features than the original that came with the OS. On OSX 10.5.6, I'm having trouble installing xattr-0.6.1. From the local machine in Terminal: $ svn co http://svn.red-bean.com/bob/xattr/releases/xattr-0.6.1/ T...
[ "It needs to compile a C file, so it needs gcc. Mac folks need to install XCode. Update As @jathanism mentions, you should have an XCode install DVD that came with your Mac (most likely version 3.2).\nFor example:\natlas% which gcc\n/usr/bin/gcc\natlas% gcc -v\nTarget: i686-apple-darwin10\n..\nThread model: posix\n...
[ 1 ]
[]
[]
[ "installation", "macos", "python", "svn" ]
stackoverflow_0005890085_installation_macos_python_svn.txt
Q: pyqt: how to remove elements from a QVBoxLayout? I want a multi-color selection widget. The way I'm doing it is having a "+" button, and an initially empty vbox. When + is pressed, it adds a QHBoxLayout to the vbox containing a "-" button and 3 spinboxes. When the "-" button is pressed I want that row to disappear...
pyqt: how to remove elements from a QVBoxLayout?
I want a multi-color selection widget. The way I'm doing it is having a "+" button, and an initially empty vbox. When + is pressed, it adds a QHBoxLayout to the vbox containing a "-" button and 3 spinboxes. When the "-" button is pressed I want that row to disappear and everything to go back to looking like it did befo...
[ "Try removing from parent widget, not the layout.\nQLayout is not a parent, the parent for widgets being laid out is actually layout's parent. For more info and a clearer explanation see documentation on Qt layouts.\nTo remove widget, set its parent to None like this:\nwidget = QWidget() \nlayout = QVBoxLayout()...
[ 12 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0005889705_pyqt_pyqt4_python_qt_qt4.txt
Q: Python: libxml2 xpath returns empty list I want to parse XML content with Python's libxml2 using xpath, i followed this example and that tutorial. The XML file is: <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://purl.org/atom/ns#" version="0.3"> <title>Gmail - Inbox for myemailaddress@gmail.com</title> ...
Python: libxml2 xpath returns empty list
I want to parse XML content with Python's libxml2 using xpath, i followed this example and that tutorial. The XML file is: <?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://purl.org/atom/ns#" version="0.3"> <title>Gmail - Inbox for myemailaddress@gmail.com</title> <tagline>New messages in your Gmail Inbox</tag...
[ "Your XPath is failing because you need to specify the purl namespace on the node:\nimport libxml2\ntree = libxml2.parseDoc(data)\nxp = tree.xpathNewContext()\nxp.xpathRegisterNs(\"purl\", \"http://purl.org/atom/ns#\")\nprint xp.xpathEval('//purl:fullcount')\n\nResult:\n[<xmlNode (fullcount) object at 0x7fbbeba9ef8...
[ 2, 0 ]
[]
[]
[ "libxml2", "list", "python", "xpath" ]
stackoverflow_0005890521_libxml2_list_python_xpath.txt
Q: Python NLTK code snippet to train a classifier (naive bayes) using feature frequency I was wondering if anyone could help me through a code snippet that demonstrates how to train Naive Bayes classifier using a feature frequency method as opposed to feature presence. I presume the below as shown in Chap 6 link text...
Python NLTK code snippet to train a classifier (naive bayes) using feature frequency
I was wondering if anyone could help me through a code snippet that demonstrates how to train Naive Bayes classifier using a feature frequency method as opposed to feature presence. I presume the below as shown in Chap 6 link text refers to creating a featureset using Feature Presence (FP) - def document_features(docum...
[ "In the link you sent it says this function is feature extractor that simply checks whether each of these words is present in a given document. \nHere is the whole code with numbers for each line:\n1 all_words = nltk.FreqDist(w.lower() for w in movie_reviews.words())\n2 word_features = all_words.keys()[:200...
[ 3, 3, 0 ]
[]
[]
[ "nlp", "nltk", "python", "stanford_nlp" ]
stackoverflow_0002162718_nlp_nltk_python_stanford_nlp.txt
Q: Python (mod-wsgi) hangs when importing from SymPy I can import sympy without a problem, but when I from sympy import linalg or import scipy.linalg, the request hangs out. I can't seem to find anything in the server logs about it either, and curl times out. Any ideas on what could be going wrong will be greatly app...
Python (mod-wsgi) hangs when importing from SymPy
I can import sympy without a problem, but when I from sympy import linalg or import scipy.linalg, the request hangs out. I can't seem to find anything in the server logs about it either, and curl times out. Any ideas on what could be going wrong will be greatly appreciated. If I comment out that single line, my program...
[ "Sounds like the module isn't installed in the PYTHONPATH and/or mod_wsgi is compiled against a different Python interpreter than the one you're using from the command-line. Double check!\n" ]
[ 1 ]
[]
[]
[ "import", "module", "python", "scipy", "timeout" ]
stackoverflow_0005890777_import_module_python_scipy_timeout.txt
Q: decorating recursive functions I have a decorator that I wrote that will time a given function. It seems to work well with any function, except for recursive functions. Decorator: def tictoc(repeats=3, loops=1): def t(func): from functools import partial, wraps import timeit @wraps(fun...
decorating recursive functions
I have a decorator that I wrote that will time a given function. It seems to work well with any function, except for recursive functions. Decorator: def tictoc(repeats=3, loops=1): def t(func): from functools import partial, wraps import timeit @wraps(func) def timer(*args, **kargs)...
[ "The function your decorator returns doesn't return anything. So although fib is supposed to return an integer, your wrapped fib returns None. It works a few times because a few recursive calls are made without checking the results of fib, but when it needs the result (when it has to add two of them together) you g...
[ 6, 0 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0005860289_decorator_python.txt
Q: BeautifulSoup and Searching By Class Possible Duplicate: Beautiful Soup cannot find a CSS class if the object has other classes, too I'm using BeautifulSoup to find tables in the HTML. The problem I am currently running into is the use of spaces in the class attribute. If my HTML reads <html><table class="wikita...
BeautifulSoup and Searching By Class
Possible Duplicate: Beautiful Soup cannot find a CSS class if the object has other classes, too I'm using BeautifulSoup to find tables in the HTML. The problem I am currently running into is the use of spaces in the class attribute. If my HTML reads <html><table class="wikitable sortable">blah</table></html>, I can'...
[ "The pattern match will also fail if wikitable appears after another CSS class, as in class=\"something wikitable other\", so if you want all tables whose class attribute contains the class wikitable, you need a pattern that accepts more possibilities:\nhtml = '''<html><table class=\"sortable wikitable other\">blah...
[ 24, 8 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0005890659_beautifulsoup_python.txt
Q: Trying to install the Pymouse module on Ubuntu and receiving an error message So, I created a Directory in Ubuntu called Pymouse and I put all the related Pymouse files from Github in there including setup.py. When I go to terminal I cd the directory and then once i have done that I type python setup.py install or...
Trying to install the Pymouse module on Ubuntu and receiving an error message
So, I created a Directory in Ubuntu called Pymouse and I put all the related Pymouse files from Github in there including setup.py. When I go to terminal I cd the directory and then once i have done that I type python setup.py install or python setup.py build and each time I enter that command I receive the following i...
[ "Go back to the PyMouse Github page, click on \"Downloads\", pick one of the options from the window that pops up, extract the archive to your hard drive, and try again.\n", "Well I think that easiest Ubuntu way to do it is just do (as root):\napt-get install python-pip\npip install pymouse\nYou may find pip tool...
[ 1, 1 ]
[]
[]
[ "build", "installation", "linux", "python", "ubuntu" ]
stackoverflow_0005890802_build_installation_linux_python_ubuntu.txt
Q: Change color of individual print line in Python 3.2? I'm working on a little text-based adventure in Python 3.2 as I learn it in order to practise and become more familiar with the language. Anyway, I want to make it so that when certain actions happen, the color of the print text changes. How do I do this. For ex...
Change color of individual print line in Python 3.2?
I'm working on a little text-based adventure in Python 3.2 as I learn it in order to practise and become more familiar with the language. Anyway, I want to make it so that when certain actions happen, the color of the print text changes. How do I do this. For example, the first text I want this to occur for is: if 'str...
[ "Colorama is a great fully cross platform module for printing to the terminal/command line in different colours.\nExample:\nimport colorama\nfrom colorama import Fore, Back, Style\n\ncolorama.init()\n\ntext = \"The quick brown fox jumps over the lazy dog\"\n\nprint(Fore.RED + text)\nprint(Back.GREEN + text + Style....
[ 32, 6 ]
[]
[]
[ "colors", "printing", "python" ]
stackoverflow_0005890437_colors_printing_python.txt
Q: NoSQL abstraction layer for Python Does anybody know of an abstraction layer for nosql databases for Python similar to SQL Alchemy for SQL? This would allow redis, mongodb, etc... to be pluggable backends without having to write for each one specifically. A: This would allow redis, mongodb, etc... to be pluggab...
NoSQL abstraction layer for Python
Does anybody know of an abstraction layer for nosql databases for Python similar to SQL Alchemy for SQL? This would allow redis, mongodb, etc... to be pluggable backends without having to write for each one specifically.
[ "\nThis would allow redis, mongodb, etc... to be pluggable backends without having to write for each one specifically.\n\nThere is django-nonrel, but that library seems to be converting SQL actions into the various library actions.\nThe major problem here is that these things are not really the same at all. In part...
[ 9, 2 ]
[]
[]
[ "mongodb", "nosql", "python", "redis" ]
stackoverflow_0005884747_mongodb_nosql_python_redis.txt
Q: Remove lines from files I have a lot of files which have comments beginning with ! and I need to remove all of those, then replace the #Mhz with # Mhz on the next line and keep the file name same. What is an efficient way of doing this? I can read the file and write to a new file in a different directory and manua...
Remove lines from files
I have a lot of files which have comments beginning with ! and I need to remove all of those, then replace the #Mhz with # Mhz on the next line and keep the file name same. What is an efficient way of doing this? I can read the file and write to a new file in a different directory and manually delete them later i guess...
[ "Here's a stupidly simple way:\nfor line in in_file:\n if line[0] == '!':\n continue\n if line.startswith('#Mhz'):\n line = '# MHz' + line[4:] # Assuming it's megahertz, it's spelled MHz.\n out_file.write(line)\n\nYou can read the whole input file and split it into lines then open the file fo...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005886661_python.txt
Q: django saving database works, but returns 500 error? I am straight up confused. I will admit to being a newb, but this should work. See code below. As written the .save() line is commented out. When i run this, everythings works fine and as expected, data not saved and 'g' is returned. If i uncomment the .save() l...
django saving database works, but returns 500 error?
I am straight up confused. I will admit to being a newb, but this should work. See code below. As written the .save() line is commented out. When i run this, everythings works fine and as expected, data not saved and 'g' is returned. If i uncomment the .save() line The table entry is saved, but a 500 error is return. A...
[ "ip is a field in poll. See line 12 of your paste.\n" ]
[ 1 ]
[]
[]
[ "database", "django", "python", "save" ]
stackoverflow_0005890842_database_django_python_save.txt
Q: Referencing the ith element of each list in a 2d list Take a 2d list. I want to make a new list with only the ith element from each list. What is the best way to do this? I have: map(lambda x: x[i], l) Here is an example >>> i = 0 >>> l = [[1,10],[2,20],[3,30]] >>> map(lambda x: x[i], l) [1, 2, 3] A: Use...
Referencing the ith element of each list in a 2d list
Take a 2d list. I want to make a new list with only the ith element from each list. What is the best way to do this? I have: map(lambda x: x[i], l) Here is an example >>> i = 0 >>> l = [[1,10],[2,20],[3,30]] >>> map(lambda x: x[i], l) [1, 2, 3]
[ "Use list comprehension:\ni = 1\ndata = [[1,10],[2,20],[3,30]]\nresult = [d[i] for d in data] # [10, 20, 30]\n\nAlso see this question on list comprehension vs. map.\n" ]
[ 5 ]
[]
[]
[ "map", "python", "subscript" ]
stackoverflow_0005891284_map_python_subscript.txt
Q: ajax load disables other links, form submitted even if return false , I'm trying to load portions of a form based on validation results. here is the code I'm using its the same for all those button on the form. $("#button").click(function(e){ e.preventDefault(); noPgLoad(this); }); function noPgLoad(bu...
ajax load disables other links, form submitted even if return false ,
I'm trying to load portions of a form based on validation results. here is the code I'm using its the same for all those button on the form. $("#button").click(function(e){ e.preventDefault(); noPgLoad(this); }); function noPgLoad(button){ $.ajax({ type: "POST", url: url, data : serialized_dat...
[ "I'm not sure about your first problem, but I think you can solve the second by using live (see jquery docs) instead of click\n$(\"#button\").live('click', function(e){\n e.preventDefault();\n noPgLoad(this);\n});\n\nTo explain briefly, when you use click, it only applies to the elements on the page. I think that...
[ 0 ]
[]
[]
[ "django", "jquery", "python" ]
stackoverflow_0005890764_django_jquery_python.txt
Q: Matching a specific sequence with regex? I'm trying to match terms which appear as: abcd[_stringiwant_]efgh and abcd[_string_i_want_]efgh I'm able to the first expression with: re.compile('\[_[^\[\]_]*_\]'); but this fails to grab the string for the second expression. Anyone have any suggestions of a regex wh...
Matching a specific sequence with regex?
I'm trying to match terms which appear as: abcd[_stringiwant_]efgh and abcd[_string_i_want_]efgh I'm able to the first expression with: re.compile('\[_[^\[\]_]*_\]'); but this fails to grab the string for the second expression. Anyone have any suggestions of a regex which works for both?
[ "re.compile('\\[([^\\]]+)\\]')\n\nThat ought to work. Not sure about anything Python specific you'd have to do, but that expression will grab any string between [ and ]\n", "David's regex should work, but I prefer\nre.compile(r'\\[(.+?)\\]')\n\nfor readability. The +? is a non-greedy modifier, meaning it will gra...
[ 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005889338_python_regex.txt
Q: Trouble handling generic relationship in django I want to model a situation and I´m having real trouble handling it. The domain is like this: There are Posts, and every post has to be associated one to one with a MediaContent. MediaContent can be a picture or a video (for now, maybe music later). So, what I have i...
Trouble handling generic relationship in django
I want to model a situation and I´m having real trouble handling it. The domain is like this: There are Posts, and every post has to be associated one to one with a MediaContent. MediaContent can be a picture or a video (for now, maybe music later). So, what I have is: mediacontents/models.py class MediaContent(models....
[ "Your approach looks good to me. You just need to override the draw_item method in your Picture and Video models. Your template will look something like\n{% for post in posts %}\n {{ post.media_content.draw_item }}\n{% endfor %}\n\nand it doesn't matter which model the generic foreign key points to, as long as it ...
[ 1 ]
[]
[]
[ "database_design", "django", "django_models", "python", "relational_database" ]
stackoverflow_0005890559_database_design_django_django_models_python_relational_database.txt
Q: Counting bi-gram frequencies I've written a piece of code that essentially counts word frequencies and inserts them into an ARFF file for use with weka. I'd like to alter it so that it can count bi-gram frequencies, i.e. pairs of words instead of single words although my attempts have proved unsuccessful at best. ...
Counting bi-gram frequencies
I've written a piece of code that essentially counts word frequencies and inserts them into an ARFF file for use with weka. I'd like to alter it so that it can count bi-gram frequencies, i.e. pairs of words instead of single words although my attempts have proved unsuccessful at best. I realise there's alot to look at ...
[ "This should get you started:\ndef bigrams(words):\n wprev = None\n for w in words:\n yield (wprev, w)\n wprev = w\n\nNote that the first bigram is (None, w1) where w1 is the first word, so you have a special bigram that marks start-of-text. If you also want an end-of-text bigram, add yield (wpr...
[ 5, 3, 1, 1 ]
[]
[]
[ "arff", "nlp", "python" ]
stackoverflow_0005883573_arff_nlp_python.txt
Q: Help with Strange Python scraping error. HTTPError with one machine while it works on others I am using a proxy and following is the code. 20 req = urllib2.Request(url) 21 # run the request for each proxy 22 # now set the proxy 23 req.set_proxy(proxy, "http") 24 req.add_header('User-Agent...
Help with Strange Python scraping error. HTTPError with one machine while it works on others
I am using a proxy and following is the code. 20 req = urllib2.Request(url) 21 # run the request for each proxy 22 # now set the proxy 23 req.set_proxy(proxy, "http") 24 req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') ...
[ "Does that script work on the first machine?\nCheck here to see if proxy is working: http://www.domaintools.com/research/my-ip/\n" ]
[ 0 ]
[]
[]
[ "python", "screen_scraping", "urllib2" ]
stackoverflow_0003259207_python_screen_scraping_urllib2.txt
Q: Opening a handle to a device in Python on Windows I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax: #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, ...
Opening a handle to a device in Python on Windows
I'm trying to use the giveio.sys driver which requires a "file" to be opened before you can access protected memory. I'm looking at a C example from WinAVR/AVRdude that uses the syntax: #define DRIVERNAME "\\\\.\\giveio" HANDLE h = CreateFile(DRIVERNAME, GENERIC_READ, 0, NULL...
[ "Solution: in python you have to use win32file.CreateFile() instead of open(). Thanks everyone for telling me what I was trying to do, it helped me find the answer!\n", "I don't know anything about Python, but I do know a bit about drivers. You're not trying to 'open a file in kernel space' at all - you're just ...
[ 6, 3, 2, 2, 2, 1 ]
[]
[]
[ "device", "python", "windows" ]
stackoverflow_0000212715_device_python_windows.txt
Q: Display the date, like "May 5th", using pythons strftime? Possible Duplicate: Python: Date Ordinal Output? In Python time.strftime can produce output like "Thursday May 05" easily enough, but I would like to generate a string like "Thursday May 5th" (notice the additional "th" on the date). What is the best way...
Display the date, like "May 5th", using pythons strftime?
Possible Duplicate: Python: Date Ordinal Output? In Python time.strftime can produce output like "Thursday May 05" easily enough, but I would like to generate a string like "Thursday May 5th" (notice the additional "th" on the date). What is the best way to do this?
[ "strftime doesn't allow you to format a date with a suffix.\nHere's a way to get the correct suffix:\nif 4 <= day <= 20 or 24 <= day <= 30:\n suffix = \"th\"\nelse:\n suffix = [\"st\", \"nd\", \"rd\"][day % 10 - 1]\n\nfound here\nUpdate:\nCombining a more compact solution based on Jochen's comment with gsteff...
[ 102, 19, 12, 3, 2 ]
[]
[]
[ "python", "strftime" ]
stackoverflow_0005891555_python_strftime.txt
Q: How to invert colors of an image in pygame? I have a pygame Surface and would like to invert the colors. Is there any way quicker & more pythonic than this? It's rather slow. I'm aware that subtracting the value from 255 isn't the only definition of an "inverted color," but it's what I want for now. I'm surprise...
How to invert colors of an image in pygame?
I have a pygame Surface and would like to invert the colors. Is there any way quicker & more pythonic than this? It's rather slow. I'm aware that subtracting the value from 255 isn't the only definition of an "inverted color," but it's what I want for now. I'm surprised that pygame doesn't have something like this bu...
[ "Taken from: http://archives.seul.org/pygame/users/Sep-2008/msg00142.html\ndef inverted(img):\n inv = pygame.Surface(img.get_rect().size, pygame.SRCALPHA)\n inv.fill((255,255,255,255))\n inv.blit(img, (0,0), None, BLEND_RGB_SUB)\n return inv\n\nThis may do the alpha channel wrong, but you should be able to ...
[ 10, 7, 1 ]
[]
[]
[ "colors", "graphics", "inversion", "pygame", "python" ]
stackoverflow_0005891808_colors_graphics_inversion_pygame_python.txt
Q: Python Simulate Keypress in Flash Application There is a form in a flash application that I would like to fill out automatically. I did a search, and found this: Key Presses in Python That works fine for notepad and such, but how do I grab a flash object running in FireFox, simulate pressing characters, and also s...
Python Simulate Keypress in Flash Application
There is a form in a flash application that I would like to fill out automatically. I did a search, and found this: Key Presses in Python That works fine for notepad and such, but how do I grab a flash object running in FireFox, simulate pressing characters, and also simulate pressing ENTER for moving to the next field...
[ "This works perfectly: http://www.rutherfurd.net/python/sendkeys\n", "This is possible via the Selenium testing framework with a special Flash extension for letting selenium talk to Flash in the browser. The Python client is in the downloads section.\nHere is an article walking through an example (the sample clie...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005889372_python.txt
Q: 'module' object has no attribute 'Twitter' I am trying to follow the example on page 5 of the book: Mining the Social Web, from O'Reilly. I am coming across the following error: >>> import twitter >>> twitter_api = twitter.Twitter(domain="api.twitter.com", api_version='1') Traceback (most recent call last): Fi...
'module' object has no attribute 'Twitter'
I am trying to follow the example on page 5 of the book: Mining the Social Web, from O'Reilly. I am coming across the following error: >>> import twitter >>> twitter_api = twitter.Twitter(domain="api.twitter.com", api_version='1') Traceback (most recent call last): File "", line 1, in AttributeError: 'module' obj...
[ "Works for me. I installed twitter through easy_install, which installed the latest version (1.6.1). dir(twitter) also lists Twitter here.\nYou could remove the twitter package from site-packages and try reinstalling again.\n", "Check the value of twitter.__file__ (after you've imported twitter). My guess is eith...
[ 4, 4 ]
[]
[]
[ "python", "twitter" ]
stackoverflow_0005891349_python_twitter.txt
Q: Send HTML e-mail in App Engine / Python? Can you please give me a simple, and straightforward python example of sending an HTML e-mail using App Engine? Plaintext is straightforward, but I'm having difficulties with HTML tags. A: I haven't tested this, so please forgive any little bugs. It's based on an example...
Send HTML e-mail in App Engine / Python?
Can you please give me a simple, and straightforward python example of sending an HTML e-mail using App Engine? Plaintext is straightforward, but I'm having difficulties with HTML tags.
[ "I haven't tested this, so please forgive any little bugs. It's based on an example from the Google documentation:\nhttp://code.google.com/appengine/docs/python/mail/sendingmail.html\nfrom google.appengine.api import mail\n\nmessage = mail.EmailMessage(sender=\"Example.com Support <support@example.com>\",\n ...
[ 54, 4, 0 ]
[]
[]
[ "email", "google_app_engine", "python" ]
stackoverflow_0002860614_email_google_app_engine_python.txt
Q: Static and instance methods in Python Can I define a Python method to be both static and instance at the same time? Something like: class C(object): @staticmethod def a(self, arg1): if self: blah blah So that I can call it with both: C.a(arg1) C().a(arg1) The intent is to be a...
Static and instance methods in Python
Can I define a Python method to be both static and instance at the same time? Something like: class C(object): @staticmethod def a(self, arg1): if self: blah blah So that I can call it with both: C.a(arg1) C().a(arg1) The intent is to be able to run two sets of logics. If accessed ...
[ "import functools\n\nclass static_or_instance(object):\n def __init__(self, func):\n self.func = func\n\n def __get__(self, instance, owner):\n return functools.partial(self.func, instance)\n\nclass C(object):\n @static_or_instance\n def a(self, arg):\n if self is None:\n print \"called without se...
[ 17, 4, 2, 1 ]
[]
[]
[ "descriptor", "instance_methods", "python", "static_methods" ]
stackoverflow_0005892619_descriptor_instance_methods_python_static_methods.txt
Q: Python syntax inconsistency? I've been reading up on python's special class methods in Dive into Python, and it seems like some methods have odd or inconsistent syntax. To get the items from a dictionary you would call the dictionary class method items() >>> my_dictionary.items() [('name', 'Old Gregg'), ('Race', '...
Python syntax inconsistency?
I've been reading up on python's special class methods in Dive into Python, and it seems like some methods have odd or inconsistent syntax. To get the items from a dictionary you would call the dictionary class method items() >>> my_dictionary.items() [('name', 'Old Gregg'), ('Race', 'Scaly Man-Fish')] However, to det...
[ "Guido van Rossum explained it thusly:\n(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a form...
[ 13, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005892723_python.txt
Q: Ajax returning only new message I've this Django app: A page with a form at the top with one field for sending message into db, and below it the global message list. <body> <form id="messageForm" action="" method="post"> {{ form.as_p }} <input type="submit" id="go" name="go" value="Go!"> </form> <div id=...
Ajax returning only new message
I've this Django app: A page with a form at the top with one field for sending message into db, and below it the global message list. <body> <form id="messageForm" action="" method="post"> {{ form.as_p }} <input type="submit" id="go" name="go" value="Go!"> </form> <div id="msg_list"> <ul id="update"> ...
[ "If I understand you correctly you want to return a list of messages newer than the one saved by your form. You could get the timestamp from the form, and then filter messages to get only messages with a timestamp greater than the message just saved. I'm going to assume your form's timestamp field is of the forms.D...
[ 0 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0005891045_ajax_django_python.txt
Q: Python threading- returning control to the terminal while keeping a frame open To sum up: I want to open a frame in Python, be able to work with that frame, and also be able to continue using that terminal. Basically, I'd like to mimic some Matlab behavior in Python. In Matlab, you can do: x=0:10; y=0:10; plot(x,y...
Python threading- returning control to the terminal while keeping a frame open
To sum up: I want to open a frame in Python, be able to work with that frame, and also be able to continue using that terminal. Basically, I'd like to mimic some Matlab behavior in Python. In Matlab, you can do: x=0:10; y=0:10; plot(x,y) and a plot will come up, be interactive, and you also have access to the terminal...
[ "matplotlib gets funny about using plt.show(). To get the behaviour you want, look at the docs on using matplotlib interactively. The nice thing is, no threading necessary.\n(In your solution, the plot is prepared in the background, the background thread terminates, and your foreground threads stays in the plt.show...
[ 3, 0 ]
[]
[]
[ "matplotlib", "multithreading", "python" ]
stackoverflow_0005888127_matplotlib_multithreading_python.txt
Q: Python3.2 Str.format value repetition I'm generating specifically formated input files for a program, and using a small python tkinter GUI frontend to do so. The old code made use of fortran format statements. Unless there's already a direct conversion set of functions for python (which I haven't found), I figured...
Python3.2 Str.format value repetition
I'm generating specifically formated input files for a program, and using a small python tkinter GUI frontend to do so. The old code made use of fortran format statements. Unless there's already a direct conversion set of functions for python (which I haven't found), I figured python's formatting would do the job. In g...
[ "As ninjagecko suggested, you want to construct your format string in pieces.\nUsing implicit field numbering as I have done helps simplify this, although it isn't strictly necessary (explicit numbering just gets a little more verbose making sure the numbers line up). Mixing old- and new-style string formatting als...
[ 4, 2 ]
[]
[]
[ "format", "python", "string" ]
stackoverflow_0005890572_format_python_string.txt
Q: Python: Convert simplejson dumped unicode datetime back to datetime object I have... entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())}) How do I convert the datetime (that was converted to unicode) back to datetime again? So that I can do something like... entity2 = simplejson.loads(entity) #you...
Python: Convert simplejson dumped unicode datetime back to datetime object
I have... entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())}) How do I convert the datetime (that was converted to unicode) back to datetime again? So that I can do something like... entity2 = simplejson.loads(entity) #your answer here.. add5 = entity2["a"] + datetime.timedelta(minutes=5) Thanks!
[ "DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'\n\nDo the following before serializing:\ntime = datetime.strftime(time, DATETIME_FORMAT)\n\nDo the following after unserializing:\ntime = datetime.strptime(time, DATETIME_FORMAT)\n\nexample:\n>>> from datetime import datetime\n\n>>> DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'\n\n>>>...
[ 7, 2 ]
[]
[]
[ "datetime", "json", "python", "simplejson", "unicode" ]
stackoverflow_0005893853_datetime_json_python_simplejson_unicode.txt
Q: How do you run a Django development server at the command prompt? trying to run the development server as directed by the django book 2.0. Heres what im doing so far: 1) cd into the directory containing python 2) run the python interpreter using the "python" command 3) Import django with the python interpreter h...
How do you run a Django development server at the command prompt?
trying to run the development server as directed by the django book 2.0. Heres what im doing so far: 1) cd into the directory containing python 2) run the python interpreter using the "python" command 3) Import django with the python interpreter http://www.djangobook.com/en/2.0/chapter02/ Now step 4 should be cd into...
[ "Change in your django project and run:\npython manage.py runserver\n\nthat's all!\n", "You can't execute the \"cd\" command directly while in the Python interpreter. You need to first exit the interpreter by calling the exit() method. (Just write exit() into the interpreter and press enter). The revised steps ta...
[ 32, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005894131_django_python.txt
Q: Installing Python eggs under PyPy How do I install Python egg under PyPy? During installation, PyPy created /usr/lib64/pypy-1.5/site-packages/ directory. So, I tried using easy_install with prefix set to this directory, however it complains that this is not a valid directory for eggs. Do I just copy eggs from /usr...
Installing Python eggs under PyPy
How do I install Python egg under PyPy? During installation, PyPy created /usr/lib64/pypy-1.5/site-packages/ directory. So, I tried using easy_install with prefix set to this directory, however it complains that this is not a valid directory for eggs. Do I just copy eggs from /usr/lib/python2.7/site-packages, or is it ...
[ "First, you need to make sure that you have distribute installed specifically for PyPy. I don't know how fedora packages things, but in general installing a package for cpython does not make it available also for PyPy. In particular, /usr/bin/easy_install is probably CPython-only.\nIf you use a \"normal\" install ...
[ 14 ]
[]
[]
[ "development_environment", "pypy", "python" ]
stackoverflow_0005885820_development_environment_pypy_python.txt
Q: GPA Calculator Program in Python with a tkinter GUI I'm trying to create a GPA calculator in python using tkinter. I'm using python 3.1. Heres what I have so far for my GUI. root = Tk() root.title('GPA Calculator') #create frames self.column_headers = Frame(root) self.class1_frame = Frame(roo...
GPA Calculator Program in Python with a tkinter GUI
I'm trying to create a GPA calculator in python using tkinter. I'm using python 3.1. Heres what I have so far for my GUI. root = Tk() root.title('GPA Calculator') #create frames self.column_headers = Frame(root) self.class1_frame = Frame(root) self.class2_frame = Frame(root) self.class3_fr...
[ "So, I completely agree with jon_darkstar about not hardcoding the courses. This looks like a prime candidate for it's own class (in the programming concept sense).\nBut, to replace your Entry boxes with dropdowns (known as *OptionMenu*s), you'd do the following:\nself.class1label = Label(self.class1_frame, \\\n ...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0005893009_python_tkinter.txt
Q: jQuery datepicker and selenium I am creating a selenium test and in all the tests I want to simulate the user choosing the date. The problem is when the month changes the possible date selections is limited making it very fragile. This is my current code: sel.click("fromdate") sel.click("//div[@id='dp-popup']/div...
jQuery datepicker and selenium
I am creating a selenium test and in all the tests I want to simulate the user choosing the date. The problem is when the month changes the possible date selections is limited making it very fragile. This is my current code: sel.click("fromdate") sel.click("//div[@id='dp-popup']/div[3]/table/tbody/tr[2]/td[6]") sel.cl...
[ "I'm using selenium and jQuery date picker. I'm always using xpath checker in selenium tests to create stable tests. \nWell, this is the path of month name //html/body/div[@id='ui-datepicker-div']/div/div/span[1] and this gives the year //html/body/div[@id='ui-datepicker-div']/div/div/span[2] and this is //html/bod...
[ 0 ]
[]
[]
[ "jquery", "python", "selenium" ]
stackoverflow_0005873848_jquery_python_selenium.txt
Q: Split string by ' and - How do split string by apostrophe ' and - ? For example, given string = "pete - he's a boy" A: You can use the regular expression module's split function: re.split("['-]", "pete - he's a boy") A: string = "pete - he's a boy" result = string.replace("'", "-").split("-") print result ['p...
Split string by ' and -
How do split string by apostrophe ' and - ? For example, given string = "pete - he's a boy"
[ "You can use the regular expression module's split function:\nre.split(\"['-]\", \"pete - he's a boy\")\n\n", "string = \"pete - he's a boy\"\nresult = string.replace(\"'\", \"-\").split(\"-\")\nprint result\n\n['pete ', ' he', 's a boy']\n\n", "This feels kind of hacky but you could do:\nstring.replace(\"-\", ...
[ 18, 9, 2, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005894392_python.txt
Q: Putting matlab code into python I got a little problem in putting the code from matlab into python, i know how to make loops and stuff but the double equal sign is the same as function is member and I have no idea how to put it in python for i=1:49 if path==var(path(1),i) == 0 & var(path(1),i) ~= 0 pat...
Putting matlab code into python
I got a little problem in putting the code from matlab into python, i know how to make loops and stuff but the double equal sign is the same as function is member and I have no idea how to put it in python for i=1:49 if path==var(path(1),i) == 0 & var(path(1),i) ~= 0 path(1,2) = var(r,i); var2(i,1:2...
[ "The double double equal sign in Matlab tests whether each value is equivalent.\nIn other words (a==b==c) will evaluate to 1 if a,b,c are equivalent, and 0 otherwise (even if a==b.)\nIt is sufficient to ensure that a==b and b==c (or a==b and a==c, etc.)\nThe tilde equals sign is simply \"not equal to\".\nSo your if...
[ 1 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0005894941_matlab_python.txt
Q: Django - create nested html list from list of dictionary objects I have a Python list of dictionary in the form e.g. [{'Parent':'top', 'Child':'obj1', 'Level':0}, {'Parent':'obj1', 'Child':'obj2', 'Level':1}, {'Parent':'obj1', 'Child':'obj3', 'Level':1}, {'Parent':'obj2', 'Child':'obj4', 'Level':2}, {'Parent':...
Django - create nested html list from list of dictionary objects
I have a Python list of dictionary in the form e.g. [{'Parent':'top', 'Child':'obj1', 'Level':0}, {'Parent':'obj1', 'Child':'obj2', 'Level':1}, {'Parent':'obj1', 'Child':'obj3', 'Level':1}, {'Parent':'obj2', 'Child':'obj4', 'Level':2}, {'Parent':'obj4', 'Child':'obj5', 'Level':3}] I want to write this out as a nes...
[ "Quick solution:\ndef make_list(d):\n def append_children(parent, d):\n children = [[x['Child']] for x in d if x['Parent'] == parent[0]]\n if children:\n parent.append(children)\n for child in children:\n append_children(child, d)\n\n results = [[x['Child']] ...
[ 3 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0005895353_django_django_templates_python.txt
Q: How to use for loop to print cards? I have all 52 cards set up, and i try to print all 52 cards by using for loop. I don't know how to set my for loop at this point. def define_cards(n): rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king") suit_string =...
How to use for loop to print cards?
I have all 52 cards set up, and i try to print all 52 cards by using for loop. I don't know how to set my for loop at this point. def define_cards(n): rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king") suit_string = ("clubs","diamonds","hearts","spades") ...
[ "Your function define_cards has to return the list. Add return cards at its end.\nThen you have to actually call/execute this function.\nThen you can access individual cards in this list:\ncards = define_cards()\nfor i, card in enumerate(cards):\n print i, card\n\nHowever, if you are searching for a \"more pytho...
[ 4, 2, 1, 1, 1 ]
[]
[]
[ "playing_cards", "python" ]
stackoverflow_0005895581_playing_cards_python.txt
Q: Sorting a multiple river stream branch structure I have a list of numbered Stream segments. And each one lists the next down stream stream segment. The last stream segment of course has no down stream segment referenced. I need to order the entire river, starting from the topmost stream and progressing down stream...
Sorting a multiple river stream branch structure
I have a list of numbered Stream segments. And each one lists the next down stream stream segment. The last stream segment of course has no down stream segment referenced. I need to order the entire river, starting from the topmost stream and progressing down stream. At junctions I need to jump to the top of the next b...
[ "You need to represent your segments as a graph data structure. Then, familiar graph algorithms like DFS, BFS and topological sort should do the work for you, depending on what you need exactly.\nIf you could clarify your question with a simple example or a picture so it's clearly understood which sorting order you...
[ 1, 1 ]
[]
[]
[ "branch", "python", "sorting", "stream", "tree" ]
stackoverflow_0005894219_branch_python_sorting_stream_tree.txt
Q: Is it possible to detect whether or not something is plugged into the audio jack, in python? I'm trying to detect if there is a device hooked into the audio jack with python. This is in Windows 7. A: see https://superuser.com/questions/110933/how-does-a-sound-card-determine-if-headphones-are-plugged-in The answe...
Is it possible to detect whether or not something is plugged into the audio jack, in python?
I'm trying to detect if there is a device hooked into the audio jack with python. This is in Windows 7.
[ "see https://superuser.com/questions/110933/how-does-a-sound-card-determine-if-headphones-are-plugged-in\nThe answer is: It depends on your hardware. I have not seen any operating system detect headphones in the past decade, but some cheap soundcards do support it. (edit: According to Larry Osterman's comment, they...
[ 2 ]
[]
[]
[ "audio", "headphones", "python", "windows_7" ]
stackoverflow_0005895993_audio_headphones_python_windows_7.txt
Q: Get HTML source, including result of javascript and authentication I am building a web scraper and need to get the html page source as it actually appears on the page. However, I only get a limited html source, one that does not include the needed info. I think that I am either seeing it pre javascript loaded or e...
Get HTML source, including result of javascript and authentication
I am building a web scraper and need to get the html page source as it actually appears on the page. However, I only get a limited html source, one that does not include the needed info. I think that I am either seeing it pre javascript loaded or else maybe I'm not getting the full info because I don't have the right a...
[ "Most libraries like this do not support javascript.\nIf you want javascript, you will need to either automate an existing browser or browser engine, or get a really monolithic big beefy library that is essentially an advanced web crawler.\n" ]
[ 2 ]
[]
[]
[ "authentication", "python", "web_crawler" ]
stackoverflow_0005896049_authentication_python_web_crawler.txt
Q: Extracting all nouns from a string Possible Duplicate: Extracting nouns from Noun Phase in NLP Do anyone have some examples on how to extract all nouns from a string using Python's NLTK? For example, i have this string: "I Like Tomatoes and Lettuce". I want to build a method that returns "Tomatoes" and "Lettuce....
Extracting all nouns from a string
Possible Duplicate: Extracting nouns from Noun Phase in NLP Do anyone have some examples on how to extract all nouns from a string using Python's NLTK? For example, i have this string: "I Like Tomatoes and Lettuce". I want to build a method that returns "Tomatoes" and "Lettuce." If not in Python, does anyone know of...
[ "Get the NLTK package, and either use its built-in parser then this method; or, much faster, part-of-speech tag the string and get all the words out that have the tag NN; those are the nouns. Read up on other part-of-speech tags to find out how you can properly extract I and like.\nNeither method is flawless, but i...
[ 1, 0 ]
[]
[]
[ "nlp", "python" ]
stackoverflow_0005884533_nlp_python.txt
Q: initialising a form with data using django on google appengine I have a post handler that uses a 'from google.appengine.ext.db.djangoforms.ModelForm'. It pulls the existing instance the data base then initialises the form by: myForm = TestForm(instance=self_instance, data=post_data) I'm only putting one of the...
initialising a form with data using django on google appengine
I have a post handler that uses a 'from google.appengine.ext.db.djangoforms.ModelForm'. It pulls the existing instance the data base then initialises the form by: myForm = TestForm(instance=self_instance, data=post_data) I'm only putting one of the three properties in the post_data which is being correctly copied t...
[ "This is giving me the behaviour I'm after:\nif self_instance:\n logging.info('creating form with instance so updating the post data, we need this to bind the form so we can validate it')\n if post_data:\n #update the post data with existing values\n for prop in self_instance._properties:\n if prop not...
[ 2, 1, 1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0005894989_django_google_app_engine_python.txt
Q: Finding a line in a Python string (not file) I know how to do this with a file, you just do file = file.open(f) f file = open("file.txt") for line in file.readlines(): if line.startswith("foo"): print line But now I'm reading the output of a process like this log = os.popen("log.sh").read() This outputs as...
Finding a line in a Python string (not file)
I know how to do this with a file, you just do file = file.open(f) f file = open("file.txt") for line in file.readlines(): if line.startswith("foo"): print line But now I'm reading the output of a process like this log = os.popen("log.sh").read() This outputs as a string, which can be used with print fine, but...
[ "for line in log.splitlines():\n # whatever\n\nNote that you don't need to use f.readlines() for a file f.\nfor line in f:\n # whatever\n\nwill work fine.\n", "You have several options:\nOption 1:\nlog = os.popen(\"log.sh\").readlines()\n\nThis gives a list of string that you can process exactly like you do...
[ 9, 6 ]
[]
[]
[ "grep", "python", "regex" ]
stackoverflow_0005897010_grep_python_regex.txt
Q: datetime.strptime () throws 'does not match format' error I get time data '19/Apr/2011:22:12:39' does not match format '%d/%b/%y:%H:%M:%S' when using datetime.strptime('19/Apr/2011:22:12:39','%d/%b/%y:%H:%M:%S') What am I doing wrong? A: Try %d/%b/%Y:%H:%M:%S instead - %y right now means 11. You can "debug" dat...
datetime.strptime () throws 'does not match format' error
I get time data '19/Apr/2011:22:12:39' does not match format '%d/%b/%y:%H:%M:%S' when using datetime.strptime('19/Apr/2011:22:12:39','%d/%b/%y:%H:%M:%S') What am I doing wrong?
[ "Try %d/%b/%Y:%H:%M:%S instead - %y right now means 11.\nYou can \"debug\" datetime formats easily using date (on the shell and not on python, I mean, assuming you're running GNU/Linux or similar):\ndate '+%d/%b/%Y:%H:%M:%S'\n05/May/2011:09:00:41\n\n", "You're checking for a 2 digit year ( %y ) instead of a four ...
[ 30, 12, 6 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005897263_django_python.txt
Q: python iterating through lists Consider the lists below filters= [u, i, g, r, z] result = [None, 34, None, None, 45] the items in the result are computed for each filter in filters. It happens that filters, u, g, z did not return any results. So i would to re-compute the values of result[0], result[2], ...
python iterating through lists
Consider the lists below filters= [u, i, g, r, z] result = [None, 34, None, None, 45] the items in the result are computed for each filter in filters. It happens that filters, u, g, z did not return any results. So i would to re-compute the values of result[0], result[2], result[4], using the filters that re...
[ "Not particularly efficient solution:\ndef filters_by_distance(i):\n '''Generate filters by distance from i'''\n sorted_indices = sorted(range(len(filters)), key=lambda j: abs(j-i))\n return (filters[j] for j in sorted_indices)\n\n" ]
[ 1 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0005897254_list_loops_python.txt
Q: wx.Panel borders dont get destroyed by Destroy() method So I`ve started using wx to generate my GUI. I created a custom table using a FlexGridSizer and then I wanted to clear the table when I push a button. So my method is: def clearPressed(self,event): self.label_ID.Destroy() self.label_NAME.Destroy() ...
wx.Panel borders dont get destroyed by Destroy() method
So I`ve started using wx to generate my GUI. I created a custom table using a FlexGridSizer and then I wanted to clear the table when I push a button. So my method is: def clearPressed(self,event): self.label_ID.Destroy() self.label_NAME.Destroy() self.label_ADMIN.Destroy() self.label_SELECTED.Destroy()...
[ "This seems like a very complicated approach. Have you looked at using wxGrid? You might lose a little flexibility, but you will save yourself having to write tremendous amounts of code to look after routine grid management tasks such as this.\n", "What do you mean when saying \"The clearPressed method now dest...
[ 1, 0 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0005894672_python_wxpython_wxwidgets.txt
Q: diff algorithm implementation in python I checked out the source code of Python 2.6, and I want to study the diff implementation. However, I can not find the right source file. Could any one point me to whichever source file contains the algorithm implementation? A: If by "diff implementation in Python" you mea...
diff algorithm implementation in python
I checked out the source code of Python 2.6, and I want to study the diff implementation. However, I can not find the right source file. Could any one point me to whichever source file contains the algorithm implementation?
[ "If by \"diff implementation in Python\" you mean the difflib module, then here is the source.\nThere is also a simple diff implementation based on this module in the Python source distribution.\n" ]
[ 6 ]
[]
[]
[ "diff", "python" ]
stackoverflow_0005897983_diff_python.txt
Q: Python: How to access data from this type of list? Quick Python question: How do I access data from a nested list like this: {'album': [u'Rumours'], 'comment': [u'Track 3'], 'artist': [u'Fleetwood Mac'], 'title': [u'Never Going Back Again'], 'date': [u'1977'], 'genre': [u'Rock'], 'tracknumber': [u'03']} I tried ...
Python: How to access data from this type of list?
Quick Python question: How do I access data from a nested list like this: {'album': [u'Rumours'], 'comment': [u'Track 3'], 'artist': [u'Fleetwood Mac'], 'title': [u'Never Going Back Again'], 'date': [u'1977'], 'genre': [u'Rock'], 'tracknumber': [u'03']} I tried listname[0][0] but it returns the error: AttributeError...
[ "This is not a list, it is a dictionary. It takes an immutable type as key and any type as value for every key,value pair. In your case this is a dictionary with str type keys and list's as values. You must first extract the list from the dictionary, and then the first element from the list, assuming you meant that...
[ 9, 3 ]
[]
[]
[ "list", "nested", "python" ]
stackoverflow_0005898186_list_nested_python.txt
Q: Program gets stuck attempting to create NNTP connection My program starts a connection to a usenet server like this: s = nntplib.NNTP(self.nserver, 119, self.nuser, self.npass) But sometimes there's a problem. The connection is not made and the program waits for a response indefinitely. How can I make it check fo...
Program gets stuck attempting to create NNTP connection
My program starts a connection to a usenet server like this: s = nntplib.NNTP(self.nserver, 119, self.nuser, self.npass) But sometimes there's a problem. The connection is not made and the program waits for a response indefinitely. How can I make it check for a timeout?
[ "It is not the proper solution, but try to set a timeout to the socket module : \nimport socket\n\norig_timeout = socket.getdefaulttimeout(timeout)\nsocket.setdefaulttimeout(timeout)\n\ns = nntplib.NNTP(self.nserver, 119, self.nuser, self.npass)\n\nsocket.setdefaulttimeout(orig_timeout)\n\n" ]
[ 2 ]
[]
[]
[ "nntp", "python" ]
stackoverflow_0005898761_nntp_python.txt
Q: Help (or advice) me get started with lxml I am trying to learn python, and I actually feel that "learn python the hardway", "a byte of python", and "head first python" are really great books. However - now that I want to start a "real" project, lxml makes me feel like a complete git. This is what I would like to d...
Help (or advice) me get started with lxml
I am trying to learn python, and I actually feel that "learn python the hardway", "a byte of python", and "head first python" are really great books. However - now that I want to start a "real" project, lxml makes me feel like a complete git. This is what I would like to do (objectives) I am trying to parse a newspaper...
[ "This is a lot to read - perhaps you could break up into smaller specific questions.\nRegarding lxml, here are some examples. The official documentation is also very good - take the time to work through the examples. And the mailing list is very active.\nRegarding BeautifulSoup, lxml is more efficient and in my exp...
[ 3, 2 ]
[]
[]
[ "lxml", "python", "screen_scraping" ]
stackoverflow_0005757201_lxml_python_screen_scraping.txt
Q: "as of" in numpy I am looking for a way to implement an "as of" operator in numpy. Specifically, if: t1 is an n-vector of timestamps in a strictly increasing order; d1 is an n x p matrix of observations, with i-th row corresponding to t1[i]; t2 in an m-vector of timestamps, also in a strictly increasing order; I...
"as of" in numpy
I am looking for a way to implement an "as of" operator in numpy. Specifically, if: t1 is an n-vector of timestamps in a strictly increasing order; d1 is an n x p matrix of observations, with i-th row corresponding to t1[i]; t2 in an m-vector of timestamps, also in a strictly increasing order; I need to create an m x...
[ "Your best choice is numpy.searchsorted():\nd1[numpy.searchsorted(t1, t2, side=\"right\") - 1]\n\nThis will search the indices where the values of t2 would have to be inserted into t1 to maintain order. The side=\"right\" and - 1 bits are to ensure exactly the specified behaviour.\nEdit: To get rows of NaNs where ...
[ 11 ]
[]
[]
[ "loops", "numpy", "python", "time_series" ]
stackoverflow_0005898617_loops_numpy_python_time_series.txt
Q: mean of elements i and i+1 in a numpy array Out of curiosity, is there a specific numpy function to do the following (which would supposedly be faster): a = np.array((0,2,4)) b = np.zeros(len(a) - 1) for i in range(len(b)): b[i] = a[i:i+2].mean() print(b) #prints [1,3] Cheers A: You could use b = (a[1:] + ...
mean of elements i and i+1 in a numpy array
Out of curiosity, is there a specific numpy function to do the following (which would supposedly be faster): a = np.array((0,2,4)) b = np.zeros(len(a) - 1) for i in range(len(b)): b[i] = a[i:i+2].mean() print(b) #prints [1,3] Cheers
[ "You could use\nb = (a[1:] + a[:-1]) / 2.\n\nto avoid the Python loop.\n" ]
[ 7 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005899106_arrays_numpy_python.txt
Q: What sample application demonstrates best practices for MVC structure in a Google App Engine/Python app? Although I know the Python language, I've never built a significant web app containing a large number of classes. Now that I am contemplating doing so, I am questioning how best to structure the code in an orga...
What sample application demonstrates best practices for MVC structure in a Google App Engine/Python app?
Although I know the Python language, I've never built a significant web app containing a large number of classes. Now that I am contemplating doing so, I am questioning how best to structure the code in an organized way as I would normally do in a Java application. Are there any sample Python web apps for App Engine th...
[ "I recommend checking out Bloggart and rietveld.\nFor more, here's a list of App Engine samples, a big list of open-source App Engine projects, and another one.\n", "rietveld, by Guido van Rossum (Python creator) is a Django app built on GAE and is a good one to check out.\n" ]
[ 3, 2 ]
[]
[]
[ "architecture", "design_patterns", "google_app_engine", "model_view_controller", "python" ]
stackoverflow_0005896019_architecture_design_patterns_google_app_engine_model_view_controller_python.txt
Q: HTTPS connection using PEM Certificate I'm trying to POST HTTPS requests using a PEM certificate like following: import httplib CERT_FILE = '/path/certif.pem' conn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE) conn.request("POST", "/") response = conn.getresponse() print respon...
HTTPS connection using PEM Certificate
I'm trying to POST HTTPS requests using a PEM certificate like following: import httplib CERT_FILE = '/path/certif.pem' conn = httplib.HTTPSConnection('10.10.10.10','443', cert_file =CERT_FILE) conn.request("POST", "/") response = conn.getresponse() print response.status, response.reason conn.close() I h...
[ "It sounds like you need something similar to an answer I have provided before to perform simple client certificate authentication. Here is the code for convenience modified slightly for your question:\nimport httplib\nimport urllib2\n\nPEM_FILE = '/path/certif.pem' # Renamed from PEM_FILE to avoid confusion\nCLIEN...
[ 9, 2, 1 ]
[]
[]
[ "certificate", "https", "python", "ssl" ]
stackoverflow_0005896380_certificate_https_python_ssl.txt
Q: How do I use data in package_data from source code? In setup.py, I have specified package_data like this: packages=['hermes'], package_dir={'hermes': 'hermes'}, package_data={'hermes': ['templates/*.tpl']}, And my directory structure is roughly hermes/ | | docs/ | ... | hermes/ | | __init__.py | ...
How do I use data in package_data from source code?
In setup.py, I have specified package_data like this: packages=['hermes'], package_dir={'hermes': 'hermes'}, package_data={'hermes': ['templates/*.tpl']}, And my directory structure is roughly hermes/ | | docs/ | ... | hermes/ | | __init__.py | code.py | templates | | python.tpl |...
[ "The standard pkgutil module's get_data() function will calculate the path to your data, relative to your package, and retrieve the data for you via whatever module loader Python used to import the hermes package:\nimport pkgutil\ndata = pkgutil.get_data('hermes', 'templates/python.tpl')\n\nOf course in certain cas...
[ 46 ]
[]
[]
[ "build", "distribute", "distutils", "python", "setuptools" ]
stackoverflow_0005897666_build_distribute_distutils_python_setuptools.txt
Q: Does Google App Engine run one instance of an app per one request? or for all requests? Using google app engine: # more code ahead not shown application = webapp.WSGIApplication([('/', Home)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": ma...
Does Google App Engine run one instance of an app per one request? or for all requests?
Using google app engine: # more code ahead not shown application = webapp.WSGIApplication([('/', Home)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() If two different users request the webpage on two different machine, two individual ins...
[ "An instance can handle many requests over its lifetime. In the python runtime's threading model, each instance can only handle a single request at any given time. If 2 requests arrive at the same time they might be handled one after the other by a single instance, or a second instance might be spawned to handle th...
[ 4, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005899619_google_app_engine_python.txt
Q: meet M2Crypto.RSA.RSAError: bad signature while using rsa.verify all. I have to verify a signature that signed by PHP, but i'm using python. here is the code: e, n = parse_key('publickey(prod).xml') rsakey = Crypto.PublicKey.RSA.construct((long(n), long(e))) public_key = rsakey.publickey().exportKey() bio = M2Cryp...
meet M2Crypto.RSA.RSAError: bad signature while using rsa.verify
all. I have to verify a signature that signed by PHP, but i'm using python. here is the code: e, n = parse_key('publickey(prod).xml') rsakey = Crypto.PublicKey.RSA.construct((long(n), long(e))) public_key = rsakey.publickey().exportKey() bio = M2Crypto.BIO.MemoryBuffer(public_key) rsa = M2Crypto.RSA.load_pub_key_bio(bi...
[ "How are you doing the RSA signatures in PHP? A lot of PHP RSA implementations don't do PKCS#1 compliant signatures, which would mean that they're not interoperable.\nPersonally, I'd recommend phpseclib, a pure PHP RSA implementation.\n" ]
[ 0 ]
[]
[]
[ "php", "python", "rsa" ]
stackoverflow_0005899277_php_python_rsa.txt
Q: where is the instancemethod decorator? In my code I have a method that returns an instance of a class, like this: class MyClass: def fun( self, *args ): # the method return Props( self, *args ) class Props: # the returned object def __init__( self, parent, *args ): self.parent = parent self.args =...
where is the instancemethod decorator?
In my code I have a method that returns an instance of a class, like this: class MyClass: def fun( self, *args ): # the method return Props( self, *args ) class Props: # the returned object def __init__( self, parent, *args ): self.parent = parent self.args = args To keep things organized I am conside...
[ "I'm not sure exactly what you're trying to do, but I suspect you want to read up on descriptors. \nBasically, a descriptor is an attribute of a class that is itself a class that defines __get__ and __set__ methods. In your case, you could move the code from Props.__init__ to Props.__set__, set Props as the fun at...
[ 1, 1, 0 ]
[]
[]
[ "decorator", "instance_method", "python" ]
stackoverflow_0005632595_decorator_instance_method_python.txt
Q: Using input() in cmd I began messing around in python trying to create a frozen exe, i finally got it to work, then discovered that the input function doesn't seem to work properly when ran through the command prompt as opposed to in idle, or the interactive session. Any ideas why, or how to fix this? Edit: When i...
Using input() in cmd
I began messing around in python trying to create a frozen exe, i finally got it to work, then discovered that the input function doesn't seem to work properly when ran through the command prompt as opposed to in idle, or the interactive session. Any ideas why, or how to fix this? Edit: When i say not properly, I mean ...
[ "If you're trying to get a user string input, the function is named raw_input() (at least that's what it's called in Python 2.7). This code works as expected from cmdline using Python 3.2:\nidea = ''\nwhile idea != 'new':\n idea = input('...').strip()\n if idea == 'hit':\n print(\"It's not nice to hit...
[ 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005900009_python_python_3.x.txt
Q: Twisted as a client/server problems I'm using twisted to create a "client/server", a programme which act as a client to get some data, and as a server to re-send this data or just to send other data to clients. I'm using twistd and my code to initialize my factories look like that: application = service.Applicatio...
Twisted as a client/server problems
I'm using twisted to create a "client/server", a programme which act as a client to get some data, and as a server to re-send this data or just to send other data to clients. I'm using twistd and my code to initialize my factories look like that: application = service.Application('monitorD', uid=0, gid=0) factoryMonito...
[ "There are two things you should be able to change right off the bat. Get rid of the time.sleep(30) calls. Also, you're heavily using the threadpool so you'll likely want to increase the size of it. Every 30 seconds you're creating 5 threads and because the reactor threadpool size defaults to 5 any other threads...
[ 1 ]
[]
[]
[ "block", "client", "python", "twisted" ]
stackoverflow_0005900000_block_client_python_twisted.txt
Q: python & numpy: sum of an array slice I have 1-dimensional numpy array (array_) and a Python list (list_). The following code works, but is inefficient because slices involve an unnecessary copy (certainly for Python lists, and I believe also for numpy arrays?): result = sum(array_[1:]) result = sum(list_[1:]) Wh...
python & numpy: sum of an array slice
I have 1-dimensional numpy array (array_) and a Python list (list_). The following code works, but is inefficient because slices involve an unnecessary copy (certainly for Python lists, and I believe also for numpy arrays?): result = sum(array_[1:]) result = sum(list_[1:]) What's a good way to rewrite that?
[ "Slicing a numpy array doesn't make a copy, as it does in the case of a list.\nAs a basic example:\nimport numpy as np\nx = np.arange(100)\ny = x[1:5]\ny[:] = 1000\nprint x[:10]\n\nThis yields:\n[ 0 1000 1000 1000 1000 5 6 7 8 9]\n\nEven though we modified the values in y, it's just a view into the...
[ 15, 8, 3, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0005891523_arrays_numpy_python.txt
Q: Using variables in Python regular expression I'm parsing a file and looking in the lines for username-# where the username will change and there can be any number of digits [0-9] after the dash. I have tried nearly every combination trying to use the variable username in the regular expression. Am I even close wi...
Using variables in Python regular expression
I'm parsing a file and looking in the lines for username-# where the username will change and there can be any number of digits [0-9] after the dash. I have tried nearly every combination trying to use the variable username in the regular expression. Am I even close with something like re.compile('%s-\d*'%user)?
[ "Working as it should:\n>>> user = 'heinz'\n>>> import re\n>>> regex = re.compile('%s-\\d*'%user)\n>>> regex.match('heinz-1')\n<_sre.SRE_Match object at 0x2b27a18e3f38>\n>>> regex.match('heinz-11')\n<_sre.SRE_Match object at 0x2b27a2f7c030>\n>>> regex.match('heinz-12345')\n<_sre.SRE_Match object at 0x2b27a18e3f38>\...
[ 22, 3, 3, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005900683_python_regex.txt
Q: pygtk image fadein I have image1.png and image2.png when my app starts the image1.png is showed, after the app runs I need hide the image1.png and show image2.png using a fadein of image2.png over the image1.png how can I do that? I'm using python and pygtk also I can import PIL modules if is necesary A: Here...
pygtk image fadein
I have image1.png and image2.png when my app starts the image1.png is showed, after the app runs I need hide the image1.png and show image2.png using a fadein of image2.png over the image1.png how can I do that? I'm using python and pygtk also I can import PIL modules if is necesary
[ "Here's a quick and dirty pygtk app I just did for the fade-in effect. It was adapted from this C code:\nimport gtk\nimport gobject\nimport cairo\nimport sys\n\nclass PyApp(gtk.Window):\n\n def __init__(self):\n super(PyApp, self).__init__()\n\n self.set_title(\"Fade In\")\n self.resize(300...
[ 4, 1 ]
[]
[]
[ "fadein", "image", "pygtk", "python", "python_imaging_library" ]
stackoverflow_0005852705_fadein_image_pygtk_python_python_imaging_library.txt
Q: How can I debug (potentially C-library related) memory issues using 64-bit Python on Windows? I have a python program that processes image frames with Python 2.7, PIL, OpenCV, and numpy/scipy. To the best of my knowledge, it does not maintain any lists of previous frame. Nevertheless, memory consumption increase...
How can I debug (potentially C-library related) memory issues using 64-bit Python on Windows?
I have a python program that processes image frames with Python 2.7, PIL, OpenCV, and numpy/scipy. To the best of my knowledge, it does not maintain any lists of previous frame. Nevertheless, memory consumption increases steadily as the program processes more and more frames. There are several good discussions of mem...
[ "I've found the tools discussed here very helpful: http://mg.pov.lt/blog/hunting-python-memleaks.html\nThere is a version of his code here with some additions for measure numpy array sizes.\n", "I had a similar sort of problem tracking down a severe memory leak in a numpy/scipy heavy code where none of the usual...
[ 1, 1, 1 ]
[]
[]
[ "memory_management", "numpy", "profiling", "python", "scipy" ]
stackoverflow_0005760754_memory_management_numpy_profiling_python_scipy.txt
Q: how to find phrases in documents efficiently I have a large list of phrases (single and multiple words; some overlapping) and I have a lot of documents. In the end I only want to store a list of phrases (from the large phrase list) per document and not the whole documents. What's an efficient way to achive this? (...
how to find phrases in documents efficiently
I have a large list of phrases (single and multiple words; some overlapping) and I have a lot of documents. In the end I only want to store a list of phrases (from the large phrase list) per document and not the whole documents. What's an efficient way to achive this? (preferably in python) example: phrase_list = ['cat...
[ "Sounds like you need an indexer and search engine, like Lucene for Java. Perhaps the PyLucene port will be helpful.\n" ]
[ 2 ]
[]
[]
[ "language_agnostic", "python" ]
stackoverflow_0005901491_language_agnostic_python.txt
Q: Name of Current App in Google App Engine (Python) Using the Google App Engine Python API is there a way to access the name of the currently running application--i.e., the app name specified in your app.yaml file with application: foobar? A: import os appname = os.environ['APPLICATION_ID'] EDIT: I just noticed t...
Name of Current App in Google App Engine (Python)
Using the Google App Engine Python API is there a way to access the name of the currently running application--i.e., the app name specified in your app.yaml file with application: foobar?
[ "\nimport os\nappname = os.environ['APPLICATION_ID']\n\n\nEDIT: I just noticed this because I got a new upvote on it today (shame on you, upvoter!), but this is no longer correct.\nfrom google.appengine.api.app_identity import get_application_id\nappname = get_application_id()\n\nshould be used. The value in os.env...
[ 35 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005901653_google_app_engine_python.txt
Q: numpy.memmap for an array of strings? Is it possible to use numpy.memmap to map a large disk-based array of strings into memory? I know it can be done for floats and suchlike, but this question is specifically about strings. I am interested in solutions for both fixed-length and variable-length strings. The soluti...
numpy.memmap for an array of strings?
Is it possible to use numpy.memmap to map a large disk-based array of strings into memory? I know it can be done for floats and suchlike, but this question is specifically about strings. I am interested in solutions for both fixed-length and variable-length strings. The solution is free to dictate any reasonable file f...
[ "If all the strings have the same length, as suggested by the term \"array\", this is easily possible:\na = numpy.memmap(\"data\", dtype=\"S10\")\n\nwould be an example for strings of length 10.\nEdit: Since apparently the strings don't have the same length, you need to index the file to allow for O(1) item access....
[ 5, 2 ]
[]
[]
[ "large_data", "memory_mapped_files", "numpy", "python", "string" ]
stackoverflow_0005896747_large_data_memory_mapped_files_numpy_python_string.txt
Q: HOW to build a system which allows a user to submit jobs to a queue Using a combination of C, C++, Shell, Perl and/or Python I want to develop a system which allows a user to submit jobs to a queue (or queues). Jobs from the queue should be executed on one of a number of worker machines in an appropriate order. Th...
HOW to build a system which allows a user to submit jobs to a queue
Using a combination of C, C++, Shell, Perl and/or Python I want to develop a system which allows a user to submit jobs to a queue (or queues). Jobs from the queue should be executed on one of a number of worker machines in an appropriate order. The system should provide basic functionality. However in addition you may ...
[ "Why do you try to reinvent wheels? \nUse http://celeryproject.org/\n" ]
[ 3 ]
[]
[]
[ "jobs", "networking", "python", "queue", "system" ]
stackoverflow_0005901676_jobs_networking_python_queue_system.txt
Q: the bytes type in python 2.7 and PEP-358 According to PEP 358, a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case. However, my python 2.7 says otherwise >>> bytes([1,2,3]) '[1, 2, 3]' >>> bytes([280]) '[280]' >>> bytes is str True >>> bytes <type 'str'> Does anyon...
the bytes type in python 2.7 and PEP-358
According to PEP 358, a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case. However, my python 2.7 says otherwise >>> bytes([1,2,3]) '[1, 2, 3]' >>> bytes([280]) '[280]' >>> bytes is str True >>> bytes <type 'str'> Does anyone have a clue on the reason why the PEP is dec...
[ "The new bytes type is 3.x only. The 2.x bytes built-in is just an alias to the str type. There is no new type called bytes in 2.x; Just a new alias and literal syntax for str.\nHere's the documentation snippet everybody loves:\n\nPython 2.6 adds bytes as a synonym for\n the str type, and it also supports the\n b...
[ 53, 40, 3 ]
[]
[]
[ "python", "types" ]
stackoverflow_0005901706_python_types.txt
Q: Run Django unit tests from custom management command I used to have a standalone script with some unit tests to test data in our database. I did not use the builtin Django testing tool, as that would create an empty testing database, which is not what I want. In that script, I created three different classes exten...
Run Django unit tests from custom management command
I used to have a standalone script with some unit tests to test data in our database. I did not use the builtin Django testing tool, as that would create an empty testing database, which is not what I want. In that script, I created three different classes extending unittest.TestCase containing some test functions that...
[ "I'm sorry for not having searched for an answer long enough before asking, but I found the solution to this problem myself in another Stackoverflow answer:\n\nHow to run django unit-tests on production database?\n\nEssentially, instead of unittest.main() the following code can be used:\nsuite = unittest.TestLoader...
[ 2, 1 ]
[]
[]
[ "django", "python", "testing", "unit_testing" ]
stackoverflow_0005831994_django_python_testing_unit_testing.txt
Q: django queryset include more columns in select statement I been trying to create a backward relation using queryset and the joining is working fine, accept that its not including the other joined table in the selected columns. Below is my models, queryset and query.str() print class Main(models.Model): slug ...
django queryset include more columns in select statement
I been trying to create a backward relation using queryset and the joining is working fine, accept that its not including the other joined table in the selected columns. Below is my models, queryset and query.str() print class Main(models.Model): slug = models.SlugField() is_active = models.BooleanField(...
[ "The relationship from Main to List is a backwards ForeignKey (ie the FK is on List pointing at Main), and select_related doesn't work that way. When you think about it, this is correct: there are many Lists for each Main, so it doesn't make sense to say \"give me the one List for this Main\", which is what select_...
[ 2, 0 ]
[]
[]
[ "django", "django_models", "django_queryset", "orm", "python" ]
stackoverflow_0005889751_django_django_models_django_queryset_orm_python.txt
Q: What's the best way to add a specific user-based context to every page in a project To give the question some context, let's say I have 10 views with each view function decorated to include extra context, but I want this context to be in all views (see the problem below). Is there a better way to do this instead o...
What's the best way to add a specific user-based context to every page in a project
To give the question some context, let's say I have 10 views with each view function decorated to include extra context, but I want this context to be in all views (see the problem below). Is there a better way to do this instead of putting the decorator on every view function? It just seems silly/repetitive to have th...
[ "Context processors.\n" ]
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005902339_django_python.txt
Q: Colorama AssertionError in Python 3.2 I've recently started using Python 3.2 and have never attempted programming before. I copied the colorama folder to the lib directory in C:\Python32\lib and then made the following code in my attempt at a text-based adventure game: import colorama from colorama import For...
Colorama AssertionError in Python 3.2
I've recently started using Python 3.2 and have never attempted programming before. I copied the colorama folder to the lib directory in C:\Python32\lib and then made the following code in my attempt at a text-based adventure game: import colorama from colorama import Fore, Back, Style colorama.init() not...
[ "It seems to be an issue of : colorama 0.1.18 with IDLE try in the real python interpretor.\n" ]
[ 3 ]
[]
[]
[ "assertion", "colorama", "module", "python" ]
stackoverflow_0005902233_assertion_colorama_module_python.txt
Q: Django - sort by userprofile field in admin I figured out how to get UserProfile information to appear in my admin field thanks to some help from you guys. Now I want to come up with a way to properly sort those fields. I'm close. class EmployerProfileAdmin(UserAdmin): inlines = [EmployerProfileInline, ] ...
Django - sort by userprofile field in admin
I figured out how to get UserProfile information to appear in my admin field thanks to some help from you guys. Now I want to come up with a way to properly sort those fields. I'm close. class EmployerProfileAdmin(UserAdmin): inlines = [EmployerProfileInline, ] def company(self): return self.get_profi...
[ "As Honza said, what are you trying to order? \nIn general, the order in the admin change list page will follow the model's default ordering, or can be specified by ModelAdmin.ordering as a list or tuple. \n", "Perhaps you could try using the model__field approach?\nAs others say we don't know the whole problem, ...
[ 1, 1 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0004571376_django_django_admin_django_models_python.txt
Q: Parsing an ISO datetime in Python Possible Duplicate: Converting string to datetime object in python Given the below Python import datetime >>> a '2011-05-04 16:20:09 -0700' >>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S %z") Traceback (most recent call last): File "<stdin>", line 1, in <module> File ...
Parsing an ISO datetime in Python
Possible Duplicate: Converting string to datetime object in python Given the below Python import datetime >>> a '2011-05-04 16:20:09 -0700' >>> datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S %z") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/_strptime.py", lin...
[ "Here is the complete story:\nhttp://bugs.python.org/issue6641\nand related:\nConverting string with UTC offset to a datetime object\n" ]
[ 7 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0005902460_datetime_python.txt
Q: matplotlib bar chart with dates I know about plot_date() but is there a bar_date() out there? The general method would be to use set_xticks and set_xticklabels, but I'd like something that can handle time scales from a few hours out to a few years (this means involving the major and minor ticks to make things read...
matplotlib bar chart with dates
I know about plot_date() but is there a bar_date() out there? The general method would be to use set_xticks and set_xticklabels, but I'd like something that can handle time scales from a few hours out to a few years (this means involving the major and minor ticks to make things readable I think). Edit: I realized that ...
[ "All plot_date does is plot the function and the call ax.xaxis_date().\nAll you should need to do is this:\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\n\nx = [datetime.datetime(2010, 12, 1, 10, 0),\n datetime.datetime(2011, 1, 4, 9, 0),\n datetime.datetime(2011, 5, 5, 9, 0)]\ny = [4,...
[ 61 ]
[]
[]
[ "bar_chart", "datetime", "matplotlib", "python" ]
stackoverflow_0005902371_bar_chart_datetime_matplotlib_python.txt
Q: Selecting and sorting on unique foreign key with Django I have a table called 'speed' which has a foreign key to a user row and an integer field called 'speed'. What I would like to do is get the top speed for unique users. For example: If speed contained id | speed | user_id | 1 | 40 | 1 ...
Selecting and sorting on unique foreign key with Django
I have a table called 'speed' which has a foreign key to a user row and an integer field called 'speed'. What I would like to do is get the top speed for unique users. For example: If speed contained id | speed | user_id | 1 | 40 | 1 | 2 | 50 | 1 | 3 | 10 | ...
[ "This is not quite what you asked, but gives you the list of user IDs and their associated max speeds:\nfrom django.db.models import Max\nSpeed.objects.values_list('user').annotate(Max('speed'))\n\nThis might be more useful: a list of User objects with their max speeds:\nUser.objects.all().annotate(Max('speed__spee...
[ 2 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0005902443_django_python_sql.txt
Q: Keeping the ajax call alive when calling the Tornado server I'm trying to write my first tornado application. The sample example for tornado, shows the below code, however it seems that once the "MainHandler" function returns, the connection between the client & this server will be lost. I want the server to cont...
Keeping the ajax call alive when calling the Tornado server
I'm trying to write my first tornado application. The sample example for tornado, shows the below code, however it seems that once the "MainHandler" function returns, the connection between the client & this server will be lost. I want the server to continuously push data, as and when it becomes available. How does on...
[ "You might want to use a websocket if you want to keep the connection open. Something like:\nLISTENERS = []\n\nclass RealtimeHandler(tornado.websocket.WebSocketHandler):\n def open(self):\n LISTENERS.append(self)\n\n def on_close(self):\n LISTENERS.remove(self)\n\napplication = tornado.web.Appli...
[ 3 ]
[]
[]
[ "comet", "nonblocking", "python", "tornado" ]
stackoverflow_0005902684_comet_nonblocking_python_tornado.txt
Q: Renderer for 3D model (points/lines) in Python I have a 3d model that consists of points, lines and balls in space. For debugging, it would be nice to render these objects in real time and rotateable. What are my easiest options to achieve this in python? Since I know nothing about graphical programming, I'd like...
Renderer for 3D model (points/lines) in Python
I have a 3d model that consists of points, lines and balls in space. For debugging, it would be nice to render these objects in real time and rotateable. What are my easiest options to achieve this in python? Since I know nothing about graphical programming, I'd like to write as litte boilerplate code as possible.
[ "The easiest way to get 3d graphics on screen in python is VPython, though if your model is stored in a CAD file format, you'll need some other library to load the data. With just VPython, you will either need to hard-code the model or implement your own loader.\n", "Two options I'd consider myself (depends what ...
[ 4, 4, 0 ]
[]
[]
[ "3d", "python" ]
stackoverflow_0005902448_3d_python.txt
Q: numpy slicing that would always return an array Given a numpy array and a __getitem__-type index, is there an idiomatic way to get the corresponding slice of the array, that would always return an array and never a scalar? Examples of valid indices include: an int, a slice, an ellipsis or a tuple of the above. Say...
numpy slicing that would always return an array
Given a numpy array and a __getitem__-type index, is there an idiomatic way to get the corresponding slice of the array, that would always return an array and never a scalar? Examples of valid indices include: an int, a slice, an ellipsis or a tuple of the above. Say I have an array like this: a = np.array([[1,2],[3,4]...
[ "If you just want to return a single-element array in cases where a scalar would otherwise be returned, why not just use numpy.atleast_1d on the result of the slice?\nE.g.:\nimport numpy as np\nx = np.arange(100).reshape(10,10)\nprint x[0,0]\nprint np.atleast_1d(x[0,0])\nprint np.atleast_1d(x[:,:3])\n\n", "Here i...
[ 6, 2, 0 ]
[]
[]
[ "numpy", "python", "slice" ]
stackoverflow_0005902108_numpy_python_slice.txt
Q: Django: Integrity error when deleting an object with a 'through' many-to-many field I am using a through table in a many-to-many field: class EmailType(models.Model): name = models.CharField(max_length=200) class Email(models.Model): email = models.EmailField(max_length=200) type = models.Fore...
Django: Integrity error when deleting an object with a 'through' many-to-many field
I am using a through table in a many-to-many field: class EmailType(models.Model): name = models.CharField(max_length=200) class Email(models.Model): email = models.EmailField(max_length=200) type = models.ForeignKey(EmailType,blank=True,null=True,default='') class EntityEmail(Email): ...
[ "You can overwrite Model.delete() method on the Entity model to match the on_delete functionality, if this is really what you are after. \n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "mysql", "python" ]
stackoverflow_0005900115_django_django_models_mysql_python.txt
Q: How to add message to state in OpenERP I have a very simple question. How to add own message to state on status bar? A: It looks like the form class in the client has a message_state() method that displays a message in the status bar. If you look through the client/bin/modules/gui/window/form.py file, you can fi...
How to add message to state in OpenERP
I have a very simple question. How to add own message to state on status bar?
[ "It looks like the form class in the client has a message_state() method that displays a message in the status bar. If you look through the client/bin/modules/gui/window/form.py file, you can find several calls. I didn't see any easy way to set that message from within a standard module, so you might have to hack t...
[ 0, 0 ]
[]
[]
[ "notifications", "openerp", "python" ]
stackoverflow_0005659117_notifications_openerp_python.txt
Q: the loop does not execute correctly class cga(object): '''''' def __int__(self,i,o): '''''' self.i = i self.o = o def get(self): '''''' self.i = [] c = raw_input("How many courses you have enrolled in this semester?:") cout = 0 while cout...
the loop does not execute correctly
class cga(object): '''''' def __int__(self,i,o): '''''' self.i = i self.o = o def get(self): '''''' self.i = [] c = raw_input("How many courses you have enrolled in this semester?:") cout = 0 while cout < c: n = raw_input("plz ente...
[ "The problem is, that raw_input returns a string (not a number), and for some odd historical reasons, strings can be compared (for ordering) to any other kind of object by default, but the results are... odd. \nPython 2.6.5 (r265:79063, Oct 28 2010, 20:56:23) \n[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] ...
[ 6, 2 ]
[]
[]
[ "comparison", "debugging", "python", "raw_input", "while_loop" ]
stackoverflow_0005903093_comparison_debugging_python_raw_input_while_loop.txt
Q: Wrong encoding with Python BeautifulSoup + MySql I'm working with the BeautifulSoup python library. I used the urllib2 library to download the HTML code from a page, and then I have parsed it with BeautifulSoup. I want to save some of the HTML content into a MySql table, but I'm having some problems with the encod...
Wrong encoding with Python BeautifulSoup + MySql
I'm working with the BeautifulSoup python library. I used the urllib2 library to download the HTML code from a page, and then I have parsed it with BeautifulSoup. I want to save some of the HTML content into a MySql table, but I'm having some problems with the encoding. The MySql table is encoded with 'utf-8' charset. ...
[ "You have correct UTF-8 data coming out of BeautifulSoup, but it's being stored in a normal string type, not python's native unicode string type. I think this is what you need to do:\ncodecs.decode(your_string, 'utf-8')\n\nAnd then the string should be the proper data type and encoding to send to mysql.\nAn example...
[ 3, 2 ]
[]
[]
[ "beautifulsoup", "encoding", "mysql", "python", "urllib2" ]
stackoverflow_0005902914_beautifulsoup_encoding_mysql_python_urllib2.txt
Q: What are the advantages of using with for opening files on Python 3? What are the real performance advantages of using with open(__file__, 'r') as f: instead of using: open(__file__,'r') in Python 3 for both writing and reading files? A: Using with means that the file will be closed as soon as you leave the bl...
What are the advantages of using with for opening files on Python 3?
What are the real performance advantages of using with open(__file__, 'r') as f: instead of using: open(__file__,'r') in Python 3 for both writing and reading files?
[ "Using with means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need.\n", "What the with statement basically does is take advantage of two new magic keywords on an object: __...
[ 12, 9, 2, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0005902432_python_python_3.x.txt
Q: python: cairoplot gantt_chart rendering problems looks like gantt_chart() doesn't work properly for following set of data: tg_p = [ (0, 12), (0, 5), (0,13) ] tg_v = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'] tg_h = [ 'test', 'test2', 'test3' ] tg_c = [ (1.0, 0.0, 0.0), (1.0...
python: cairoplot gantt_chart rendering problems
looks like gantt_chart() doesn't work properly for following set of data: tg_p = [ (0, 12), (0, 5), (0,13) ] tg_v = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14'] tg_h = [ 'test', 'test2', 'test3' ] tg_c = [ (1.0, 0.0, 0.0), (1.0, 0.7, 0.0), (0.0, 1.0, 0.0) ] CairoPlot.gantt_chart('...
[ "There is a bug report here: https://bugs.launchpad.net/cairoplot/+bug/274181\ntry setting the tuple in lists, according to the reporter it should work.\n\nPassing data like:\ndata = [(0,3), (4,5), (8,10)]\nmakes Gantt Chart crash, plotting all the pieces on the same line.\nThis, however, works:\ndata = [(0,3), [(4...
[ 3 ]
[]
[]
[ "cairoplot", "charts", "python", "rendering" ]
stackoverflow_0004154458_cairoplot_charts_python_rendering.txt
Q: Specifying Django Query Filters at Run Time How do I specify an arbitrary Django query filter at runtime? Normally one uses filters like so... query_set = MyModel.objects.filter(name__iexact='foobar') But what if I have the query filter specifier contained in a string? query_specifier = "name_iexact='foobar'" que...
Specifying Django Query Filters at Run Time
How do I specify an arbitrary Django query filter at runtime? Normally one uses filters like so... query_set = MyModel.objects.filter(name__iexact='foobar') But what if I have the query filter specifier contained in a string? query_specifier = "name_iexact='foobar'" query_set = MyModel.objects.filter(query_specifier) ...
[ "query_specifier = {\n 'name__iexact': 'foobar'\n}\nquery_set = MyModel.objects.filter(**query_specifier)\n\n" ]
[ 9 ]
[]
[]
[ "django", "django_queryset", "python", "runtime" ]
stackoverflow_0005903384_django_django_queryset_python_runtime.txt
Q: Convert C# decryption to Python PyDes I'm having trouble converting code from C# to Python. Over at Martijn's C# Blog is an excellent program for encrypt/decrypt [enclosed below] but I can't get it to convert directly to the python version pyDes [sample below] public static string DecryptString(string Message...
Convert C# decryption to Python PyDes
I'm having trouble converting code from C# to Python. Over at Martijn's C# Blog is an excellent program for encrypt/decrypt [enclosed below] but I can't get it to convert directly to the python version pyDes [sample below] public static string DecryptString(string Message, string Passphrase) { byte[] R...
[ "Never mind --- figured it out. \nIf you change this line in pyDes\nprint \"Encrypted: %r\" % d\n\nto \nprint \"Encrypted: %r\" % d.encode('base64')\n\nthen the code matches up exactly.\nTo compare, run the original code from Martijn's site: [Output]\n\nMessage: This world is round, not flat, don't believe them!\nP...
[ 10 ]
[]
[]
[ "c#", "encryption", "python", "tripledes" ]
stackoverflow_0005903135_c#_encryption_python_tripledes.txt
Q: simple url format for crawling youtube categories? Is there a simple form like http://www.youtube.com/category/horror or even something with a simple get parameter that would allow one get to the different youtube category homes? Note I am aware of the api...I am asking about a direct url format that would allow o...
simple url format for crawling youtube categories?
Is there a simple form like http://www.youtube.com/category/horror or even something with a simple get parameter that would allow one get to the different youtube category homes? Note I am aware of the api...I am asking about a direct url format that would allow one visit different categories with python or php or some...
[ "Youtube category homes?\nTake a look to see if the following types of pages are what you're looking for:\n\nYoutube Category Home - Autos & Vehicles\nYoutube Category Home - Gaming (Hurray!)\nBoth use the 'c' variable to denote a category.. The URL is youtube.com/categories .\n\nIf you want, the second best option...
[ 3 ]
[]
[]
[ "curl", "php", "python", "web_crawler", "youtube" ]
stackoverflow_0005903440_curl_php_python_web_crawler_youtube.txt
Q: Python library to generate flash files I was wondering if there is any Python library out there which would allow me to generate Flash files (a simple slide show of a bunch of images). I tried installing Ming but was running into some problems, so was wondering if there is any other library out there with better...
Python library to generate flash files
I was wondering if there is any Python library out there which would allow me to generate Flash files (a simple slide show of a bunch of images). I tried installing Ming but was running into some problems, so was wondering if there is any other library out there with better documentation.
[ "For this you can do a workaround unless you find a python library for it.\nYou can use Flex SDK and the command line compiler (found in /bin).\nBasically, setup the flash actionscript code with python, then compile it to an swf.\nIf you have images in a folder, then\n[Embed(source=\"IMAGE-NAME\")]\nvar Image:Class...
[ 3 ]
[]
[]
[ "flash", "python" ]
stackoverflow_0005768669_flash_python.txt
Q: Handling the different results from parsedatetime I'm trying to learn python after spending the last 15 or so years working only in Perl and only occasionally. I can't understand how to handle the two different kinds of results from the parse method of Calendar.parse() from parsedatetime Given this script: #!/usr/...
Handling the different results from parsedatetime
I'm trying to learn python after spending the last 15 or so years working only in Perl and only occasionally. I can't understand how to handle the two different kinds of results from the parse method of Calendar.parse() from parsedatetime Given this script: #!/usr/bin/python import parsedatetime.parsedatetime as pdt i...
[ "I know this is an old question but I ran into this yesterday and the answer here is incomplete (it will fail in the case that parse() returns a datetime).\nFrom the parsedatetime docs:\nparse() returns a tuple ( result, type ) where type specifies one of:\n 0 = not parsed at all\n 1 = parsed as a date (of type...
[ 16, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001810432_python.txt
Q: Problems with Snow Leopard, Django & PIL I am having some trouble getting Django & PIL work properly since upgrading to Snow Leopard. I have installed freetype, libjpeg and then PIL, which tells me: --- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok but when I try t...
Problems with Snow Leopard, Django & PIL
I am having some trouble getting Django & PIL work properly since upgrading to Snow Leopard. I have installed freetype, libjpeg and then PIL, which tells me: --- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok but when I try to upload a jpeg through the django admin inter...
[ "Cato\nI had the same experience with Leopard 10.5.x\nHere is what I did to fix it, (may not work for you).\n\nGo to your PIL working folder (where you unzipped PIL)\ncd to your build folder\ncd to your lib.macosx-10.* folder (specific to your os)\nremove *.so\ncd back to your PIL build folder\n(I logged in as su ...
[ 14, 5, 3 ]
[]
[]
[ "django", "libjpeg", "osx_snow_leopard", "python", "python_imaging_library" ]
stackoverflow_0001398701_django_libjpeg_osx_snow_leopard_python_python_imaging_library.txt
Q: Python: How to resolve IndentationError My IndentationError just seems so irresolvable. http://pastebin.com/AFdnYcRc. #!/usr/bin/env python import os import glob import shutil import mutagen from sys import exit musicdir = raw_input("What directory are the music files located in? : ") musfile = glob.glob(musicdir...
Python: How to resolve IndentationError
My IndentationError just seems so irresolvable. http://pastebin.com/AFdnYcRc. #!/usr/bin/env python import os import glob import shutil import mutagen from sys import exit musicdir = raw_input("What directory are the music files located in? : ") musfile = glob.glob(musicdir + '/' + "*.mp3") musfile1 = glob.glob(musicd...
[ "You have a try block (starting on line 30) with no except\n", "I don't see an except block for your second try. That should break it, but I don't think it gives you a IndendationError so you might have more problems.\n", "Have you ever looked at pep8 ( link ) it automatically checks your code for errors. \ntes...
[ 13, 5, 5, 2 ]
[]
[]
[ "indentation", "python" ]
stackoverflow_0005903739_indentation_python.txt
Q: Convert Double to Single without loss of precision in MATLAB I don't think this is possible, hence I decided to ask here to see as googling around hasn't returned any results that hint that I can do so. Especially after reading this: Can doubles be used to represent a 64 bit number without loss of precision Thoug...
Convert Double to Single without loss of precision in MATLAB
I don't think this is possible, hence I decided to ask here to see as googling around hasn't returned any results that hint that I can do so. Especially after reading this: Can doubles be used to represent a 64 bit number without loss of precision Though my numbers can be held in 32bit as the example below shows. But ...
[ "A single can hold integer numbers up to 2^24 (16,777,216) without loss of precision - some bits are required for the sign and the exponent .\nIn other words, no, there is no way that you can make a number larger than 2^24 fit into a single without error (note that it can hold some larger numbers, as long as they c...
[ 4, 2, 0 ]
[]
[]
[ "cuda", "double", "matlab", "python" ]
stackoverflow_0004513346_cuda_double_matlab_python.txt
Q: How to edit filters list of a queryset This feature is used in a view where I list search results. In my search form, I have some ModelChoiceFields to search by foreign keys. Usual workflow mean turn our current search more and more precise, so to disable a lot of not pertinent results, I'm trying to remove entrie...
How to edit filters list of a queryset
This feature is used in a view where I list search results. In my search form, I have some ModelChoiceFields to search by foreign keys. Usual workflow mean turn our current search more and more precise, so to disable a lot of not pertinent results, I'm trying to remove entries which would return no result if no other s...
[ "Short answer:\nNo, you cannot do that.\nLong answer:\nTheoretically, it may be possible (to some extent anyway) but certainly not advisable. \n(I have not fully studied the django source, so what follows is a result of a simple climb up the call tree.)\nLooking at the source for QuerySet, filter() and exclude() re...
[ 8, 8 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005220433_django_python.txt
Q: Smooth Transition Between Frames in WxPython I wonder if it is possible to make transitions between frames smoother in WxPython. For now I use the classical "self.Destroy" and "self.GetParent().Show()" methods to implement this task. But transitions are sharp. And it just doesnt look nice to my eyes. Any other sug...
Smooth Transition Between Frames in WxPython
I wonder if it is possible to make transitions between frames smoother in WxPython. For now I use the classical "self.Destroy" and "self.GetParent().Show()" methods to implement this task. But transitions are sharp. And it just doesnt look nice to my eyes. Any other suggestions? Thanks in advance.
[ "I don't know why you're Destroying the frame. Just hide / show it. Or use a \"fade in\" / \"fade out\" effect to make it look cooler. When it fades out all the way, hide the frame and vice-versa. See http://www.blog.pythonlibrary.org/2008/04/14/doing-a-fade-in-with-wxpython/ for an example of the fading effect.\n"...
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0005896366_python_wxpython.txt
Q: Disable -webkit-transform for webkit2png When I try to take a screenshot of an element using webkit2png, if the element uses webkit-transform, often the screenshot will be blank. This is for a research project, where I'm trying to take a thumbnail of google streetview so I can quickly scan which location I need to...
Disable -webkit-transform for webkit2png
When I try to take a screenshot of an element using webkit2png, if the element uses webkit-transform, often the screenshot will be blank. This is for a research project, where I'm trying to take a thumbnail of google streetview so I can quickly scan which location I need to adjust. Note: We have a special ToS from goo...
[ "Answer submitted on github by https://github.com/Wevah\nIf you can drop support for OS X < 10.4, you can replace\nbitmapdata = AppKit.NSBitmapImageRep.alloc()\nbitmapdata.initWithFocusedViewRect_(view.bounds())\nview.unlockFocus()\n\nwith\nbitmapdata = view.bitmapImageRepForCachingDisplayInRect_(view.bounds())\nvi...
[ 0 ]
[]
[]
[ "jquery", "python", "screen_scraping", "webkit" ]
stackoverflow_0005837452_jquery_python_screen_scraping_webkit.txt
Q: Google App Engine Development Task Queue Not Running I'm adding Tasks to my development default task queue like so... task = Task(params={'id':'foo','name':'bar'}, countdown=0, url = '/foobar', ) task.add() But my Tasks just sit in the default queue and don't execute. If I run them manually by going to /_...
Google App Engine Development Task Queue Not Running
I'm adding Tasks to my development default task queue like so... task = Task(params={'id':'foo','name':'bar'}, countdown=0, url = '/foobar', ) task.add() But my Tasks just sit in the default queue and don't execute. If I run them manually by going to /_ah/admin/tasks?queue=default and clicking the "Run" button...
[ "According to this question, automatic task execution only works if you're running Python 2.5. Are you running something higher?\nFailing that, check to make sure you're using at least version 1.3.4 of the SDK, and you're not passing --disable_task_running to dev_appserver.py.\n" ]
[ 4 ]
[]
[]
[ "django", "django_nonrel", "djangoappengine", "google_app_engine", "python" ]
stackoverflow_0005904552_django_django_nonrel_djangoappengine_google_app_engine_python.txt
Q: Why is the minimal (non-greedy) match affected by the end of string character '$'? EDIT: remove original example because it provoked ancillary answers. also fixed the title. The question is why the presence of the "$" in the regular expression effects the greedyness of the expression: Here is a simpler example: >...
Why is the minimal (non-greedy) match affected by the end of string character '$'?
EDIT: remove original example because it provoked ancillary answers. also fixed the title. The question is why the presence of the "$" in the regular expression effects the greedyness of the expression: Here is a simpler example: >>> import re >>> str = "baaaaaaaa" >>> m = re.search(r"a+$", str) >>> m.group() 'aaaaaaa...
[ "Matches are \"ordered\" by \"left-most, then longest\"; however \"longest\" is the term used before non-greedy was allowed, and instead means something like \"preferred number of repetitions for each atom\". Being left-most is more important than the number of repetitions. Thus, \"a+?$\" will not match the last ...
[ 4, 4, 4, 1, 1, 0 ]
[]
[]
[ "non_greedy", "python", "regex" ]
stackoverflow_0005876989_non_greedy_python_regex.txt