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: python: class attributes and instance attributes I'm new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code: >>> class Foo: ... a=1 ... >>> f1=Foo(); >>> f2=Foo() >>> f1.a 1 >>> f1.a=5 >>> f1.a 5 >>> f2.a 1 Shouldn't f2.a a...
python: class attributes and instance attributes
I'm new to python and learned that class attributes are like static data members in C++. However, I got confused after trying the following code: >>> class Foo: ... a=1 ... >>> f1=Foo(); >>> f2=Foo() >>> f1.a 1 >>> f1.a=5 >>> f1.a 5 >>> f2.a 1 Shouldn't f2.a also equal 5? If a is defined as a list instead of an i...
[ "Python's class attributes and object attributes are stored in separate dictionaries. For the object f1, these can be accessed via, respectively, f1.__class__.__dict__ and f1.__dict__. Executing print f1.__class__ is Foo will output True.\nWhen you reference the attribute of an object, Python first tries to look ...
[ 9, 8, 7, 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007548546_python.txt
Q: Refresh output line containing download percentage I'm writing a script that has to download several files from the www. To make it more expressive I've just added a download hook to calculate the downloading percentage of the file that has being downloaded. Printing it out on the terminal produces a lot of output...
Refresh output line containing download percentage
I'm writing a script that has to download several files from the www. To make it more expressive I've just added a download hook to calculate the downloading percentage of the file that has being downloaded. Printing it out on the terminal produces a lot of output because I rewrite the same line each time the percentag...
[ "You need curses:\nhttp://docs.python.org/howto/curses.html\n", "Use \\r (carriage return) and write directly to the terminal with sys.stdout.write:\nimport time\nimport sys\nfor i in range(101):\n sys.stdout.write('%3d%%\\r' % i)\n time.sleep(.1)\n\nOr a little more Python 3-ish:\nimport time\nfor i in ran...
[ 2, 2 ]
[]
[]
[ "bash", "python", "python_3.x" ]
stackoverflow_0007548775_bash_python_python_3.x.txt
Q: Converting adjectives and adverbs to their noun forms I am experimenting with word sense disambiguation using wordnet for my project. As a part of the project, I would like to convert a derived adjective or an adverb form to it's root noun form. For example beautiful ==> beauty wonderful ==> wonder How can I ach...
Converting adjectives and adverbs to their noun forms
I am experimenting with word sense disambiguation using wordnet for my project. As a part of the project, I would like to convert a derived adjective or an adverb form to it's root noun form. For example beautiful ==> beauty wonderful ==> wonder How can I achieve this? Is there any other dict other than wordnet that ...
[ "Search google or SO for terms like 'stemming' and 'lemmatization', these terms might help you get what you are looking for.\nFor example, go to http://qaa.ath.cx/porter_js_demo.html and enter the words 'beautiful' and 'beauty', and you will see they both stem to the same token.\nPorter stemmer essentially removes ...
[ 6 ]
[]
[]
[ "linguistics", "nlp", "python", "wordnet" ]
stackoverflow_0007548479_linguistics_nlp_python_wordnet.txt
Q: why would spaces in a Python tuple matter? I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks! jcomeau@intrepid:/tmp$ cat hav...
why would spaces in a Python tuple matter?
I've been getting weird results and I finally noticed that my habit of putting spaces in a tuple is causing the problem. If you can reproduce this problem and tell me why it works this way, you would be saving what's left of my hair. Thanks! jcomeau@intrepid:/tmp$ cat haversine.py #!/usr/bin/python def dms_to_float(deg...
[ "The spaces should make no difference. The difference is due to the case: SW vs Sw.\nYou don't check for SW here: \ncompass in ['S', 'W', 'Sw']] \n\nPerhaps change it to this:\ncompass.upper() in ['S', 'W', 'SW']] \n\n", "Presuming that the \"degrees\" relate to degrees of latitude or longitude, I can't imagine w...
[ 12, 0 ]
[]
[]
[ "iterable_unpacking", "python" ]
stackoverflow_0007548562_iterable_unpacking_python.txt
Q: How can I toy with this .py file? I'm learning Python just so I can tinker with the files from AIMA easily. I know Java and C++, but I find the AIMA code on the repositories to be too obfuscated. The Python code looks simpler and more elegant...yet, I don't know Python. I wanna import the functions in search.py. ...
How can I toy with this .py file?
I'm learning Python just so I can tinker with the files from AIMA easily. I know Java and C++, but I find the AIMA code on the repositories to be too obfuscated. The Python code looks simpler and more elegant...yet, I don't know Python. I wanna import the functions in search.py. I tried creating a search2.py file li...
[ "When you import search, you define the name search, as a module created from executing search.py. If in there is a class called Problem, you access it as search.Problem:\nimport search\n\nclass Problem2(search.Problem):\n pass\n\nAn alternative is to define Problem with this statement:\nfrom search import Prob...
[ 7, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007548895_python.txt
Q: Virtualenvwrapper.sh functions not available in bash shell I'm doing a new install of virtualenvwrapper, and for some reason after running virtualenvwrapper.sh it's functions aren't available. $ virtualenvwrapper.sh creating..... $ workon workon: command not found I know that it's running, aside from the successf...
Virtualenvwrapper.sh functions not available in bash shell
I'm doing a new install of virtualenvwrapper, and for some reason after running virtualenvwrapper.sh it's functions aren't available. $ virtualenvwrapper.sh creating..... $ workon workon: command not found I know that it's running, aside from the successful creation of all the VE files, I've wrapped some of the functi...
[ "Oh I see, the correct thing to do is:\n$ source virtualenvwrapper.sh\n\nit was on my PATH, and getting run in a subshell, I guess.\n" ]
[ 7 ]
[]
[]
[ "bash", "python", "virtualenvwrapper" ]
stackoverflow_0007548893_bash_python_virtualenvwrapper.txt
Q: Python socket data returns object. How to regexp it? I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((soc...
Python socket data returns object. How to regexp it?
I'm writing a basic html-proxy in python (3), and up to now I'm not using prebuild classes like http.server. I'm just starting a socket which accepts connection: self.listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.listen_socket.bind((socket.gethostname(), 4321)) self.listen_socket.listen(5) (a, ...
[ "You need to include an encoding when converting to a string, for example use:\n>>> str(b'GET http://...', 'UTF-8')\n'GET http://...'\n\nIf you don't use an encoding then as you've discovered you get something a little less helpful:\n>>> str(b'GET http://...')\n\"b'GET http://...'\"\n\n", "Also, you might want to...
[ 3, 1, 0 ]
[]
[]
[ "http_headers", "proxy", "python", "python_3.x", "sockets" ]
stackoverflow_0002341972_http_headers_proxy_python_python_3.x_sockets.txt
Q: how to run a python file on a linux server as a page I want to begin with the fact that I know nothing about linux, and I found a script that I would like to run on my server as a page, but when I goto the .py file it downloads the file!!! how am I suppose to run it?? am I suppose to use a php file and do a comman...
how to run a python file on a linux server as a page
I want to begin with the fact that I know nothing about linux, and I found a script that I would like to run on my server as a page, but when I goto the .py file it downloads the file!!! how am I suppose to run it?? am I suppose to use a php file and do a command to run the file? Thanks in advance
[ "This may be quite easy (and there's certainly no need to employ PHP here)!\nGiven a trivial Python script:\n> cat cgi-bin/test.py\n#!/usr/bin/env python\n\nprint '''Content-Type: text/html\n\n<html>\n <head>\n <title>Hello from Python</title>\n </head>\n <body>\n <h2>Hello from Python</h2>\n...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007548826_python.txt
Q: Flash-Selenium and Python I want to try Flash-Selenium with the python driver, however I have some concerns regarding the available python extension, it seems aged and there is no example on how to use it... Is there anybody who is using it? Any example on how to use it ? A: Example taken from FlashSelenium page...
Flash-Selenium and Python
I want to try Flash-Selenium with the python driver, however I have some concerns regarding the available python extension, it seems aged and there is no example on how to use it... Is there anybody who is using it? Any example on how to use it ?
[ "Example taken from FlashSelenium page:\nfrom com.thoughtworks.selenium.FlashSelenium import FlashSelenium\nfrom com.thoughtworks.selenium.selenium import selenium\n\nurl = \"http://flashselenium.t35.com/colors.html\"\nbrowserType = \"*firefox\"\n\nselenium = selenium(\"localhost\", 4444, browserType, url)\nseleniu...
[ 1 ]
[]
[]
[ "python", "selenium", "selenium_rc" ]
stackoverflow_0001975244_python_selenium_selenium_rc.txt
Q: Check files in current directory How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops ...
Check files in current directory
How can I tell python to scan the current directory for a file called "filenames.txt" and if that file isn't there, to extract it from a zip file called "files.zip"? I know how to work zipfile, I just don't know how to scan the current directory for that file and use if/then loops with it..
[ "import os.path\ntry: \n os.path.isFile(fname)\n # play with the file\nexcept:\n # unzip file\n\n", "import os, zipfile\nif 'filenames.txt' in os.listdir('.'):\n print 'file is in current dir'\nelse:\n zf = zipfile.ZipFile('files.zip')\n zf.extract('filenames.txt')\n\n", "From the documenta...
[ 5, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007549403_python.txt
Q: Passing output from subprocess.Popen to a if elif statement Im creating a python script to check for suPHP i'm trying to create an if else statement to declare if suPHP is on the server using output from subprocess.Popen I've tested the output of the variable with print before i created this post and it pass's th...
Passing output from subprocess.Popen to a if elif statement
Im creating a python script to check for suPHP i'm trying to create an if else statement to declare if suPHP is on the server using output from subprocess.Popen I've tested the output of the variable with print before i created this post and it pass's the correct output to the variable suphp. This is what i have so fa...
[ "You don't appear to be doing anything useful with the shell=True, and so you can probably safely skip it alltogether: \ntry:\n suphp = subprocess.Popen([\"/usr/local/cpanel/bin/rebuild_phpconf\", \"--current\"], \n stdout=subprocess.PIPE,).communicate()[0]\nexcept OSError:\n print...
[ 2, 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0007548328_linux_python.txt
Q: Unexpected behavior for python set.__contains__ Borrowing the documentation from the __contains__ documentation print set.__contains__.__doc__ x.__contains__(y) <==> y in x. This seems to work fine for primitive objects such as int, basestring, etc. But for user-defined objects that define the __ne__ and __eq__ m...
Unexpected behavior for python set.__contains__
Borrowing the documentation from the __contains__ documentation print set.__contains__.__doc__ x.__contains__(y) <==> y in x. This seems to work fine for primitive objects such as int, basestring, etc. But for user-defined objects that define the __ne__ and __eq__ methods, I get unexpected behavior. Here is a sample c...
[ "For sets and dicts, you need to define __hash__. Any two objects that are equal should hash the same in order to get consistent / expected behavior in sets and dicts.\nI would reccomend using a _key method, and then just referencing that anywhere you need the part of the item to compare, just as you call __eq__ fr...
[ 7, 3, 2 ]
[]
[]
[ "list", "python", "set" ]
stackoverflow_0007549709_list_python_set.txt
Q: Python program treating dictionary like a string I set up a dictionary, and filled it from a file, like so: filedusers = {} # cheap way to keep track of users, not for production FILE = open(r"G:\School\CS442\users.txt", "r") filedusers = ast.literal_eval("\"{" + FILE.readline().strip() + "}\"") FILE.close() then...
Python program treating dictionary like a string
I set up a dictionary, and filled it from a file, like so: filedusers = {} # cheap way to keep track of users, not for production FILE = open(r"G:\School\CS442\users.txt", "r") filedusers = ast.literal_eval("\"{" + FILE.readline().strip() + "}\"") FILE.close() then later I did a test on it, like this: if not fileduse...
[ "literal_eval takes a string, and converts it into a python object. So, the following is true...\nast.literal_eval('{\"a\" : 1}')\n>> {'a' : 1}\n\nHowever, you are adding in some quotations that aren't needed. If your file simply contained an empty dictionary ({}), then the string you create would look like this......
[ 5, 3, 1 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0007549839_dictionary_python.txt
Q: A Python screen capture script that can be called programmatically? I want to open a page and grab the screen and obtain its mean color with PIL. I want to open about 100 pages so I thought a screen capture script with Python would be useful. I found several of them and I decided to use this simple one: """ A sim...
A Python screen capture script that can be called programmatically?
I want to open a page and grab the screen and obtain its mean color with PIL. I want to open about 100 pages so I thought a screen capture script with Python would be useful. I found several of them and I decided to use this simple one: """ A simple screen grabbing utility @author Fabio Varesano - @date 2009-03-17 "...
[ "You can use Selenium and any browser:\nTake a screenshot with Selenium WebDriver\nThis is cross-platform, works on every browser. \nSelenium is designed for functional web browser testing, but is suitable also for use cases like yours. More info about Python + Selenium:\nhttp://pypi.python.org/pypi/selenium\nThe b...
[ 4, 1 ]
[]
[]
[ "python", "screenshot" ]
stackoverflow_0007549044_python_screenshot.txt
Q: Convert 8 bit ( 16 Color Palette ) PNG to proper 4 bit ( 16 color Palette ) with Java or Python? I have a bunch of images, to many to do by hand that are 16 color 8 bit PNG format that I need in 16 4 bit format, they all have the same palette. I am scouring Google for the best library to use, but I am not finding ...
Convert 8 bit ( 16 Color Palette ) PNG to proper 4 bit ( 16 color Palette ) with Java or Python?
I have a bunch of images, to many to do by hand that are 16 color 8 bit PNG format that I need in 16 4 bit format, they all have the same palette. I am scouring Google for the best library to use, but I am not finding much on this specific problem so I am coming here for hopefully some more targeted solutions. I am try...
[ "In PNG the palette is always stored in RGB8 (3 bytes for each index=color), with an arbitrary (up to 256) number of entries. If you currently have a 8 bit image with a 16-colors palette (16 total entries), you dont need to alter the pallete, only to repack the pixel bytes (two indexes per byte). If so, I think you...
[ 1, 0 ]
[]
[]
[ "java", "png", "pypng", "python" ]
stackoverflow_0007535716_java_png_pypng_python.txt
Q: Help with inner loop in Python method I'm having trouble understanding why an inner loop in my method isn't producing the desired behavior I'm expecting and I'm hoping someone can help me understand the problem. My method takes a series of arguments (*args) and if the argument is an integer I want to add dollar si...
Help with inner loop in Python method
I'm having trouble understanding why an inner loop in my method isn't producing the desired behavior I'm expecting and I'm hoping someone can help me understand the problem. My method takes a series of arguments (*args) and if the argument is an integer I want to add dollar signs around the integer (eg. $5$). def t_row...
[ "The problem is because in this line:\nline_prefix = [''.join((str(value), \" & \")) for value in penult_args]\n\nYou are overwriting value with the original (non-dollar-signed) value.\nIt works for the last argument only because the above line is not called for args[-1].\nUse a different variable name for your loo...
[ 2, 2 ]
[]
[]
[ "if_statement", "methods", "python" ]
stackoverflow_0007549858_if_statement_methods_python.txt
Q: Divide set into subsets with equal number of elements For the purpose of conducting a psychological experiment I have to divide a set of pictures (240) described by 4 features (real numbers) into 3 subsets with equal number of elements in each subset (240/3 = 80) in such a way that all subsets are approximately ba...
Divide set into subsets with equal number of elements
For the purpose of conducting a psychological experiment I have to divide a set of pictures (240) described by 4 features (real numbers) into 3 subsets with equal number of elements in each subset (240/3 = 80) in such a way that all subsets are approximately balanced with respect to these features (in terms of mean and...
[ "If I understand correctly your problem, you might use random.sample() in python:\nimport random\n\npool = set([\"foo\", \"bar\", \"baz\", \"123\", \"456\", \"789\"]) # your 240 elements here\nslen = len(pool) / 3 # we need 3 subsets\nset1 = set(random.sample(pool, slen)) # 1st random subset\npool -= set1\nset2 = s...
[ 5, 2, 1, 1, 0 ]
[]
[]
[ "algorithm", "python", "r" ]
stackoverflow_0007539186_algorithm_python_r.txt
Q: How can I check the logging message and the method called my unittests? I'm using Django 1.3 and need to check the output and number of interactions in my logging system. For logging I'm using Django-Sentry though it appears that it's working just like the regular Python logger. I'm using python-mockito for mockin...
How can I check the logging message and the method called my unittests?
I'm using Django 1.3 and need to check the output and number of interactions in my logging system. For logging I'm using Django-Sentry though it appears that it's working just like the regular Python logger. I'm using python-mockito for mocking and if possible I would like to check the number of times different methods...
[ "Here's some code that does just that with the standard mock python library.\n with mock.patch('infra.manifest.fake_put') as fake_patch:\n infra.manifest.copy_files(root, files, folder, True)\n\n args, kwargs = fake_patch.call_args\n\n self.assertEqual((u'/etc/a.tmp', u'/tmp/a.tmp'), args)\n self...
[ 0 ]
[]
[]
[ "python", "python_mock", "testing", "unit_testing" ]
stackoverflow_0006689986_python_python_mock_testing_unit_testing.txt
Q: Error while trying to parse JSON using the json library I'm trying to parse JSON using the json library. I'm executing the chunk of code below, and I get the error: Traceback (most recent call last): File "test1.py", line 12, in <module> parsedResponse = json.loads(data) File "/usr/local/lib/python2.7/json...
Error while trying to parse JSON using the json library
I'm trying to parse JSON using the json library. I'm executing the chunk of code below, and I get the error: Traceback (most recent call last): File "test1.py", line 12, in <module> parsedResponse = json.loads(data) File "/usr/local/lib/python2.7/json/__init__.py", line 326, in loads return _default_decoder...
[ "When you printed your output, did it by any chance look like this?\n<SearchResult>\n<QueryDetails>\n<Category>womens-clothes</Category>\n<CategoryName>Clothing</CategoryName>\n<ShowSizeFilter>false</ShowSizeFilter>\n<ShowColorFilter>true</ShowColorFilter>\n...\n\nThat's XML, not JSON.\n", "is data null?\nis data...
[ 4, 1 ]
[]
[]
[ "json", "python" ]
stackoverflow_0007550056_json_python.txt
Q: Fetch a large chunk of data with TaskQueue I'd like to fetch a large file from an url, but it always raises a DeadLineExceededError, although I have tried with a TaskQueue and put deadline=600 to fetch. The problem comes from the fetch, so Backends cannot help here : even if i'd launched a backend with a TaskQueue...
Fetch a large chunk of data with TaskQueue
I'd like to fetch a large file from an url, but it always raises a DeadLineExceededError, although I have tried with a TaskQueue and put deadline=600 to fetch. The problem comes from the fetch, so Backends cannot help here : even if i'd launched a backend with a TaskQueue, i'd had 24h to return, but there 'd be still t...
[ "If the server supports it, you can supply the HTTP Range header to specify a subset of the file that you want to fetch. If the content is being served statically, the server will probably respect range requests; if it's dynamic, it depends on whether the author of the code that generates the response allowed for t...
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0007542651_google_app_engine_python.txt
Q: small problem with django-tinymce and django-filebrowser integration I am trying to integrate django-tinymce with django-filebrowser for my django admin site. Everything (almost) works fine. manage.py test filebrowser, works ok http://localhost:8000/admin/filebrowser/browse/ works, too however when I press the b...
small problem with django-tinymce and django-filebrowser integration
I am trying to integrate django-tinymce with django-filebrowser for my django admin site. Everything (almost) works fine. manage.py test filebrowser, works ok http://localhost:8000/admin/filebrowser/browse/ works, too however when I press the browse button on the windows popup of insert/edit image of tinymce button p...
[ "I finally managed to find the answer to my problem.\nI had to modify the tinymce/views.py file like this:\nfb_url = \"%s://%s%s\" % (request.is_secure() and 'https' or 'http',\n #request.get_host(), urlresolvers.reverse('filebrowser-index'))\n request.get_host(), urlresolvers.reverse('fb_browse'))\n\nI found...
[ 1 ]
[]
[]
[ "django", "django_filebrowser", "django_tinymce", "python" ]
stackoverflow_0007539957_django_django_filebrowser_django_tinymce_python.txt
Q: Python binding to ImageMagick I am looking for a good Python binding to ImageMagick, but there seem a lot of bindings already. I am not sure that which of these is the right tool for my job. Can you guys recommend me one? Here is the list of my requirements and preferences (in order of importance): Must be availa...
Python binding to ImageMagick
I am looking for a good Python binding to ImageMagick, but there seem a lot of bindings already. I am not sure that which of these is the right tool for my job. Can you guys recommend me one? Here is the list of my requirements and preferences (in order of importance): Must be available on PyPI (to simplify our deploy...
[ "I found the package myself: magickwand is a ctypes-based ImageMagick binding for Python. Yet it has no documentation at all, it still satisfies most of my requirements.\nPlus: I finally started my own project: Wand.\n" ]
[ 24 ]
[]
[]
[ "binding", "imagemagick", "python", "wand" ]
stackoverflow_0007550900_binding_imagemagick_python_wand.txt
Q: endcoding error my code has a trouble with encoding error: File "test.py", line 1 SyntaxError: encoding problem: with BOM I attached the code below. is there any clear idea to fix it? the input and the output file contain Korean words, numbers, and english charaters. I try to run this code in Mac and windows, it d...
endcoding error
my code has a trouble with encoding error: File "test.py", line 1 SyntaxError: encoding problem: with BOM I attached the code below. is there any clear idea to fix it? the input and the output file contain Korean words, numbers, and english charaters. I try to run this code in Mac and windows, it doesn't work at both o...
[ "You've misspelled UTF-8 on the first line. Since you've only used ASCII characters in you're code, it isn't even required to have a coding line.\n", "The problem is not with the code, but with the encoding of the script itself. Try saving it with a different editor. Notepad on Windows works for me.\n" ]
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007551032_python.txt
Q: Why do Python's datetime.strftime('%w') and datetime.weekday() use different indexes for the days of the week? In Python, showing the day of the week as an integer using datetime.strftime() shows a different result than using datetime.weekday(). >>> import datetime >>> now = datetime.datetime.now() >>> now.strftim...
Why do Python's datetime.strftime('%w') and datetime.weekday() use different indexes for the days of the week?
In Python, showing the day of the week as an integer using datetime.strftime() shows a different result than using datetime.weekday(). >>> import datetime >>> now = datetime.datetime.now() >>> now.strftime('%A') 'Sunday' >>> now.strftime('%w') # Day of the week as an integer. '0' >>> now.weekday() # Day of the week as ...
[ "Python's strftime function emulates that in the c library. Thus, the motivation that %w returns 0 for a Sunday comes entirely from that.\nIn contrast, the method date.weekday() returns a 6 for Sunday as it seeks to match the behaviour of the much older time module. Within that module times are generally represen...
[ 14, 5, 2 ]
[]
[]
[ "datetime", "python" ]
stackoverflow_0007550726_datetime_python.txt
Q: How to scrape a huge amounts of tweets I am building a project in python that needs to scrape huge and huge amounts of Twitter data. Something like 1 million users and all their tweets need to be scraped. Previously I have used Tweepy and Twython, but hit the limit of Twitter very fast. How do sentiment analysis ...
How to scrape a huge amounts of tweets
I am building a project in python that needs to scrape huge and huge amounts of Twitter data. Something like 1 million users and all their tweets need to be scraped. Previously I have used Tweepy and Twython, but hit the limit of Twitter very fast. How do sentiment analysis companies etc. get their data? How do they g...
[ "I don't know if this will work for what you're trying to do, but the Tweets2011 dataset was recently released.\nFrom the description:\n\nAs part of the TREC 2011 microblog track, Twitter provided identifiers\n for approximately 16 million tweets sampled between January 23rd and\n February 8th, 2011. The corpus i...
[ 7, 7 ]
[]
[]
[ "python", "screen_scraping", "twitter" ]
stackoverflow_0007547646_python_screen_scraping_twitter.txt
Q: Django Context Processor and Form variables I have a form in my site_base.html which extends to all of my templates. In my site_base.html, there is a dropdown form which allows a user to change his role. Based on the selected role, the templates changes. I've thought to persist this information via a context proc...
Django Context Processor and Form variables
I have a form in my site_base.html which extends to all of my templates. In my site_base.html, there is a dropdown form which allows a user to change his role. Based on the selected role, the templates changes. I've thought to persist this information via a context processor but I'm having problems writing the right l...
[ "Store the value in the session (in a view, not the context processor) as soon as it's set for the first time.\nrequest.session['role_id'] = request.POST['role']\n\nThen you can get the actual Role object in your context processor each time:\ncurrent_role = Role.objects.get(role_id=request.session['role_id'])\n\n" ...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0007550730_django_django_forms_python.txt
Q: python encoding Using mechanize, I retrieved source page of an web which contains some non-ASCII characters, such as Chinese characters. Code goes below: #using python2.6 from mechanize import Browser br = Browser() br.open("http://www.example.html") src = br.reponse().read() #retrieve the source of the web pr...
python encoding
Using mechanize, I retrieved source page of an web which contains some non-ASCII characters, such as Chinese characters. Code goes below: #using python2.6 from mechanize import Browser br = Browser() br.open("http://www.example.html") src = br.reponse().read() #retrieve the source of the web print src #print the ...
[ "src is a unicode, which has no encoding. print (or more correctly, sys.stdout.write()) figures out what encoding to use when outputting.\n" ]
[ 3 ]
[]
[]
[ "encoding", "mechanize", "python" ]
stackoverflow_0007551618_encoding_mechanize_python.txt
Q: pdf to chm handling libraries for python3 I've tried to find a software for pdf to chm conversion to convert my pdf e-books to chm, but I ended up disappointed. So, as a pythonian, I decided to create my own program to convert pdf files to chm, however, all pdf/chm libraries I found are python2 libraries. Are ther...
pdf to chm handling libraries for python3
I've tried to find a software for pdf to chm conversion to convert my pdf e-books to chm, but I ended up disappointed. So, as a pythonian, I decided to create my own program to convert pdf files to chm, however, all pdf/chm libraries I found are python2 libraries. Are there python 3 libraries to handle pdf/chm files?
[ "If you want to write CHM, then afaik only Free Pascal (and therefore Delphi with minimal effort) has a free CHM generator library. \nAll other tools use the Microsoft commandline tool behind the scenes.\nFor reading there is chmlib, I assume there is some python wrapper for it somewhere.\n" ]
[ 0 ]
[]
[]
[ "chm", "pdf", "python" ]
stackoverflow_0007504221_chm_pdf_python.txt
Q: config_vars.mk missing in default xampp-linux installation I extracted the xampp package xampp-linux-1.6.7 on a Ubuntu 8.10 system and followed the instuctions from mod_wsgi documentation. I get the error below: ravi@Ibex:~/mod_wsgi-2.3$ ./configure --with-apxs=/opt/lampp/bin/apxs checking Apache version... cann...
config_vars.mk missing in default xampp-linux installation
I extracted the xampp package xampp-linux-1.6.7 on a Ubuntu 8.10 system and followed the instuctions from mod_wsgi documentation. I get the error below: ravi@Ibex:~/mod_wsgi-2.3$ ./configure --with-apxs=/opt/lampp/bin/apxs checking Apache version... cannot open /opt/lampp/build/config_vars.mk: No such file or directo...
[ "When apxs throws and error complaining about missing config_vars.mk it means that the build directory of Apache is missing. Fox xampp users the solution is to download xampp-dev as well and extract that to the same path.\n" ]
[ 1 ]
[]
[]
[ "apache", "mod_wsgi", "python", "xampp" ]
stackoverflow_0000274638_apache_mod_wsgi_python_xampp.txt
Q: Statistics & other add-on tools for Planet blog aggregator software The Planet software is often used for particular topics or large projects, to collect blogs that post on a particular theme. http://www.planetplanet.org/ I think there are lots of interesting add-ons that could be done for it but so far I haven't ...
Statistics & other add-on tools for Planet blog aggregator software
The Planet software is often used for particular topics or large projects, to collect blogs that post on a particular theme. http://www.planetplanet.org/ I think there are lots of interesting add-ons that could be done for it but so far I haven't seen any. Does anyone know any? (Because of the name, it's kinda hard to ...
[ "Answer: No, there are no addons afaik. You could write them. :-)\n" ]
[ 0 ]
[]
[]
[ "add_on", "python" ]
stackoverflow_0000490634_add_on_python.txt
Q: Working with directories - Python I have the following piece of python code. The code is supposed to get a source, a temporary and an final output path from the user and extract some header files. When the full paths are specified from the terminal, the program works perfectly but when the terminal command is as s...
Working with directories - Python
I have the following piece of python code. The code is supposed to get a source, a temporary and an final output path from the user and extract some header files. When the full paths are specified from the terminal, the program works perfectly but when the terminal command is as so : Python Get-iOS-Private-SDKs.py -p /...
[ "os.makedirs gets a relative path (based on ./tmp) and gets called after calls to chdir (see dest initialisation and usage)\n", "As already said, the loop\nfor file in files:\n os.makedirs(dest + file)\n os.chdir(dest + file)\n command = ['/opt/local/bin/class-dump','-H',os.path.join(root,file)]\n sub...
[ 3, 0 ]
[]
[]
[ "directory_structure", "python" ]
stackoverflow_0007551706_directory_structure_python.txt
Q: Slow Django database operations on Google App Engine I'm testing Google App Engine and Django-nonrel with free quota. It seems to me, that the database operations to Datastore a hideously slow. Take for example this simplified function processing a request, which takes in a multipart/form-data of XML blobs, parses...
Slow Django database operations on Google App Engine
I'm testing Google App Engine and Django-nonrel with free quota. It seems to me, that the database operations to Datastore a hideously slow. Take for example this simplified function processing a request, which takes in a multipart/form-data of XML blobs, parses them and inserts them to the database: def post(request):...
[ "In the absence of batch operations, there's not much you can do to reduce wallclock times. Batch operations are pretty essential to reducing wallclock time on App Engine (or any distributed platform with RPCs, really).\nUnder the current billing model, CPU milliseconds reported by the datastore reflect the cost of...
[ 3, 1 ]
[]
[]
[ "django_nonrel", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0007471604_django_nonrel_google_app_engine_google_cloud_datastore_python.txt
Q: Output row in text file with max value in specified column to new file I have a fairly simple task I need to automate for an analysis. I have found similar questions on this forum but not applied to a plain text file, and as I am a python newbie I am not sure how to convert these solutions directly to my needs. So...
Output row in text file with max value in specified column to new file
I have a fairly simple task I need to automate for an analysis. I have found similar questions on this forum but not applied to a plain text file, and as I am a python newbie I am not sure how to convert these solutions directly to my needs. So I'd appreciate any help. I have a series of files in this format: 11 5012 1...
[ "import glob, operator\n\nfpout = open(\"result.dat\",\"w\")\n\nfor path in glob.glob(\"data?-?\"):\n with open(path, \"r\") as fp:\n fields = [ line.split(\" \") for line in fp ]\n maxline = \" \".join(max(fields, key = lambda row: float(row[5]))\n print >> fpout, maxline\n\n" ]
[ 2 ]
[]
[]
[ "database", "max", "python", "text" ]
stackoverflow_0007552855_database_max_python_text.txt
Q: Python equivalent of Perl's idiom do this or that, usually known as "or die"? IN Perl it's quite common to do things like function() || alternative(). If the first returns false it will run the second one. How can this be easily implemented in Python? Update Examples (pseudocode): x = func() or raise exeption x = ...
Python equivalent of Perl's idiom do this or that, usually known as "or die"?
IN Perl it's quite common to do things like function() || alternative(). If the first returns false it will run the second one. How can this be easily implemented in Python? Update Examples (pseudocode): x = func() or raise exeption x = func() or print(x) func() or print something If possible solutions should work wit...
[ "Use or: Python uses short circuit evaluation for boolean expressions:\nfunction() or alternative()\n\nIf function returs True, the final value of this expression is determined and \nalternative is not evaluated at all.\n", "you can use or:\nfunction() or alternative()\n\nalso, there is conditional expression def...
[ 5, 2, 1, 1 ]
[]
[]
[ "boolean", "idioms", "perl", "python", "short_circuiting" ]
stackoverflow_0007552928_boolean_idioms_perl_python_short_circuiting.txt
Q: Why do I get the message: 'module' object has no attribute 'load_source' I have function: def load_from_file(filepath, expected_class): mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) py_mod = imp.load_source(mod_name, filepath) in templatetags file and it is ok. But when i copy/paste ...
Why do I get the message: 'module' object has no attribute 'load_source'
I have function: def load_from_file(filepath, expected_class): mod_name, file_ext = os.path.splitext(os.path.split(filepath)[-1]) py_mod = imp.load_source(mod_name, filepath) in templatetags file and it is ok. But when i copy/paste this function to my view i get error: 'module' object has no attribute 'load_s...
[ "You have another module named imp.\nEither rename it, move it either to a spot later in your sys.path than the standard library modules or out of sys.path completely, or rearrange your sys.path.\nIt's most likely in the same directory as your views; if that's the case, the easiest thing to do is probably to move i...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007552947_django_python.txt
Q: Python module "twill"--HTML flood during variable assignment I'm making a simple command line program for gathering and parsing information from websites (pretty generic) using the Twill module in Python. I want to assign the HTML output to a variable using Twill's show() command to run the page through my parsin...
Python module "twill"--HTML flood during variable assignment
I'm making a simple command line program for gathering and parsing information from websites (pretty generic) using the Twill module in Python. I want to assign the HTML output to a variable using Twill's show() command to run the page through my parsing commands, but every time I assign it to a variable... htmlString...
[ "I would propose to use lxml or BeautifulSoup to parse HTML, never faced twill. But I see you calling .show() method, maybe this method have print statement inside.\n", "Twill is an odd one and prints a lot of output to the terminal. It's not the variable assignment that's causing the stuff to be printed out, it'...
[ 3, 1 ]
[]
[]
[ "python", "twill", "variable_assignment" ]
stackoverflow_0005831793_python_twill_variable_assignment.txt
Q: Storing windows path in MySQL without escaping backslashes I would like to store windows path in MySQL without escaping the backslashes. How can I do this in Python? I am using MySQLdb to insert records into the database. When I use MySQLdb.escape_string(), I notice that the backslashes are removed. A: Have a lo...
Storing windows path in MySQL without escaping backslashes
I would like to store windows path in MySQL without escaping the backslashes. How can I do this in Python? I am using MySQLdb to insert records into the database. When I use MySQLdb.escape_string(), I notice that the backslashes are removed.
[ "Have a look at os.path.normpath(thePath)\nI can't remember if it's that one, but there IS a standard os.path formating function that gives double backslashes, that can be stored in a db \"as is\" and reused later \"as is\". I have no more windows machine and cannot test it anymore.\n", "Just use a dictionary t...
[ 0, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0007553200_mysql_python.txt
Q: Tkinter Optionmenu callback not working For some reason I can't get this optionmenu so call the callback function. Is there some special treatment those widgets require? (The function itself works and I can call it from i.e. a button.) self.shapemenu=Tkinter.OptionMenu(self.frame,self.shape,"rectangle", "circular"...
Tkinter Optionmenu callback not working
For some reason I can't get this optionmenu so call the callback function. Is there some special treatment those widgets require? (The function itself works and I can call it from i.e. a button.) self.shapemenu=Tkinter.OptionMenu(self.frame,self.shape,"rectangle", "circular", command=self.setshape) self.shape is a Tki...
[ "The optionmenu is designed to set a value, not perform an action. You can't assign a command to it, and if you do, you will break its default behavior of setting the value -- it uses the command option internally to manage its values . \nIf you want something to happen when the value changes, add a trace on the St...
[ 6 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007553885_python_tkinter.txt
Q: Django URLs regex I need you help to validate a regular expression link in Python. Here's how should the link look like: http://www.example.com?utm_source=something&utm_medium=somethingelse And I've tried something like: r'^\?utm_source\=(?P<utm_source>[-\w]+)&utm_medium\=(?P<utm_medium>[-\w]+)/$' But this does...
Django URLs regex
I need you help to validate a regular expression link in Python. Here's how should the link look like: http://www.example.com?utm_source=something&utm_medium=somethingelse And I've tried something like: r'^\?utm_source\=(?P<utm_source>[-\w]+)&utm_medium\=(?P<utm_medium>[-\w]+)/$' But this doesn't work. Can you pleas...
[ "This is a classic XY problem.\nTim's answer, gives you the solution you asked for.\nI'd suggest that you do not need regular expressions here at all if all you want to do is validate a query string. \nTake a look at urlparse...\n>>> a_url = 'http://www.example.com?utm_source=something&utm_medium=somethingelse'\n>>...
[ 4, 1 ]
[]
[]
[ "django", "python", "regex", "url" ]
stackoverflow_0007554223_django_python_regex_url.txt
Q: problem with deserialization xml to objects - unwanted split by special chars I try to deserialize xml to objects, and i met a problem with encoding of various items in xml tree. XML example: <?xml version="1.0" encoding="utf-8"?> <results> <FlightTravel> <QuantityOfPassengers>6</QuantityOfPassengers> <I...
problem with deserialization xml to objects - unwanted split by special chars
I try to deserialize xml to objects, and i met a problem with encoding of various items in xml tree. XML example: <?xml version="1.0" encoding="utf-8"?> <results> <FlightTravel> <QuantityOfPassengers>6</QuantityOfPassengers> <Id>N5GWXM</Id> <InsuranceId>330992</InsuranceId> <TotalTime>3h 00m</TotalTim...
[ "The problem is that the data method of your target class may be called more than once per element. This may happen if the feeder crosses a block boundary, for example. Looks like it can also happen when it hits a non-ASCII character. This is ancient legend. I can't find where this is documented. However if you cha...
[ 1 ]
[]
[]
[ "deserialization", "encoding", "python", "xml" ]
stackoverflow_0007553470_deserialization_encoding_python_xml.txt
Q: How do I find the shortest overlapping match using regular expressions? I'm still relatively new to regex. I'm trying to find the shortest string of text that matches a particular pattern, but am having trouble if the shortest pattern is a substring of a larger match. For example: import re string = "A|B|A|B|C|D|E...
How do I find the shortest overlapping match using regular expressions?
I'm still relatively new to regex. I'm trying to find the shortest string of text that matches a particular pattern, but am having trouble if the shortest pattern is a substring of a larger match. For example: import re string = "A|B|A|B|C|D|E|F|G" my_pattern = 'a.*?b.*?c' my_regex = re.compile(my_pattern, re.DOTALL|r...
[ "Contrary to most other answers here, this can be done in a single regex using a positive lookahead assertion with a capturing group:\n>>> my_pattern = '(?=(a.*?b.*?c))'\n>>> my_regex = re.compile(my_pattern, re.DOTALL|re.IGNORECASE)\n>>> matches = my_regex.findall(string)\n>>> print min(matches, key=len)\nA|B|C\n\...
[ 15, 1, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0002148700_python_regex.txt
Q: Reading large excel tables (guessing size) I'm using pywin32 to read and write to excel. Now the only method I know is accessing Range.Value however, I usually don't know the size of the full excel table in advance. So at the moment I read line by line until I find a completely empty line. This can be quite slow. ...
Reading large excel tables (guessing size)
I'm using pywin32 to read and write to excel. Now the only method I know is accessing Range.Value however, I usually don't know the size of the full excel table in advance. So at the moment I read line by line until I find a completely empty line. This can be quite slow. Of course I will try tricks like reading blocks ...
[ "You can use xlrd to open a workbook and read the size of particular worksheet. It's quite fast. \nHints: book = xlrd.open_workbook(\"myfile.xls\") then you get Sheet object by sheet = book.sheet_by_index(sheetx) or sheet = book.sheet_by_name(sheet_name) and you have sheet.nrows property with number of rows in give...
[ 3, 2, 2 ]
[]
[]
[ "com", "excel", "python", "pywin32", "vba" ]
stackoverflow_0007554582_com_excel_python_pywin32_vba.txt
Q: Python - self, no self and cls Yet another question on what the 'self' is for, what happens if you don't use 'self' and what's 'cls' for. I "have done my homework", I just want to make sure I got it all. self - To access an attribute of an object, you need to prefix the attribute name with the object name (objname...
Python - self, no self and cls
Yet another question on what the 'self' is for, what happens if you don't use 'self' and what's 'cls' for. I "have done my homework", I just want to make sure I got it all. self - To access an attribute of an object, you need to prefix the attribute name with the object name (objname.attributename). The same way self i...
[ "\nThe same way self is used to access an attribute inside the object (class) itself. \n\nNot inside the object / class, just inside the class' instance methods. self is just a convention, you could call it whatever you wanted, even something different in each method.\n\nSo if you didn't prefix a variable with self...
[ 121, 17 ]
[]
[]
[ "class", "object", "python", "self" ]
stackoverflow_0007554738_class_object_python_self.txt
Q: Calculating Reciprocals: n**(-1) or (1/n)? In random.py's source code, there is the following constant definition: BPF = 53 # Number of bits in a float RECIP_BPF = 2**-BPF I'm no math major, but isn't it more readable to invert BPF by placing a 1 over it? Or is there something about multiplication that is ...
Calculating Reciprocals: n**(-1) or (1/n)?
In random.py's source code, there is the following constant definition: BPF = 53 # Number of bits in a float RECIP_BPF = 2**-BPF I'm no math major, but isn't it more readable to invert BPF by placing a 1 over it? Or is there something about multiplication that is more convenient than division in programming? N...
[ "RECIP_BPF, despite its name, is not 1/BPF. It is 1/(2^BPF). I can't speak for everyone, but I find it easier to read as 2**-BPF than I would as 1.0/2**BPF.\nNote that the speed of multiplication and division is not really relevant here; in particular, since these are constants, a compiler or interpreter only nee...
[ 3, 1, 1 ]
[]
[]
[ "computer_science", "math", "python" ]
stackoverflow_0007554853_computer_science_math_python.txt
Q: Website Downloader using Python I am trying to create a website downloader using python. I have the code for: Finding all URLs from a page Downloading a given URL What I have to do is to recursively download a page, and if there's any other link in that page, I need to download them also. I tried combining the a...
Website Downloader using Python
I am trying to create a website downloader using python. I have the code for: Finding all URLs from a page Downloading a given URL What I have to do is to recursively download a page, and if there's any other link in that page, I need to download them also. I tried combining the above two functions, but recursion thi...
[ "You may want to look into the Scrapy library.\nIt would make a task like this pretty trivial, and allow you to download multiple pages concurrently.\n", "done_url = []\ndef download(url):\n if url in done_url:return\n ...download url code...\n done_url.append(url)\n urls = sone_function_to_fetch_urls...
[ 2, 2, 1 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0007554862_python_web_crawler.txt
Q: Which python to install if I have an Intel Core i7 and 64-Bit Windows 7? I have to install Python 2.5.4 from http://www.python.org/download/releases/2.5.4/ which is required for the pcraster program. However there are three python choices For x86 processors: python-2.5.4.msi For Win64-Itanium users: python-2.5.4....
Which python to install if I have an Intel Core i7 and 64-Bit Windows 7?
I have to install Python 2.5.4 from http://www.python.org/download/releases/2.5.4/ which is required for the pcraster program. However there are three python choices For x86 processors: python-2.5.4.msi For Win64-Itanium users: python-2.5.4.ia64.msi For Win64-AMD64 users: python-2.5.4.amd64.msi I know I have Win64 b...
[ "Install the Win64-AMD64 version. Since AMD won the race to implement the 64 bit architecture before Intel, the architecture is still commonly known as AMD64.\nIrony!\nIntel licensed x86 architecture to AMD. Years later. AMD licensed AMD64 (based on the x86 architecture) to Intel!\nRead more about it from Wikipedia...
[ 19, 12, 2 ]
[]
[]
[ "64_bit", "python" ]
stackoverflow_0007554103_64_bit_python.txt
Q: How to convert a string to tuple I like to convert in a Python script the following string: mystring='(5,650),(235,650),(465,650),(695,650)' to a list of tuples mytuple=[(5,650),(235,650),(465,650),(695,650)] such that print mytuple[0] yields: (5,650) A: I'd use ast.literal_eval: In [7]: ast.literal_eval('(5,6...
How to convert a string to tuple
I like to convert in a Python script the following string: mystring='(5,650),(235,650),(465,650),(695,650)' to a list of tuples mytuple=[(5,650),(235,650),(465,650),(695,650)] such that print mytuple[0] yields: (5,650)
[ "I'd use ast.literal_eval:\nIn [7]: ast.literal_eval('(5,650),(235,650),(465,650),(695,650)')\nOut[7]: ((5, 650), (235, 650), (465, 650), (695, 650))\n\nAs seen above, this returns a tuple of tuples. If you want a list of tuples, simply apply list() to the result.\n", "That's not a tuple, that's a list.\nIf you c...
[ 13, 1, 1 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0007555044_configparser_python.txt
Q: blender: how to export shape keys using python? I want to export shape keys for some object. How can i get access to a shape key's mesh ? I'm using blender 2.59. Thanks A: i did it. Here is the script. maybe it would be helpful for someone: import bpy import xml.dom.minidom path = "/Users/x/Documents/y/game_pro...
blender: how to export shape keys using python?
I want to export shape keys for some object. How can i get access to a shape key's mesh ? I'm using blender 2.59. Thanks
[ "i did it. Here is the script. maybe it would be helpful for someone:\nimport bpy\nimport xml.dom.minidom\n\npath = \"/Users/x/Documents/y/game_projects/test.xml\"\n\ndom = xml.dom.minidom.getDOMImplementation()\ntree = dom.createDocument(None, \"document\", None)\n\nroot = tree.documentElement\nroot.setAttribute(\...
[ 7 ]
[]
[]
[ "blender", "export", "python" ]
stackoverflow_0007553726_blender_export_python.txt
Q: Setuptools / distutils: Installing files into the distribution's DLLs directory on Windows I'm writing a setup.py which uses setuptools/distutils to install a python package I wrote. It need to install two DLL files (actually a DLL file and a PYD file) into location which is available for python to load. Thought t...
Setuptools / distutils: Installing files into the distribution's DLLs directory on Windows
I'm writing a setup.py which uses setuptools/distutils to install a python package I wrote. It need to install two DLL files (actually a DLL file and a PYD file) into location which is available for python to load. Thought this is the DLLs directory under the installation directory on my python distribution (e.g. c:\Py...
[ "I was able to solve this issue by doing the following changes:\n 1. All data_files path changed to be relative\ndata_files=[\"myhome\", [\"Win32/file1.pyd\", \"Win32/file2.dll\"])]\n\n2. I try to find the location of \"myhome\" in the package init file so I'll be able to use them. This require some nasty code, bec...
[ 2 ]
[]
[]
[ "distutils", "easy_install", "pip", "python", "setuptools" ]
stackoverflow_0007537799_distutils_easy_install_pip_python_setuptools.txt
Q: Printing first field and (and only) matching fields in record, using awk I really don't know if awk would be the appropriate tool for that task... Maybe something in python would be better. Anyway, I thought asking here first for the feasibility of the task. Here we go : Datas : ### offspr84 175177 200172...
Printing first field and (and only) matching fields in record, using awk
I really don't know if awk would be the appropriate tool for that task... Maybe something in python would be better. Anyway, I thought asking here first for the feasibility of the task. Here we go : Datas : ### offspr84 175177 200172 312312 310326 338342 252240 226210 113129 223264 male28 197175 17220...
[ "This code will produce the output you want. Maybe not the best way, but seems to work as expected.\n#data = [\n #'offspr84 175177 200172 312312 310326 338342 252240 226210 113129 223264',\n #'male28 197175 172200 308312 310338 262338 256252 190226 113129 223219',\n #'female13 197177 172172 312308 318326 3...
[ 1, 0, 0, 0 ]
[]
[]
[ "awk", "python" ]
stackoverflow_0007546880_awk_python.txt
Q: How to convert pointer to c array to python array I have a C++ callback function that calls into Python using ctypes. This function's parameters are a pointer to an array of double and the number of elements. There are a lot of elements, approximately 2,000,000. I need to send this into scipy functions. The C++ ...
How to convert pointer to c array to python array
I have a C++ callback function that calls into Python using ctypes. This function's parameters are a pointer to an array of double and the number of elements. There are a lot of elements, approximately 2,000,000. I need to send this into scipy functions. The C++ prototype is : bool (*ptsetDataSource)(double*, long lo...
[ "If Data were (c_double*DataLength.value) array then you could:\na = np.frombuffer(Data) # no copy. Changes in `a` are reflected in `Data`\n\nIf Data is a POINTER(c_double) you could get numpy array using numpy.fromiter(). It is the same loop as in your question but faster:\na = np.fromiter(Data, dtype=np.float, co...
[ 33 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0007543675_ctypes_python.txt
Q: How to avoid creation of foreign keys on Django Models? when i create a model with a foreign key relationship, something like this: class Post(models.Model): title = models.CharField(max_length=250) date_created = models.DateTimeField(auto_now=False, auto_now_add=True) owner = models.ForeignKey(User) ...
How to avoid creation of foreign keys on Django Models?
when i create a model with a foreign key relationship, something like this: class Post(models.Model): title = models.CharField(max_length=250) date_created = models.DateTimeField(auto_now=False, auto_now_add=True) owner = models.ForeignKey(User) when i do syncdb to dump those models to the DB it creates th...
[ "Please don't. Foreign keys are the right thing to have and you should never prevent the database from protecting its own consistency. If you need to do something special to the table (and are sure not to break its integrity) you can temporarily disable the checks:\nSET foreign_key_checks = 0\n# do something\nSET f...
[ 2 ]
[]
[]
[ "django", "foreign_keys", "mysql", "python" ]
stackoverflow_0007555874_django_foreign_keys_mysql_python.txt
Q: Create DB connection and maintain on multiple processes (multiprocessing) Similar to another post I made, this answers that post and creates a new question. Recap: I need to update every record in a spatial database in which I have a data set of points that overlay data set of polygons. For each point feature I w...
Create DB connection and maintain on multiple processes (multiprocessing)
Similar to another post I made, this answers that post and creates a new question. Recap: I need to update every record in a spatial database in which I have a data set of points that overlay data set of polygons. For each point feature I want to assign a key to relate it to the polygon feature that it lies within. So...
[ "Try to isolate the creation of your connection in the Consumer constructor, then give it to the executed Task : \nimport multiprocessing, time, psycopg2\n\nclass Consumer(multiprocessing.Process):\n\n def __init__(self, task_queue, result_queue):\n multiprocessing.Process.__init__(self)\n self.tas...
[ 41 ]
[]
[]
[ "database_connection", "multiprocessing", "python" ]
stackoverflow_0007555680_database_connection_multiprocessing_python.txt
Q: which command equivalent in Python I have the following code which i am using to check if the program class-dump exists on a system. The program only returns a blank. cmd = ["which","class-dump"] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) print process.stdout.read() This code always returns a blank....
which command equivalent in Python
I have the following code which i am using to check if the program class-dump exists on a system. The program only returns a blank. cmd = ["which","class-dump"] process = subprocess.Popen(cmd, stdout=subprocess.PIPE) print process.stdout.read() This code always returns a blank. Technically it should work right ?
[ "I tried the following on my machine and its working perfectly.\nimport subprocess\ncmd = [\"which\",\"java\"]\nprocess = subprocess.Popen(cmd, stdout=subprocess.PIPE)\nprint process.communicate()\n\nthis is the output\n('/usr/bin/java\\n', None)\n\n", "which is a shell built-in. You need to pass shell=True to t...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "command", "python" ]
stackoverflow_0007555531_command_python.txt
Q: Python, Paramiko: How to do a "ssh -n user@host cmd" using paramiko? I'm trying to execute a command remotely via SSH from Python, and in this particular case need stdin to be redirected to /dev/null. That is, the same as using the OpenSSH client with its -n flag: ssh -n user@host cmd How do you achieve this (-n)...
Python, Paramiko: How to do a "ssh -n user@host cmd" using paramiko?
I'm trying to execute a command remotely via SSH from Python, and in this particular case need stdin to be redirected to /dev/null. That is, the same as using the OpenSSH client with its -n flag: ssh -n user@host cmd How do you achieve this (-n) with Paramiko? paramiko.SSHClient.exec_command() doesn't seem to allow th...
[ "Unless I understand your question incorrectly: you don't need to achieve this. Nothing is automatically read from stdin/written to the remote process' stdin unless you yourself explicitly do so. So you don't need to prevent reading from stdin from happening?\nEDIT: there might be an issue if the remote process exp...
[ 2, 1 ]
[]
[]
[ "paramiko", "python", "ssh" ]
stackoverflow_0007555805_paramiko_python_ssh.txt
Q: What is the alternative for CollabNet's python svn bindings? What is the alternative for the python svn bindings provided by CollabNet (this where you have 2 directories: svn and libsvn, the second with a lot of pre-compiled libraries)? The problem with it is that it just can't be configured to run with Windows ve...
What is the alternative for CollabNet's python svn bindings?
What is the alternative for the python svn bindings provided by CollabNet (this where you have 2 directories: svn and libsvn, the second with a lot of pre-compiled libraries)? The problem with it is that it just can't be configured to run with Windows version on Python. We've done what was written on various fora, but ...
[ "Apache Subversion is written in C and provides native libraries for the OS. On Windows, this means DLL's. Subversion provides \"bindings\" for a number of different languages, including Python. This gives you a shim that lets you write code in your language and the bindings handle making calls into the native l...
[ 3 ]
[]
[]
[ "python", "python_bindings", "svn", "windows" ]
stackoverflow_0007555519_python_python_bindings_svn_windows.txt
Q: Database Selection and Datetime Sorting (real-time Python dashboard) I have a dashboard for real-time updates and latest notifications. Imagine this is a blogging system where you can subscribe to authors posts and comments. I then want 2 type of notifications to appear in my dashboard, sorted by insertion time: ...
Database Selection and Datetime Sorting (real-time Python dashboard)
I have a dashboard for real-time updates and latest notifications. Imagine this is a blogging system where you can subscribe to authors posts and comments. I then want 2 type of notifications to appear in my dashboard, sorted by insertion time: Last posts Last comments Imagine I only want 10 updates to show up when I...
[ "Query the first table ordering by descending insertion time and limiting results to 10. Then query the second table the same way. Then merge results in python and return the first 10 of them.\nA django example could look like this:\nfrom operator import attrgetter\n\nrecent_posts = Post.objects.order_by('-created'...
[ 2 ]
[]
[]
[ "database", "python", "real_time", "selection" ]
stackoverflow_0007556311_database_python_real_time_selection.txt
Q: usage function doesn't work with getopt I have a problem with a usage function in Python. This is a part of my main function: def main(argv): try: opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output=']) if not opts: print 'No options supplied' ...
usage function doesn't work with getopt
I have a problem with a usage function in Python. This is a part of my main function: def main(argv): try: opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output=']) if not opts: print 'No options supplied' usage() except getopt...
[ "The below worked for me. Run it with \"python code.py\".\nimport getopt, sys\n\ndef usage():\n print \"\\nThis is the usage function\\n\"\n print 'Usage: '+sys.argv[0]+' -i <file1> [option]'\n\ndef main(argv):\n try:\n opts, args = getopt.getopt(argv, 'hi:o:tbpms:', ['help', 'input=', 'output='])\n if no...
[ 8 ]
[]
[]
[ "command_line_arguments", "getopt", "python" ]
stackoverflow_0007556639_command_line_arguments_getopt_python.txt
Q: Can't Selecting Multiple fields in django admin In My django admin form I have one Image Upload field and also It has been done for the preview support.Also I has clear option to clear that image in the object.If i need to select another image with also clicking the clear option "It does't do that" At a time it sa...
Can't Selecting Multiple fields in django admin
In My django admin form I have one Image Upload field and also It has been done for the preview support.Also I has clear option to clear that image in the object.If i need to select another image with also clicking the clear option "It does't do that" At a time it says only one option will be done.What I should have to...
[ "Use django inline model admin here\nearlier question on SO: go here\n" ]
[ 0 ]
[]
[]
[ "django", "python", "views" ]
stackoverflow_0007555552_django_python_views.txt
Q: Download POP3 headers from a certain date (Python) I'm trying to write a pop3 and imap clients in python using available libs, which will download email headers (and subsequently entire email bodies) from various servers and save them in a mongodb database. The problem I'm facing is that this client downloads emai...
Download POP3 headers from a certain date (Python)
I'm trying to write a pop3 and imap clients in python using available libs, which will download email headers (and subsequently entire email bodies) from various servers and save them in a mongodb database. The problem I'm facing is that this client downloads emails in addition to a user's regular email client. So with...
[ "Outlook logs in to a POP3 server and issues the STAT, LIST and UIDL commands; then if it decides the user has no new messages it logs out. I have observed Outlook doing this when tracing network traffic between a client and my DBMail POP3 server. I have seen Outlook fail to detect new messages on a POP3 server u...
[ 3 ]
[]
[]
[ "email", "pop3", "python" ]
stackoverflow_0007553606_email_pop3_python.txt
Q: MySQLdb can't use cursorclass I am trying to execute the following code: import MySQLdb import MySQLdb.cursors conn=MySQLdb.connect(host = '127.0.0.1', user = 'root', passwd = 'root', db = 'test', cursorclass = MySQLdb.cursors.Dict...
MySQLdb can't use cursorclass
I am trying to execute the following code: import MySQLdb import MySQLdb.cursors conn=MySQLdb.connect(host = '127.0.0.1', user = 'root', passwd = 'root', db = 'test', cursorclass = MySQLdb.cursors.DictCursor) cursor=conn.cursor() But i...
[ "\n import MySQLdb\n import MySQLdb.cursors\n conn=MySQLdb.connect(host = '127.0.0.1',\n user = 'root', \n passwd = 'root',\n db = 'test',)\ncursor=conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)\n\nThis is a rough hack, but it may not be...
[ 13 ]
[]
[]
[ "mysql_python", "python" ]
stackoverflow_0006160761_mysql_python_python.txt
Q: WxPython Updating Frame to show buttons I am new to wx widgets. I am trying to make a GUI in which I have to show certain buttons based on certain conditions. The problem is that when I create this new button after Frame.show() The button is not visible until I take the mouse over the place the button is supposed ...
WxPython Updating Frame to show buttons
I am new to wx widgets. I am trying to make a GUI in which I have to show certain buttons based on certain conditions. The problem is that when I create this new button after Frame.show() The button is not visible until I take the mouse over the place the button is supposed to be. I tried Frame.Refresh() But that isn't...
[ "You probably just need to call the Frame's Layout() method. That's what I do when I insert or remove a widget. I also recommend learning sizers as they are very handy for automatic sizing and positioning.\n" ]
[ 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007540711_python_wxpython.txt
Q: reading log files in Python and outputing specific text I have a piece of code that reads the last line of a log file as the log is being written to. I want to print errors which occur in the logs, basically start printing when line.startswith('Error') and finish printing when line.startwith('End of Error'). My co...
reading log files in Python and outputing specific text
I have a piece of code that reads the last line of a log file as the log is being written to. I want to print errors which occur in the logs, basically start printing when line.startswith('Error') and finish printing when line.startwith('End of Error'). My code is below, Could anybody help me with this please? log = 'C...
[ "Initialize a flag before the loop:\nin_error = False\n\nThen switch it on and off as needed:\nif line.startswith('Error'):\n in_error = True\nelif line.startswith('End of Error'):\n print(line)\n in_error = False\nif in_error:\n print(line)\n\n", "It may be easier to use the subprocess module to simp...
[ 1, 0 ]
[]
[]
[ "logging", "loops", "python" ]
stackoverflow_0007557057_logging_loops_python.txt
Q: pygame.MOUSEBUTTONDOWN pygame.VIDEORESIZE ERROR? I posted a similar question a few days ago but i have refined the problem: when i have both MOUSEBUTTONDOWN and VIDEORESIZE in the same event loop it doent work... when i click the mouse down it also prints the statement which should only get printed when the MOUSEB...
pygame.MOUSEBUTTONDOWN pygame.VIDEORESIZE ERROR?
I posted a similar question a few days ago but i have refined the problem: when i have both MOUSEBUTTONDOWN and VIDEORESIZE in the same event loop it doent work... when i click the mouse down it also prints the statement which should only get printed when the MOUSEBUTTONUP event occurs.... TRY it your selves this probl...
[ "Don't update the screen at every event, it slows down your program considerably. It's so slow on my computer I can't make any sense of the mouse events. Just moving a couple of lines of your code fixes that and it runs fine.\nimport pygame\nfrom pygame.locals import *\nfrom sys import exit\n\nLEFT = 1\nsize = 520,...
[ 0 ]
[]
[]
[ "pygame", "python" ]
stackoverflow_0007556940_pygame_python.txt
Q: Can I send logout request to radius server with radius client? There is one pptp server and I use radius server for authentication. Sometimes the vpn client is off line with unknow reason , so the radius can not clear the session for client. I want to run one process with radius client to monitor the client, if t...
Can I send logout request to radius server with radius client?
There is one pptp server and I use radius server for authentication. Sometimes the vpn client is off line with unknow reason , so the radius can not clear the session for client. I want to run one process with radius client to monitor the client, if the client has no heartbeat, the process will send logout request to ...
[ "You've tagged your question with several languages.\nAssuming you would like to do this in Python, you can use Pyrad and use one of the method from pyrad.packet.\n" ]
[ 1 ]
[]
[]
[ "freeradius", "linux", "python", "radius", "ruby" ]
stackoverflow_0007550998_freeradius_linux_python_radius_ruby.txt
Q: Which Dynamic Internationalisation system to use in Django projects? I am developing a new project from scratch with Django. I see that there are many apps for handling translation of dynamic content. Django-multilingual Django-pluggable-model-i18n Django-modeltranslation Transdb Django-multilingual-model- Djang...
Which Dynamic Internationalisation system to use in Django projects?
I am developing a new project from scratch with Django. I see that there are many apps for handling translation of dynamic content. Django-multilingual Django-pluggable-model-i18n Django-modeltranslation Transdb Django-multilingual-model- Django-transmeta to name few. Transdb, transmeta and multilingual sounded fair...
[ "I agree with S.Lott in that you will want to think about what you need from internationalization. However, this is a very good run-down of all of the mentioned packages:\nhttp://blog.muhuk.com/2010/01/06/dynamic-translation-apps-for-django.htm\nMy personal pick thus far is \"none of the above\". I am currently pro...
[ 5, 3, 2, 0 ]
[]
[]
[ "django", "internationalization", "python" ]
stackoverflow_0003531813_django_internationalization_python.txt
Q: Why doesn't just a variable name display the variable in a script, like in the interpreter? I want to display a string which is returned by a function in a Python script, without using print: def myfunc(mystring): return "Converting to lowercase :{0}".format(mystring.lower()) result=myfunc("LOWER") result Bu...
Why doesn't just a variable name display the variable in a script, like in the interpreter?
I want to display a string which is returned by a function in a Python script, without using print: def myfunc(mystring): return "Converting to lowercase :{0}".format(mystring.lower()) result=myfunc("LOWER") result But it doesn't give an output. How can I get result to display without print?
[ "Your code does print 'Converting to lowercase :lower' when run in an interactive session (using python or ipython).\nIt does not, however, print anything if run as part of a script, since there is no implicit printing of expression results.\nThis is how it's meant to be.\nIf you want to print something from a scri...
[ 3, 0 ]
[]
[]
[ "interpreter", "printing", "python" ]
stackoverflow_0007557557_interpreter_printing_python.txt
Q: How to interface Ruby with Mercurial (Python)? I'm hoping to integrate Mercurial into my Rails site. I want to run basic commands like status, summary, log, and maybe even clone. I'd like to interface directly with the Mercurial libraries and avoid doing any command line parsing via regex. Mercurial is written in ...
How to interface Ruby with Mercurial (Python)?
I'm hoping to integrate Mercurial into my Rails site. I want to run basic commands like status, summary, log, and maybe even clone. I'd like to interface directly with the Mercurial libraries and avoid doing any command line parsing via regex. Mercurial is written in Python; I am using Ruby. So, I need Mercurial Ruby b...
[ "I would look at the redmine code, and do whatever they do.\n", "\nSo, I need Mercurial Ruby bindings. It seems, however, that there are none.\n\nYou are right. But there is something even better than a Ruby binding to the Python Mercurial implementation: a Ruby (plus little bits of C) Mercurial implementation!\n...
[ 2, 2, 0 ]
[]
[]
[ "language_binding", "mercurial", "python", "ruby" ]
stackoverflow_0002805021_language_binding_mercurial_python_ruby.txt
Q: python: simple way to input python data from file In a shell script one might do something like: myvar='default_value' source myfile.sh echo $myvar where myfile.sh is something like: echo "myvar='special_value'" > myfile.sh I know several "safe" ways of doing this in python, but the only way I can think of getti...
python: simple way to input python data from file
In a shell script one might do something like: myvar='default_value' source myfile.sh echo $myvar where myfile.sh is something like: echo "myvar='special_value'" > myfile.sh I know several "safe" ways of doing this in python, but the only way I can think of getting similar behaviour in Python (albeit ugly and unsafe)...
[ "There are two ways to look at this question.\n\nHow can I read key-value pairs in python? Is there a standard way to do this?\n\nand\n\nHow can I give full expressive power to a configuration script?\n\nIf your question is the first; then the most obvious answer is to use the ConfigParser module:\nfrom ConfigParse...
[ 4 ]
[]
[]
[ "import", "persistence", "python" ]
stackoverflow_0007557607_import_persistence_python.txt
Q: Read string without parsing in Python xml.dom As you probably know, Pythons xml.dom readString() throws an exception, if there is anything wrong with the xml code. I am currently writing a simple xmpp chat server, and as you probably also know, one of the first client request message does not close the stream:stre...
Read string without parsing in Python xml.dom
As you probably know, Pythons xml.dom readString() throws an exception, if there is anything wrong with the xml code. I am currently writing a simple xmpp chat server, and as you probably also know, one of the first client request message does not close the stream:stream tag, until it does not get a reply. Is there any...
[ "DOM parsers always need to read the entire XML file. You want a SAX parser.\n", "Any reason you're not using an already established XMPP library like xmpppy? (See also)\n", "The parser that is likely to give you the best experience is xml.parsers.expat. In your StartElementHandler create a DOM element, and ad...
[ 2, 0, 0 ]
[]
[]
[ "dom", "python", "w3c", "xml", "xmpp" ]
stackoverflow_0007547971_dom_python_w3c_xml_xmpp.txt
Q: Module import Error Python I just installed lxml for parsing xml file in python. I am using TextMate as an IDE. Problem is that when I try to import lxml (from lxml import entree) then I get ImportError:'No module named lxml' But when I use Terminal then everything is fine Python 2.7.2 (v2.7.2:8527427914a2, Jun 1...
Module import Error Python
I just installed lxml for parsing xml file in python. I am using TextMate as an IDE. Problem is that when I try to import lxml (from lxml import entree) then I get ImportError:'No module named lxml' But when I use Terminal then everything is fine Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (A...
[ "This most probably means that you have more than one python installation on your system and that TextMate and the Terminal using different ones by default.\nOne workaround: In your python file, you can specify an interpreter directive to point to the python installation (and executable) of your choice:\n#!/usr/loc...
[ 3, 2, 1, 0 ]
[]
[]
[ "importerror", "lxml", "module", "python" ]
stackoverflow_0007557950_importerror_lxml_module_python.txt
Q: PATH variable in Python How can I change the Environmental PATH variable through code in python ? I am trying to return the path of an executable file. The code does not work because the shell is pointing to another directory. Any help is appreciated. A: You can use os.environ. Example: path = os.environ["PATH"...
PATH variable in Python
How can I change the Environmental PATH variable through code in python ? I am trying to return the path of an executable file. The code does not work because the shell is pointing to another directory. Any help is appreciated.
[ "You can use os.environ.\nExample:\npath = os.environ[\"PATH\"] # a ':'-separated string\npath += \":/var/custom/bin\"\nos.environ[\"PATH\"] = path\n\nOr in a single line:\nos.environ[\"PATH\"] = ':'.join(os.environ[\"PATH\"].split(\":\") + [\"/var/bin\"])\n\n", "You aren't looking for the PATH variable. You want...
[ 4, 2, 1 ]
[]
[]
[ "path", "python" ]
stackoverflow_0007558052_path_python.txt
Q: StringIO with binary files? I seem to get different outputs: from StringIO import * file = open('1.bmp', 'r') print file.read(), '\n' print StringIO(file.read()).getvalue() Why? Is it because StringIO only supports text strings or something? A: When you call file.read(), it will read the entire file into memo...
StringIO with binary files?
I seem to get different outputs: from StringIO import * file = open('1.bmp', 'r') print file.read(), '\n' print StringIO(file.read()).getvalue() Why? Is it because StringIO only supports text strings or something?
[ "When you call file.read(), it will read the entire file into memory. Then, if you call file.read() again on the same file object, it will already have reached the end of the file, so it will only return an empty string.\nInstead, try e.g. reopening the file:\nfrom StringIO import *\n\nfile = open('1.bmp', 'r')\npr...
[ 8, 5 ]
[ "Shouldn't you be using \"rb\" to open, instead of just \"r\", since this mode assumes that you'll be processing only ASCII characters and EOFs?\n" ]
[ -1 ]
[ "file", "python", "string", "stringio" ]
stackoverflow_0007558168_file_python_string_stringio.txt
Q: Parsing text with python and mapping to dictionary words I am trying to build a dictionary with frequent terms for my website. So basically I will retrieve a paragraph from my database and this paragraph most likely will contain terms which appear in the aforementioned dictionary. What I am looking for is a nice w...
Parsing text with python and mapping to dictionary words
I am trying to build a dictionary with frequent terms for my website. So basically I will retrieve a paragraph from my database and this paragraph most likely will contain terms which appear in the aforementioned dictionary. What I am looking for is a nice way (and fast) to parse the paragraph text and map the dictiona...
[ "Something like this?\n>>> s = \"abc def, abcdef\"\n>>> w = {\"abc\": \"xxx\", \"def\": \"yyy\"}\n>>> def replace(text, words):\n... regex = r\"\\b(?:\" + \"|\".join(re.escape(word) for word in words) + r\")\\b\"\n... reobj = re.compile(regex, re.I)\n... return reobj.sub(lambda x:words[x.group(0)], text...
[ 2 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0007558000_parsing_python.txt
Q: Grep for specific sentence that contains [] I have a python script that reports how many times an error shows up in catalina.out within a 17 minute time period. Some errors contain more information, displayed in the next three lines beneath the error. Unfortunately the sentence I'm grepping for contains []. I don'...
Grep for specific sentence that contains []
I have a python script that reports how many times an error shows up in catalina.out within a 17 minute time period. Some errors contain more information, displayed in the next three lines beneath the error. Unfortunately the sentence I'm grepping for contains []. I don't want to do a search using regular expressions. ...
[ "If you're using bash and regular grep, you have to escape the [] chars, i.e. \\[ ... \\], \ngrep 'bob: \\[2012-08-30 02:58:57.326\\] ERROR: web.errors.GrailsExceptionResolver Exception occurred when processing request: \\[GET\\] /bob/event' catalina.out\n\nNot sure if you're really asking how to search for a '17 m...
[ 2, 2, 0 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0007558369_bash_python.txt
Q: Using Python/PyGreSQL, how can I efficiently handle a large result set? I have a query result set of ~ 9-million rows. I need to do some processing for each row, and the code currently does this: query = conn.query(sql) results = query.getresult() for row in results: # blah I'm not sure, but I imagine that...
Using Python/PyGreSQL, how can I efficiently handle a large result set?
I have a query result set of ~ 9-million rows. I need to do some processing for each row, and the code currently does this: query = conn.query(sql) results = query.getresult() for row in results: # blah I'm not sure, but I imagine that getresult() is pulling down the entire result set. Is that the case? I imagi...
[ "If it's following the Python Database API spec, you could use a cursor:\ncurs = conn.cursor()\ncurs.execute('select * from bigtable')\n\nthen use curs.fetchone() or curs.fetchmany(chunksize)\n", "pgdb's cursors are iterators\ncursor = conn.cursor()\ncursor.execute(sql)\n\nfor row in cursor:\n # do something wi...
[ 3, 2, 0, 0 ]
[]
[]
[ "postgresql", "pygresql", "python" ]
stackoverflow_0007476629_postgresql_pygresql_python.txt
Q: Will setuptools work with python 3.2.x Will the setuptools for windows python 2.7 http://pypi.python.org/pypi/setuptools#files be compatible with a python 3.2.x runtime. The installer fails to detect the python settings during an install. Should I wait for a new release? A: NOTE: Answer obsolete, Setuptools now ...
Will setuptools work with python 3.2.x
Will the setuptools for windows python 2.7 http://pypi.python.org/pypi/setuptools#files be compatible with a python 3.2.x runtime. The installer fails to detect the python settings during an install. Should I wait for a new release?
[ "NOTE: Answer obsolete, Setuptools now works for Python 3. Distribute is deprecated.\nSetuptools itself doesn't work on Python 3. But you can use Distribute, a fork and a drop in replacement for setuptools:\nhttp://packages.python.org/distribute/\nhttp://pypi.python.org/pypi/distribute\nFrom the bottom of the page ...
[ 14 ]
[]
[]
[ "python", "python_3.x", "setuptools" ]
stackoverflow_0007558518_python_python_3.x_setuptools.txt
Q: Does lxml parse HTML contextually? I'm using lxml to parse HTML: >>> from lxml.html import fromstring, tostring It parses trailing whitespace correctly in some cases: >>> html = """<div>some <i>text</i> </div>""" >>> html == tostring(fromstring(html)) True But it seems to break when encountering unknown tags (su...
Does lxml parse HTML contextually?
I'm using lxml to parse HTML: >>> from lxml.html import fromstring, tostring It parses trailing whitespace correctly in some cases: >>> html = """<div>some <i>text</i> </div>""" >>> html == tostring(fromstring(html)) True But it seems to break when encountering unknown tags (such as the blah tag below). >>> html = "...
[ "This appears to be due to the behavior of libxml2 (I've removed some error messages from the version below):\n>>> print libxml2.htmlParseDoc(\"\"\"<div>some <blah>text</blah> </div>\"\"\", \"UTF-8\")\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<...
[ 0 ]
[ "You need to set a flag in the parser itself to remove whitespace. I've done this when parsing xml like this:\nfrom lxml import etree\n\nparser = etree.XMLParser(remove_blank_text=True)\n\ndata = etree.parse(open(file),parser)\n\n" ]
[ -1 ]
[ "html", "lxml", "parsing", "python", "xml" ]
stackoverflow_0007185109_html_lxml_parsing_python_xml.txt
Q: A script im robot with xmpppy of python, how to detect network failure? I am using xmpppy libary to write a XMPP IM robot. I want to act on disconnects, but I don't know how to detect disconnects. This could happen if your Jabber server crashes or if you have lost your internet connection. I found the callback, Re...
A script im robot with xmpppy of python, how to detect network failure?
I am using xmpppy libary to write a XMPP IM robot. I want to act on disconnects, but I don't know how to detect disconnects. This could happen if your Jabber server crashes or if you have lost your internet connection. I found the callback, RegisterDisconnectHandler(self, DisconnectHandler), but it didn't work for the ...
[ "Did you try waiting 30 minutes after the network failure? Depending on your network stack's settings, it could take this long to detect. However, if you're not periodically sending on the socket, you may never detect the outage. This is why many XMPP stacks periodically send a single space character, using an a...
[ 0 ]
[]
[]
[ "bots", "python", "xmpp", "xmpppy" ]
stackoverflow_0007536732_bots_python_xmpp_xmpppy.txt
Q: Best practices for Python deployment -- multiple versions, standard install locations, packaging tools etc Many posts on different aspects of this question but I haven't seen a post that brings it all together. First a subjective statement: it seems like the simplicity we experience when working with the Python la...
Best practices for Python deployment -- multiple versions, standard install locations, packaging tools etc
Many posts on different aspects of this question but I haven't seen a post that brings it all together. First a subjective statement: it seems like the simplicity we experience when working with the Python language is shot to pieces when we move outside the interpreter and start grappling with deployment issues. How b...
[ "I've found that virtualenv is the only reliable way to configure and maintain multiple environments on the same machine. It even has as a way of packaging up environment and installing it on another machine.\nFor package management I always use pip since it works so nicely with virtualenv. It also makes it easy to...
[ 8, 3, 0 ]
[]
[]
[ "distutils", "multiple_versions", "pip", "python", "virtualenv" ]
stackoverflow_0007232061_distutils_multiple_versions_pip_python_virtualenv.txt
Q: wsgi - processing unicode characters from post python 2.7 raw = '%C3%BE%C3%A6%C3%B0%C3%B6' #string from wsgi post_data raw_uni = raw.replace('%', r'\x') raw_uni # gives '\\xC3\\xBE\\xC3\\xA6\\xC3\\xB0\\xC3\\xB6' print raw uni #gives '\xC3\xBE\xC3\xA6\xC3\xB0\xC3\xB6' uni = unicode(raw_uni, 'utf-8') uni #gives u'\\...
wsgi - processing unicode characters from post
python 2.7 raw = '%C3%BE%C3%A6%C3%B0%C3%B6' #string from wsgi post_data raw_uni = raw.replace('%', r'\x') raw_uni # gives '\\xC3\\xBE\\xC3\\xA6\\xC3\\xB0\\xC3\\xB6' print raw uni #gives '\xC3\xBE\xC3\xA6\xC3\xB0\xC3\xB6' uni = unicode(raw_uni, 'utf-8') uni #gives u'\\xC3\\xBE\\xC3\\xA6\\xC3\\xB0\\xC3\\xB6+\\xC3\\xA9g' ...
[ "You should be using urllib.unquote, not a manual replace:\n>>> import urllib\n>>> raw = '%C3%BE%C3%A6%C3%B0%C3%B6'\n>>> urllib.unquote(raw)\n'\\xc3\\xbe\\xc3\\xa6\\xc3\\xb0\\xc3\\xb6'\n>>> unicode(urllib.unquote(raw), 'utf-8')\nu'\\xfe\\xe6\\xf0\\xf6'\n\nThe underlying issue here is that you have a fundamental mis...
[ 3 ]
[]
[]
[ "post", "python", "unicode", "wsgi" ]
stackoverflow_0007558758_post_python_unicode_wsgi.txt
Q: numpy and pysparse floating point representation problem I have started using numpy along with pysparse package which interfaces UMFPACK, however there is a problem with the floating point results with numpy. By the way, this is a lanczos eigenvalue solver for structural problems. When I do the same operations in ...
numpy and pysparse floating point representation problem
I have started using numpy along with pysparse package which interfaces UMFPACK, however there is a problem with the floating point results with numpy. By the way, this is a lanczos eigenvalue solver for structural problems. When I do the same operations in MATLAB I get different results, well the results are on the or...
[ "float64 is the default data type in Numpy. You could try using float128 for more precision, but be warned that certain functions (and basically everything on Windows) will coerce it to float64 anyway.\nI would recommend using scipy.sparse for your sparse eigenvector problems. I have tried both PySparse and scipy.s...
[ 2 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006179156_numpy_python.txt
Q: update foreignkey items from django shell Following is the models.py: class UserProfile(models.Model): user = models.OneToOneField(User) belongs_to_user_category = models.ForeignKey(UserCustomCategory, null=True, blank=True) class UserHistory(models.Model): date_time = models.DateTimeField() user ...
update foreignkey items from django shell
Following is the models.py: class UserProfile(models.Model): user = models.OneToOneField(User) belongs_to_user_category = models.ForeignKey(UserCustomCategory, null=True, blank=True) class UserHistory(models.Model): date_time = models.DateTimeField() user = models.ForeignKey(UserProfile, null=True, bla...
[ "When you use the create method of the default model manager in Django, it will also attempt to create that instance into the database and save it. You can do this in two ways, but I'll show you what you can do with your approach, which may help in some understanding.\nFirst, you will want to create a UserHistory o...
[ 1 ]
[]
[]
[ "django_1.3", "django_models", "foreign_keys", "python" ]
stackoverflow_0007554969_django_1.3_django_models_foreign_keys_python.txt
Q: Unpacking a list / tuple of pairs into two lists / tuples I have a list that looks like this: list = (('1','a'),('2','b'),('3','c'),('4','d')) I want to separate the list in 2 lists. list1 = ('1','2','3','4') list2 = ('a','b','c','d') I can do it for example with: list1 = [] list2 = [] for i in list: list1.ap...
Unpacking a list / tuple of pairs into two lists / tuples
I have a list that looks like this: list = (('1','a'),('2','b'),('3','c'),('4','d')) I want to separate the list in 2 lists. list1 = ('1','2','3','4') list2 = ('a','b','c','d') I can do it for example with: list1 = [] list2 = [] for i in list: list1.append(i[0]) list2.append(i[1]) But I want to know if there i...
[ ">>> source_list = [('1','a'),('2','b'),('3','c'),('4','d')]\n>>> list1, list2 = zip(*source_list)\n>>> list1\n('1', '2', '3', '4')\n>>> list2\n('a', 'b', 'c', 'd')\n\nEdit: Note that zip(*iterable) is its own inverse:\n>>> list(source_list) == zip(*zip(*source_list))\nTrue\n\nWhen unpacking into two lists, this be...
[ 479, 36 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0007558908_list_python_tuples.txt
Q: How would I search and replace multiple regexes using python re Possible Duplicate: Python replace multiple strings I am looking to replace “ “, “\r”, “\n”, “<”, “>”, “’” (single quote), and ‘”’ (double quote) with “” (empty). I’m also looking to replace “;” and “|” with “,”. Would this be handled by re.search s...
How would I search and replace multiple regexes using python re
Possible Duplicate: Python replace multiple strings I am looking to replace “ “, “\r”, “\n”, “<”, “>”, “’” (single quote), and ‘”’ (double quote) with “” (empty). I’m also looking to replace “;” and “|” with “,”. Would this be handled by re.search since I want to be able to search anywhere in the text, or would I us...
[ "If you want to remove all occurrences of those characters, just put them all in a character class and do re.sub()\nyour_str = re.sub(r'[ \\r\\n\\'\"]+', '', your_str)\nyour_str = re.sub(r'[;|]', ',', your_str)\n\nYou have to call re.sub() for every replacement rule.\n", "If you need to replace only single charac...
[ 4, 4, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007558814_python_regex.txt
Q: What's the difference between setattr() and object.__setattr__()? I know that you can't call object.__setattr__ on objects not inherited from object, but is there anything else that is different between the two? I'm working in Python 2.6, if this matters. A: Reading this question again I misunderstood what @pape...
What's the difference between setattr() and object.__setattr__()?
I know that you can't call object.__setattr__ on objects not inherited from object, but is there anything else that is different between the two? I'm working in Python 2.6, if this matters.
[ "Reading this question again I misunderstood what @paper.cut was asking about: the difference between classic classes and new-style classes (not an issue in Python 3+). I do not know the answer to that.\n\nOriginal Answer*\nsetattr(instance, name, value) is syntactic sugar for instance.__setattr__(name, value)**.\...
[ 17 ]
[]
[]
[ "python", "setattr" ]
stackoverflow_0007559170_python_setattr.txt
Q: Python: handling a large set of data. Scipy or Rpy? And how? In my python environment, the Rpy and Scipy packages are already installed. The problem I want to tackle is such: 1) A huge set of financial data are stored in a text file. Loading into Excel is not possible 2) I need to sum a certain fields and get the...
Python: handling a large set of data. Scipy or Rpy? And how?
In my python environment, the Rpy and Scipy packages are already installed. The problem I want to tackle is such: 1) A huge set of financial data are stored in a text file. Loading into Excel is not possible 2) I need to sum a certain fields and get the totals. 3) I need to show the top 10 rows based on the totals. Wh...
[ "Neither Rpy or Scipy is necessary, although numpy may make it a bit easier.\nThis problem seems ideally suited to a line-by-line parser.\nSimply open the file, read a row into a string, scan the row into an array (see numpy.fromstring), update your running sums and move to the next line.\n", "Python's File I/O d...
[ 5, 3, 2, 2, 1, 1 ]
[]
[]
[ "memory_mapped_files", "numpy", "python", "r", "scipy" ]
stackoverflow_0006853923_memory_mapped_files_numpy_python_r_scipy.txt
Q: matplotlib interactive mode: determine if figure window is still displayed I am using matplotlib in interactive mode to show the user a plot that will help them enter a range of variables. They have the option of hitting "?" to show this plot, and the prompt for variables will then be repeated. How do I know to n...
matplotlib interactive mode: determine if figure window is still displayed
I am using matplotlib in interactive mode to show the user a plot that will help them enter a range of variables. They have the option of hitting "?" to show this plot, and the prompt for variables will then be repeated. How do I know to not re-draw this plot if it's still being displayed? Superficially, I have this ...
[ "In the same vein as unutbu's answer, you can also check whether a given figure is still opened with \nimport matplotlib.pyplot as plt\n\nif plt.fignum_exists(<figure number>):\n # Figure is still opened\nelse:\n # Figure is closed\n\nThe figure number of a figure is in fig.number.\nPS: Note that the \"number...
[ 33, 23 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007557098_matplotlib_python.txt
Q: python input for itertools.product Looking for a way to simulate nested loops (or a cartesian product) i came across the itertools.product function. i need a function or piece of code that receive a list of integers as input and returns a specific generator. example: input = [3,2,4] -> gen = product(xrange(3),x...
python input for itertools.product
Looking for a way to simulate nested loops (or a cartesian product) i came across the itertools.product function. i need a function or piece of code that receive a list of integers as input and returns a specific generator. example: input = [3,2,4] -> gen = product(xrange(3),xrange(2),xrange(4)) or input = [2,4,5,6]...
[ "def bigproduct(*args):\n newargs = [xrange(x) for x in args]\n return itertools.product(*newargs)\n\nfor i in bigproduct(3, 2, 4):\n ....\n\nrange() generates a list up-front, therefore uses time up front and more space, but takes less time to get each element. xrange() generates each element on the fly, so ta...
[ 2 ]
[ "This can be easily accomplished using map:\nfrom itertools import product\nfor i in product(*map(range, shape)):\n print i\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0003020684_python.txt
Q: iotop script does not work via custom script execution I have CSF installed (configure safe firewall), it has a function to allow you to have custom scripts executed on load average events. My script: ##!/usr/bin/env bash iotop -bto --iter=1 2>&1 | mail -s "$HOSTNAME iotop output" incidents@ It works fine via bas...
iotop script does not work via custom script execution
I have CSF installed (configure safe firewall), it has a function to allow you to have custom scripts executed on load average events. My script: ##!/usr/bin/env bash iotop -bto --iter=1 2>&1 | mail -s "$HOSTNAME iotop output" incidents@ It works fine via bash shell but when executed by lfd (the monitoring process of ...
[ "Internally it calls an equivalent of:\nimport os\nimport sys\n\nf = os.popen('file -b \"%s\" 2> %s' % (sys.executable, os.devnull))\nf.read()\nf.close()\n\nFor popen() to work it has to be able to get the SIGCHLD signal telling it that a child process exited. It seems that the environment that executes iotop has a...
[ 1, 0 ]
[]
[]
[ "bash", "linux", "python" ]
stackoverflow_0007559420_bash_linux_python.txt
Q: How can i sort this dict per datetime? How can i sort this dict per datetime? Is it possible? { 1: {'l':{'created_on': datetime.datetime(2011, 9, 29, 17, 39, 26)}}, 2: {'l':{'created_on': datetime.datetime(2011, 9, 23, 17, 39, 26)}}, 3: {'l':{'created_on': datetime.datetime(2011, 9, 30, 17, 39, 26)}} } A: You ca...
How can i sort this dict per datetime?
How can i sort this dict per datetime? Is it possible? { 1: {'l':{'created_on': datetime.datetime(2011, 9, 29, 17, 39, 26)}}, 2: {'l':{'created_on': datetime.datetime(2011, 9, 23, 17, 39, 26)}}, 3: {'l':{'created_on': datetime.datetime(2011, 9, 30, 17, 39, 26)}} }
[ "You can call the sorted() function on the values, with the datetime as the comparison key:\nsorted(d.values(), key=lambda item: item[\"l\"][\"created_on\"])\n\n", "You can get a sorted list of keys for your dictionary d (dictionaries cannot be sorted by themselves):\n>>> sorted(d.keys(), key=lambda k: d[k]['l'][...
[ 4, 3, 1 ]
[]
[]
[ "datetime", "dictionary", "python" ]
stackoverflow_0007559712_datetime_dictionary_python.txt
Q: Working with python dictionary notation I'm working on a program where the user inputs 3 values (one of which is in dictionary notation form).. but I'm having trouble finding out how to work with this special notation. The user input will look like this: {'X':'X+YF','Y':'FX-Y'} which I store in a variable p. I...
Working with python dictionary notation
I'm working on a program where the user inputs 3 values (one of which is in dictionary notation form).. but I'm having trouble finding out how to work with this special notation. The user input will look like this: {'X':'X+YF','Y':'FX-Y'} which I store in a variable p. I know that with p.keys() I get ['X', 'Y'] and...
[ "Are you asking how to get the value associated to a particular key? You can acess a value by putting its key in square brackets:\nmyDict = {'X':'X+YF','Y':'FX-Y'}\nmyXVal = myDict['X']\nmyYVal = myDict['Y']\nprint myXVal, myYVal\n\noutput:\nX+YF FX-Y\n\nIf you want to have different behavior based on which keys ex...
[ 3, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007559537_python.txt
Q: Regular expression for validating year starting from 2020 I am writing a regular expression to validate year starting from 2020. The below is the regular expression I wrote, ^(20-99)(20-99)$ It doesn't seem to work. Can anyone point out where did I get it wrong? A: Regular expressions don't take ranges like tha...
Regular expression for validating year starting from 2020
I am writing a regular expression to validate year starting from 2020. The below is the regular expression I wrote, ^(20-99)(20-99)$ It doesn't seem to work. Can anyone point out where did I get it wrong?
[ "Regular expressions don't take ranges like that. You'll want to do something like:\nif( year >= 2020 )\n presto\n\nI'm being flippant because you're trying to use a regular expression where you can just use a straight-forward comparison. If you have a string, convert the string into an integer first (if you even ...
[ 5, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007559692_python_regex.txt
Q: "My Contacts" group google contacts I just wrote a small python script that gets me all the groups on my google contacts list, however for some reason "My Contacts" does not show up in that. I'm using the 3.0 api and was having similar problems with the 2.0 api too. The following is an except taken from the Google...
"My Contacts" group google contacts
I just wrote a small python script that gets me all the groups on my google contacts list, however for some reason "My Contacts" does not show up in that. I'm using the 3.0 api and was having similar problems with the 2.0 api too. The following is an except taken from the Google 2.0 Contacts documentation. To determin...
[ "Why not use the Python Client Library directly? It includes a set of methods that do exactly what you want.\nimport gdata.contacts.client\nimport gdata.contacts.data # you might also need atom.data, gdata.data\n\ngd_client = gdata.contacts.data.ContactsClient(source='eQuiNoX_Contacts')\ngd_client.ClientLogin('equ...
[ 2 ]
[]
[]
[ "google_contacts_api", "python" ]
stackoverflow_0007556375_google_contacts_api_python.txt
Q: Using math.factorial in a lambda function with reduce() I'm attempting to write a function that calculates the number of unique permutations of a string. For example aaa would return 1 and abc would return 6. I'm writing the method like this: (Pseudocode:) len(string)! / (A!*B!*C!*...) where A,B,C are the numbe...
Using math.factorial in a lambda function with reduce()
I'm attempting to write a function that calculates the number of unique permutations of a string. For example aaa would return 1 and abc would return 6. I'm writing the method like this: (Pseudocode:) len(string)! / (A!*B!*C!*...) where A,B,C are the number of occurrences of each unique character. For example, the s...
[ "See the documentation for reduce(), there is an optional 'initializer' argument that is placed before all other elements in the list so that the behavior for one element lists is consistent, for example, for your ord() lambda you could set initializer to the the character with an ord() of 0:\n>>> reduce(lambda x, ...
[ 2, 1, 1, 0 ]
[]
[]
[ "factorial", "lambda", "permutation", "python", "reduce" ]
stackoverflow_0007560284_factorial_lambda_permutation_python_reduce.txt
Q: Provide a folder out of source where all my external libraries are found I have the following folder structure lib my_module I have moved all the libraries I need into the lib/ folder. In my module/__init__.py, I think I will do: import sys sys.path.append('../lib/') import my_dependency Then when I need to use...
Provide a folder out of source where all my external libraries are found
I have the following folder structure lib my_module I have moved all the libraries I need into the lib/ folder. In my module/__init__.py, I think I will do: import sys sys.path.append('../lib/') import my_dependency Then when I need to use this dependency, I will refer to it as my_module.my_dependency Is this a bad...
[ "sys.path.append('../lib/') assumes that the current working directory is the directory of your script, which may or may not be the case.\nA version that doesn't depend on the working directory is:\nimport sys, os\nsys.path.append(os.path.join(os.path.split(os.path.split(os.path.abspath(sys.argv[0]))[0])[0], \"lib\...
[ 1, 0 ]
[]
[]
[ "import", "python" ]
stackoverflow_0007560293_import_python.txt
Q: python: method depends on whether param is int or string Is there a more pythonic way to write __getitem__ than the following? The issue is checking type and doing different things depending on the type of the parameter in the call. class This(): def __init__(self, name, value): self.name, self.value =...
python: method depends on whether param is int or string
Is there a more pythonic way to write __getitem__ than the following? The issue is checking type and doing different things depending on the type of the parameter in the call. class This(): def __init__(self, name, value): self.name, self.value = name, value class That(): def __init__(self): se...
[ "There are quite a few options, but I think there is not one best choice. It depends on your use case and preferences. Just to give you a few hints:\nDo you really have to store the data in a list? In your example you could use a dictionary and insert the object twice: Once using the integer as key and once using t...
[ 2, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007534271_python.txt
Q: Make SQLAlchemy COMMIT instead of ROLLBACK after a SELECT query I am developing an app together with a partner. I do the database part (PostgreSQL), my partner implements the app on the web-server with python using SQLAlchemy. We make heavy use of stored procedures. A SELECT query on one of those looks like this i...
Make SQLAlchemy COMMIT instead of ROLLBACK after a SELECT query
I am developing an app together with a partner. I do the database part (PostgreSQL), my partner implements the app on the web-server with python using SQLAlchemy. We make heavy use of stored procedures. A SELECT query on one of those looks like this in the db log: SET TRANSACTION ISOLATION LEVEL READ COMMITTED; SELECT...
[ "If you're using SQLAlchemy's connection pooling, then what you're seeing is probably the automatic rollback that happens when a connection is closed after use. It's apparently necessary to guarantee that the connection is 'clean' for the next time it's pulled out of the pool. See this page for more info; search ...
[ 9 ]
[]
[]
[ "commit", "postgresql", "python", "sqlalchemy", "transactions" ]
stackoverflow_0007559570_commit_postgresql_python_sqlalchemy_transactions.txt
Q: Django Admin Problem Coercing to Unicode Trying to create a Django app based off the tutorial but using a different model.(First time using Djanago) I'm at the part where you alter the Admin panel to add 3 items with a dependent foreign key. I know the problem originates from the class EventAdmin(admin.ModelAdmin...
Django Admin Problem Coercing to Unicode
Trying to create a Django app based off the tutorial but using a different model.(First time using Djanago) I'm at the part where you alter the Admin panel to add 3 items with a dependent foreign key. I know the problem originates from the class EventAdmin(admin.ModelAdmin): on line 10 of admin.py but I'm not sure ho...
[ "The .__unicode__() method is expected to return a unicode object.\nYour Event.__unicode__() however returns self.location which is a Location instance. Either have it cast self.location to unicode or explicitly reference a field in the Location object.\ndef __unicode__(self):\n return u'%s' % (self.location, )\...
[ 4 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0007560641_django_django_admin_python.txt
Q: How should I account for subprocess.Popen() overhead when timing in python? more-intelligent-members-of-the-coding-community-than-I! I have a python question for you all... :) I am trying to optimize a python script that is (among other things) returning the wall-clock time a subprocess took execute and terminate....
How should I account for subprocess.Popen() overhead when timing in python?
more-intelligent-members-of-the-coding-community-than-I! I have a python question for you all... :) I am trying to optimize a python script that is (among other things) returning the wall-clock time a subprocess took execute and terminate. I think I'm close with something like this. startTime = time.time() process = su...
[ "Welcome to batteries included.\n" ]
[ 0 ]
[]
[]
[ "cross_platform", "python", "subprocess", "time" ]
stackoverflow_0007560708_cross_platform_python_subprocess_time.txt