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: WTForms "too many values to unpack" with SelectField I'm using WTForms and I'm trying to display a SelectField, but I get the following error: >>> form.status() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\Lib\site-packages\wtforms\fields.py", line 136, in __call__ ...
WTForms "too many values to unpack" with SelectField
I'm using WTForms and I'm trying to display a SelectField, but I get the following error: >>> form.status() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\Lib\site-packages\wtforms\fields.py", line 136, in __call__ return self.widget(self, **kwargs) File "C:\Python26\...
[ "It expects a list of (str, str) tuples, not a list of strings.\n", "Never mind, it needs tuples, not strings:\n>>> form.status.choices = [(status, status) for status in Test.statuses()]\n>>> form.status()\nu'<select id=\"status\" name=\"status\"><option value=\"Status1\">Status1</option></select>'\n\n" ]
[ 24, 6 ]
[]
[]
[ "forms", "python", "wtforms" ]
stackoverflow_0006417935_forms_python_wtforms.txt
Q: Passing session info from python to flex I have a simple site made with python (django). User registers, inputs some basic info and it stores it to mysql. User then is able to log in with his username/password which he created... Now i want to add a flex application which will run once the user is logged in, but...
Passing session info from python to flex
I have a simple site made with python (django). User registers, inputs some basic info and it stores it to mysql. User then is able to log in with his username/password which he created... Now i want to add a flex application which will run once the user is logged in, but i dont want the user to have to log in twice ...
[ "If your Python/DJango app uses cookies for tracking sessions; then you just have to make sure that your SWF is served off the same domain that the Python app is served from. \nThe Flash Player will pass the appropriate cookies to the remote server whenever it makes a call to that server. As long as your \"Flash ...
[ 2 ]
[]
[]
[ "apache_flex", "django", "pyamf", "python" ]
stackoverflow_0006417986_apache_flex_django_pyamf_python.txt
Q: numpy calling sse2 via ctypes In brief, I am trying to call into a shared library from python, more specifically, from numpy. The shared library is implemented in C using sse2 instructions. Enabling optimisation, i.e. building the library with -O2 or –O1, I am facing strange segfaults when calling into the shared ...
numpy calling sse2 via ctypes
In brief, I am trying to call into a shared library from python, more specifically, from numpy. The shared library is implemented in C using sse2 instructions. Enabling optimisation, i.e. building the library with -O2 or –O1, I am facing strange segfaults when calling into the shared library via ctypes. Disabling optim...
[ "I just got bitten by this trying to call some SSE-code from python, the problem seems to be that GCC wants to assume that the stack is aligned on 16-byte boundaries (the largest native type on the architecture, i.e. the SSE-types), and calculates all offset with that assumption. When that assumption is false, the ...
[ 2, 1 ]
[ "Have you try upgrading to Numpy 1.5.0b2. Just run the following (but be careful it might break other things (you will have to recompile all pyrex):\nsudo easy_install -U numpy\n\nI was having similar problems with ctypes when I was trying to use H5PY (I had to recompile the .deb to get with the latest version of ...
[ -1 ]
[ "ctypes", "numpy", "python", "sse2" ]
stackoverflow_0003045158_ctypes_numpy_python_sse2.txt
Q: Google App Engine __main__ module I'm building a data seeder module that looks for all models using introspection and the inspect module. I index the models I found by a string looking like module.model_name because there might be more modules with the same name in different modules. The problem is that module som...
Google App Engine __main__ module
I'm building a data seeder module that looks for all models using introspection and the inspect module. I index the models I found by a string looking like module.model_name because there might be more modules with the same name in different modules. The problem is that module sometimes is indeed the right module name,...
[ "each script entry in your app.yaml will be executed as a __main__ module. If you only want a single __main__ then you need to run everything through a single entry-point and map everything via a single WSGIApplication instance. \n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006415316_google_app_engine_python.txt
Q: installing easy_install for Python 2.6.2 (missing?) I am not a python user, I'm just trying to get couchdb-dump up and running and it's in an "egg" file which I guess needs easy_install. I have Python 2.6.2 running on my computer but it seems to know nothing about easy_install or setuptools... help! What can I do ...
installing easy_install for Python 2.6.2 (missing?)
I am not a python user, I'm just trying to get couchdb-dump up and running and it's in an "egg" file which I guess needs easy_install. I have Python 2.6.2 running on my computer but it seems to know nothing about easy_install or setuptools... help! What can I do to fix this??? edit: you may note from the setuptools pa...
[ "I don't like the whole easy_install thing either.\nBut the solution is to download the source, untar it, and type \npython setup.py install\n\n", "http://pypi.python.org/pypi/setuptools\n... has been updated and has windows installers for Python 2.6 and 2.7\n(note: if you need 64-bit windows installer: http://ww...
[ 7, 1, 0 ]
[]
[]
[ "easy_install", "python" ]
stackoverflow_0001106574_easy_install_python.txt
Q: ** (times times) in Python Possible Duplicate: What does the ** operator do in Python? What does the ** do/mean in following python code? range(2,int(startnumber**0.5)+1) I was working with some Fibonacci numbers and fell over the function on the internet. Can't seem to find it in the documentation A: It mean...
** (times times) in Python
Possible Duplicate: What does the ** operator do in Python? What does the ** do/mean in following python code? range(2,int(startnumber**0.5)+1) I was working with some Fibonacci numbers and fell over the function on the internet. Can't seem to find it in the documentation
[ "It means \"to the power of.\" So x**2 means x squared, and x**0.5 means the square root of x.\n" ]
[ 13 ]
[]
[]
[ "math", "python" ]
stackoverflow_0006418431_math_python.txt
Q: Getting type/size of `time_t` using ctypes I'm accessing a C struct which contains some time_t fields using python ctypes module. Given its non completely portable nature, I cannot define these fields statically as of c_int or c_long type. How can I define them to make my code portable? Example C struct definition...
Getting type/size of `time_t` using ctypes
I'm accessing a C struct which contains some time_t fields using python ctypes module. Given its non completely portable nature, I cannot define these fields statically as of c_int or c_long type. How can I define them to make my code portable? Example C struct definition: #import <sys/types.h> #import <time.h> typede...
[ "Your best bet is by introspecting the system your script runs on and making a best bet on which integral type to use. Something like,\nif sys.platform == 'win32':\n time_t = ctypes.c_uint64\n# ...\n\nThe bottom line is that time_t is not defined in the standard. It's up to the OS and compiler. So your definitio...
[ 3 ]
[]
[]
[ "c", "ctypes", "python", "struct" ]
stackoverflow_0006418221_c_ctypes_python_struct.txt
Q: Error when defining python class (threading) class Downloader(threading.Thread): def __init__(self, priority_level, output_function): self.IDs = self.load_IDs(priority_level) self.sleep_interval = self.gen_sleep(priority_level) self.output = output_function self.name = '[Downloa...
Error when defining python class (threading)
class Downloader(threading.Thread): def __init__(self, priority_level, output_function): self.IDs = self.load_IDs(priority_level) self.sleep_interval = self.gen_sleep(priority_level) self.output = output_function self.name = '[Downloader::%s]'%(str(priority_level)) self.outp...
[ "I think you're missing a closing paren at this line:\nself.output('[Downloader] New downloader created (prio: %s)!'%(str(priority_level))\n\n" ]
[ 4 ]
[]
[]
[ "class", "multithreading", "python" ]
stackoverflow_0006418718_class_multithreading_python.txt
Q: Django: Convert a POST request parameters to query string As per subject, I am receiving a POST request. I want to convert it to the equivalent GET request and pass it to a template (so I can use it as href target in click-to-sort column headers). Is there a pre-baked way to do it, or do I need to roll my own? Che...
Django: Convert a POST request parameters to query string
As per subject, I am receiving a POST request. I want to convert it to the equivalent GET request and pass it to a template (so I can use it as href target in click-to-sort column headers). Is there a pre-baked way to do it, or do I need to roll my own? Cheers, alf UPDATE This is what I eventually used. I needed reques...
[ "Use\nrequest.POST.urlencode()\n", "Use the standard library, urllib.urlencode. e.g.\n>>> import urllib\n>>> urllib.urlencode({'a': 1, 'b': 2})\n'a=1&b=2'\n\n", "From the docs\nrequest.META['QUERY_STRING']\n\n" ]
[ 10, 7, 1 ]
[]
[]
[ "django", "python", "query_string" ]
stackoverflow_0005592756_django_python_query_string.txt
Q: Python query: iterating through log file Please can someone help me solve the following query? I have a log file with thousands of lines like the following:- jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 1 timestamp: 00:00:02,217 jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 ack: 13 timestamp: 00:00:04,5...
Python query: iterating through log file
Please can someone help me solve the following query? I have a log file with thousands of lines like the following:- jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 1 timestamp: 00:00:02,217 jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 ack: 13 timestamp: 00:00:04,537 jarid: 462c6d11-9151-11e0-a72c-00238bbd...
[ "Based on JBernardo's answer, but using defaultdict instead of setdefault. You can print it exactly the same way, so I won't copy that code here\nfrom collections import defaultdict\nlog = ['jarid: 7e5ae720-9151-11e0-eff2-00238bce4216 recv: 1 timestamp: 00:00:02,217',\n 'jarid: 7e5ae720-9151-11e0-eff2-00238bc...
[ 2, 0, 0, 0, 0 ]
[]
[]
[ "dictionary", "iteration", "python" ]
stackoverflow_0006418580_dictionary_iteration_python.txt
Q: Django-compress not getting javascript I am using Django-compress to compress my css and js files. Relevant snippets as follows. settings COMPRESS = True COMPRESS_VERSION = True COMPRESS_CSS = { 'css_all': { 'source_filenames': (CSS_ROOT + 'main.css', CSS_ROOT + 'jquery-ui...
Django-compress not getting javascript
I am using Django-compress to compress my css and js files. Relevant snippets as follows. settings COMPRESS = True COMPRESS_VERSION = True COMPRESS_CSS = { 'css_all': { 'source_filenames': (CSS_ROOT + 'main.css', CSS_ROOT + 'jquery-ui-1.7.1.custom.css', ...
[ "Django-compress is searching for CSS and JS files in MEDIA_ROOT so im sure there is a problem. Also u can specify prefix in extra_context \n" ]
[ 0 ]
[]
[]
[ "django", "javascript", "python", "templates" ]
stackoverflow_0006184175_django_javascript_python_templates.txt
Q: Efficient Django Query Little new to the Django way of doing things, but I have a series of loops that I am sure can be done more efficiently. Essentially I have a group of related objects that I need to drill down the graph to retrieve the values from the end related object. I am looping down the objects to eve...
Efficient Django Query
Little new to the Django way of doing things, but I have a series of loops that I am sure can be done more efficiently. Essentially I have a group of related objects that I need to drill down the graph to retrieve the values from the end related object. I am looping down the objects to eventually get the values I wan...
[ "Yes, you're going about it backwards. This is a problem I've had many times when working with Django. It's easiest to start with the object you want to retrieve and work backwards to meet all the conditions. i.e., it looks like you want some information about this metatag, so start with that.\nMetaTag.objects.filt...
[ 4, 1, 0 ]
[]
[]
[ "django", "django_models", "python", "sql" ]
stackoverflow_0006419384_django_django_models_python_sql.txt
Q: Python special characters in Strings I am trying to show email within a webpage. The program is written in Python. Unfortunately, I have some character encoding issues. I have quotes and double quotes in the text. Original mail: “All is good” ‘it is getting better’ with character set 'windows-1252' I get from ...
Python special characters in Strings
I am trying to show email within a webpage. The program is written in Python. Unfortunately, I have some character encoding issues. I have quotes and double quotes in the text. Original mail: “All is good” ‘it is getting better’ with character set 'windows-1252' I get from the ISP: =93All is good=94 =91it is gettin...
[ "Why are you replacing anything with anything?\n>>> m = email.message_from_string('''Content-Type: text/plain; utf-8\\nContent-Transfer-Encoding: quoted-printable\\n\\n=E2=80=9CAll is good=E2=80=9D\\n=E2=80=98it is getting better=E2=80=99''')\n>>> m.get_payload(decode=True).decode(m['Content-Type'].split('; ')[1])u...
[ 3, 0 ]
[]
[]
[ "character", "email", "encoding", "python" ]
stackoverflow_0006405834_character_email_encoding_python.txt
Q: Python (Portable 2.5) subprocess report problem "WindowsError: [Error 3] The system cannot find the path specified" I am using python and the codes are all worked well with non-portable version. Since I need to run the program on some computer that does not belong to me, which does not have installed python or suc...
Python (Portable 2.5) subprocess report problem "WindowsError: [Error 3] The system cannot find the path specified"
I am using python and the codes are all worked well with non-portable version. Since I need to run the program on some computer that does not belong to me, which does not have installed python or such option available. I use portable python instead. However the codes previously works well now report error"WindowsError:...
[ "Ah, the problem is in the cmdStr variable. You must use absolute paths, or else have the user the process is running under have an appropriately setup PATH system variable. That or you have shell=False, which can cause problems in the subprocess module. Check the documentation for issues concerning paths etc.\n", ...
[ 1, 0, 0 ]
[]
[]
[ "popen", "portability", "python", "subprocess" ]
stackoverflow_0006415651_popen_portability_python_subprocess.txt
Q: How to make a TextBox/Status Box in pygame for an rpg? I need to create a TextBox / MessageBox /StatusBox etc. for my rpg. I have made a Text Box class but it does not seem to work. It blits the surface but doesnt display any text. CODE: class TextBox(pygame.sprite.Sprite): def __init__(self): pygame...
How to make a TextBox/Status Box in pygame for an rpg?
I need to create a TextBox / MessageBox /StatusBox etc. for my rpg. I have made a Text Box class but it does not seem to work. It blits the surface but doesnt display any text. CODE: class TextBox(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.initFont() ...
[ "Umm Sorry. Never Mind. I found the problem myself. I wrote :\n self.rect.center = (0,0)\n\nwhere it should have been\n self.rect.top = 0 ; self.rect.left = 0\n\nThanks Anyway. :D\n" ]
[ 5 ]
[]
[]
[ "pygame", "python", "text" ]
stackoverflow_0006401800_pygame_python_text.txt
Q: Resize the terminal with Python? I couldn't find anything with a quick Google search, nor anything on here, saving for this. However, it doesn't do the trick. So how exactly do you resize the terminal using Python? A: To change the tty/pty setting you have to use an ioctl on the stdin file descriptor. import ter...
Resize the terminal with Python?
I couldn't find anything with a quick Google search, nor anything on here, saving for this. However, it doesn't do the trick. So how exactly do you resize the terminal using Python?
[ "To change the tty/pty setting you have to use an ioctl on the stdin file descriptor.\nimport termios\nimport struct\nimport fcntl\n\ndef set_winsize(fd, row, col, xpix=0, ypix=0):\n winsize = struct.pack(\"HHHH\", row, col, xpix, ypix)\n fcntl.ioctl(fd, termios.TIOCSWINSZ, winsize)\n\nBut to change the actua...
[ 25, 1 ]
[]
[]
[ "python", "terminal" ]
stackoverflow_0006418678_python_terminal.txt
Q: How does python process a signal? What is the workflow of processing a signal in python ? I set a signal handler, when the signal occur ,how does python invoke my function? Does the OS invoke it just like C program? If I am in a C extend of python ,is it interrupted immediately ? Now it's clear to me how does pyt...
How does python process a signal?
What is the workflow of processing a signal in python ? I set a signal handler, when the signal occur ,how does python invoke my function? Does the OS invoke it just like C program? If I am in a C extend of python ,is it interrupted immediately ? Now it's clear to me how does python process handle a signal . When you ...
[ "If you set a Python code signal handler using the signal module the interpreter will only run it when it re-enters the byte-code interpreter. The handler is not run right away. It is placed in a queue when the signal occurs. If the code path is currently in C code, built-in or extension module, the handler is defe...
[ 7, 0 ]
[]
[]
[ "extend", "python", "signals" ]
stackoverflow_0006420088_extend_python_signals.txt
Q: Conditional compilation in Python How to do conditional compilation in Python ? Is it using DEF ? A: Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled "on the fly", you can think of it as being similar to a interpreted language like Basic or Perl.1 You can do something e...
Conditional compilation in Python
How to do conditional compilation in Python ? Is it using DEF ?
[ "Python isn't compiled in the same sense as C or C++ or even Java, python files are compiled \"on the fly\", you can think of it as being similar to a interpreted language like Basic or Perl.1\nYou can do something equivalent to conditional compile by just using an if statement. For example:\nif FLAG:\n def f():...
[ 23, 22, 19, 4, 3, 0 ]
[]
[]
[ "conditional_compilation", "python" ]
stackoverflow_0000560040_conditional_compilation_python.txt
Q: Looking for a snippet to convert a string into a list of integers As an example: >> s = '0123456' >> list(s) ['0', '1', '2', '3', '4', '5', '6'] I have come up with this: >> map( lambda x:int(x), list(s) ) [0, 1, 2, 3, 4, 5, 6] Can this be improved ? A: Just use a list comprehension, or if appropriate a gener...
Looking for a snippet to convert a string into a list of integers
As an example: >> s = '0123456' >> list(s) ['0', '1', '2', '3', '4', '5', '6'] I have come up with this: >> map( lambda x:int(x), list(s) ) [0, 1, 2, 3, 4, 5, 6] Can this be improved ?
[ "Just use a list comprehension, or if appropriate a generator expression. Simple, and a bit faster (arguably) more readable.\n[int(x) for x in s]\n\n", ">>> map(int, ['1', '2'])\n[1, 2]\n\n>>> map(int, '123')\n[1, 2, 3]\n\n", "There is nothing really wrong with your approach except it is not necessary to conver...
[ 8, 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006420273_python.txt
Q: A semaphore-like mechanism for Celery We're developing a distributed application in Python + Celery for our task queue. Our application requires us to download emails from a remote ISP via IMAP (e.g.: gmail) and we're looking to have be able this task be done in parallel. For a given email account you're granted ...
A semaphore-like mechanism for Celery
We're developing a distributed application in Python + Celery for our task queue. Our application requires us to download emails from a remote ISP via IMAP (e.g.: gmail) and we're looking to have be able this task be done in parallel. For a given email account you're granted a limited to a number of simulations connec...
[ "As celery uses the multiprocessing library for processes, you should be able to use the process safe multiprocessing.Semaphore([value]).\nYou will want to create the semaphore upfront and pass it in, and you can set a default value equal to the maximum number of concurrent accesses you want to allow. Then acquire ...
[ 2 ]
[]
[]
[ "celery", "distributed_computing", "python", "semaphore" ]
stackoverflow_0005876635_celery_distributed_computing_python_semaphore.txt
Q: Why doesn't Python socket receive a final blank value during recv loop of HTTP socket? I've written a miniature proxy module in Python 3 to simply sit between my browser and the web. My goal is to merely proxy the traffic going back and forth. One behavior of the program is to save the website responses I get in...
Why doesn't Python socket receive a final blank value during recv loop of HTTP socket?
I've written a miniature proxy module in Python 3 to simply sit between my browser and the web. My goal is to merely proxy the traffic going back and forth. One behavior of the program is to save the website responses I get in a local directory. Everything works the way I expect, except for the simple fact that using...
[ "If you have a keep-alive connection, there will be some indication of the message length in the headers of the response. See HTTP Message. Buffer recv until you have the complete header (terminated by a blank line), determine the message body length, and read exactly that much information.\nHere's a simple class ...
[ 3, 2, 1, 1 ]
[]
[]
[ "http", "proxy", "python", "python_3.x", "sockets" ]
stackoverflow_0006419899_http_proxy_python_python_3.x_sockets.txt
Q: How to properly use mechanize to scrape AJAX sites So I am fairly new to web scraping. There is this site that has a table on it, the values of the table are controlled by Javascript. The values will determine the address of future values that my browser is told to request from the Javascript. These new pages have...
How to properly use mechanize to scrape AJAX sites
So I am fairly new to web scraping. There is this site that has a table on it, the values of the table are controlled by Javascript. The values will determine the address of future values that my browser is told to request from the Javascript. These new pages have JSON responses that the script updates the table with i...
[ "From the mechanize faq \"mechanize does not provide any support for JavaScript\", it then elaborates on your options (the choices aren't great).\nIf you've got something working then great but using selenium webdriver is a much better solution for scraping ajax sites than mechanize\n" ]
[ 7 ]
[]
[]
[ "javascript", "json", "mechanize", "python", "scrape" ]
stackoverflow_0006417801_javascript_json_mechanize_python_scrape.txt
Q: Python's Mechanize not recognizing a form that the HTML and BeautifulSoup does I'm submitting a form, which then has a confirmation page. At the confirmation page in a browser there is an that is an image the user clicks to confirm the order. Mechanize is not recognizing the form at all when it is present in the...
Python's Mechanize not recognizing a form that the HTML and BeautifulSoup does
I'm submitting a form, which then has a confirmation page. At the confirmation page in a browser there is an that is an image the user clicks to confirm the order. Mechanize is not recognizing the form at all when it is present in the HTML mech has: content = mech.submit().read() soup = BeautifulSoup(content) print s...
[ "Try parsing all html responses with BeautifulSoup, then mechanize should recognise the form. \nYou can see how to do it in this answer Is it possible to hook up a more robust HTML parser to Python mechanize?\n" ]
[ 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0006417978_mechanize_python.txt
Q: Using Python and BeautifulSoup to Parse a Table I am trying to access content in certain td tags with Python and BeautifulSoup. I can either get the first td tag meeting the criteria (with find), or all of them (with findAll). Now, I could just use findAll, get them all, and get the content I want out of them, but...
Using Python and BeautifulSoup to Parse a Table
I am trying to access content in certain td tags with Python and BeautifulSoup. I can either get the first td tag meeting the criteria (with find), or all of them (with findAll). Now, I could just use findAll, get them all, and get the content I want out of them, but that seems like it is inefficient (even if I put lim...
[ "\nIs there anyway to go to a certain td\n tag meeting the criteria I want? Say\n the third, or the 10th?\n\nWell...\nall_tds = [td for td in soup.findAll(\"td\", {'class': 'yfnc_tablehead1'})]\n\nprint all_tds[3]\n\n...there is no other way..\n", "find and findAll are very flexible, the BeautifulSoup.findAll d...
[ 2, 1 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0006420005_beautifulsoup_html_parsing_python.txt
Q: Why does this python program sometimes fail to exit? I wrote a test program, which has two processes. The father process gets data from a Queue, and the child puts data into it. There is a signal handler which tells the program to exit. However, it does not exit sometimes when I send the signal SIGTERM to the pid(...
Why does this python program sometimes fail to exit?
I wrote a test program, which has two processes. The father process gets data from a Queue, and the child puts data into it. There is a signal handler which tells the program to exit. However, it does not exit sometimes when I send the signal SIGTERM to the pid(child process) I printed, and it seems to be having a dead...
[ "Unless you are running python 3 you should be using xrange instead of range for a loop that large. Python tends to choke once it exceeds a certain list size and so you really really need to move to generators by that point.\nThat very well could be the issue your seeing right now.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python", "queue", "signals" ]
stackoverflow_0006410207_multiprocessing_python_queue_signals.txt
Q: lxml memory usage when parsing huge xml in python I am a python newbie. I am trying to parse a huge xml file in my python module using lxml. In spite of clearing the elements at the end of each loop, my memory shoots up and crashes the application. I am sure I am missing something here. Please helpme figure out wh...
lxml memory usage when parsing huge xml in python
I am a python newbie. I am trying to parse a huge xml file in my python module using lxml. In spite of clearing the elements at the end of each loop, my memory shoots up and crashes the application. I am sure I am missing something here. Please helpme figure out what that is. Following are main functions I am using - ...
[ "Welcome to Python and Stack Overflow!\nIt looks like you've followed some good advice looking at lxml and especially etree.iterparse(..), but I think your implementation is approaching the problem from the wrong angle. The idea of iterparse(..) is to get away from collecting and storing data, and instead processin...
[ 17 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006418576_lxml_python.txt
Q: Function won't take an argument Below is code that checks a price on a website and shoots it out to Twitter. As you can see, on line 22, I pass the first function(which fetches the price) as an argument in the second function(which streams to Twitter). When I run this I keep getting an error message that says "Ty...
Function won't take an argument
Below is code that checks a price on a website and shoots it out to Twitter. As you can see, on line 22, I pass the first function(which fetches the price) as an argument in the second function(which streams to Twitter). When I run this I keep getting an error message that says "TypeError: send_to_twitter() takes no a...
[ "def send_to_twitter(name_of_the_argument_you_want):\n\n", "def send_to_twitter(): should be def send_to_twitter(msg):\nand resp.read should be resp.read() and price = get_price should be price = get_price()\n", "Because this:\ndef send_to_twitter():\n ...\n\nDefines a function of zero arguments. Think about...
[ 5, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0006420357_python.txt
Q: Run sql like "OR" query on appengine How can I run the equivalent of this query: "select * from users where username='john' or email='john@email.com'; on appengine? I know appengine doesn't support the "OR" but has "IN" just not sure how to use it for such a query. A: This question gives an example of using 'IN...
Run sql like "OR" query on appengine
How can I run the equivalent of this query: "select * from users where username='john' or email='john@email.com'; on appengine? I know appengine doesn't support the "OR" but has "IN" just not sure how to use it for such a query.
[ "This question gives an example of using 'IN' as an 'OR' equivalent. However, as noted in the comments, GAE will treat 'IN' like multiple queries and is generally a bad idea, especially when querying on many list values. \nYour best bet is often to perform the separate queries yourself and combine them programmati...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0006414118_google_app_engine_python.txt
Q: Problem with class based generic views in Django I'm trying to write a CRUD application using Djangos class based generic views. Following is the code i wrote to create a new user in the db. from django.views.generic import CreateView from django.contrib.auth.decorators import login_required from django.cont...
Problem with class based generic views in Django
I'm trying to write a CRUD application using Djangos class based generic views. Following is the code i wrote to create a new user in the db. from django.views.generic import CreateView from django.contrib.auth.decorators import login_required from django.contrib import messages class UserCreateView(CreateView...
[ "The answer depends on what specifically you're looking to do with the messaging framework. If it needs to be called for every get request you'd naturally need to put it in the get method (point being there's no one right place to put this code).\nAnyways, it sounds like you're looking for a place that's only trigg...
[ 16 ]
[]
[]
[ "django", "django_generic_views", "python" ]
stackoverflow_0006420322_django_django_generic_views_python.txt
Q: How to find the select the whole line for looking for only substring from the line in Python Example, I have the following lines in file: Tom is a guy Sara is a woman Alex is a guy too I would like to search for "Sara" but would like to return the whole like def findLine(self, str): ... When I call findLi...
How to find the select the whole line for looking for only substring from the line in Python
Example, I have the following lines in file: Tom is a guy Sara is a woman Alex is a guy too I would like to search for "Sara" but would like to return the whole like def findLine(self, str): ... When I call findLine("Sara"), it returns "2. Sara is a woman" How do I accomplish this with Python and Regular Exp...
[ "I renamed str to content see senderle's comment\ndef findLine(self, content, search_str):\n for line in content.splitlines()\n if search_str in line:\n return line\n #or something else because the search_str was not found\n return None\n\nor if you want a list of all the lines containing...
[ 5, 2, 2, 1, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006419711_python_regex.txt
Q: Find the Latest file version in a folder using Python Ive been trying to get python to try to search all my shots A: import glob latest = sorted(glob.glob('dd19_15_00_an[0-9]+\.avi'))[-1] Note: a normal sort is OK if your versions have zero padding. If they had no zero padding, you needed some kind of natural s...
Find the Latest file version in a folder using Python
Ive been trying to get python to try to search all my shots
[ "import glob\nlatest = sorted(glob.glob('dd19_15_00_an[0-9]+\\.avi'))[-1]\n\nNote: a normal sort is OK if your versions have zero padding. If they had no zero padding, you needed some kind of natural sort, which complicated things a bit.\n", "\nBuild a tree representation of your files, recursively\nDo the search...
[ 2, 0 ]
[]
[]
[ "directory", "file", "python", "windows" ]
stackoverflow_0006421321_directory_file_python_windows.txt
Q: Payment gateway with Python SDK compatible with GAE I'm looking for a Payment gateway that offers Python SDK which would run on GAE. So far I've looked at Braintree[1] and TrustCommerce[2], and both required C-based libraries to work, which won't work on GAE. If there's no such thing, which payment gateway would y...
Payment gateway with Python SDK compatible with GAE
I'm looking for a Payment gateway that offers Python SDK which would run on GAE. So far I've looked at Braintree[1] and TrustCommerce[2], and both required C-based libraries to work, which won't work on GAE. If there's no such thing, which payment gateway would you recommend that provides a possibly JSON-based API or a...
[ "It would be really helpful if you provided links. I googled and found this TrustCommerce, but I guess maybe it's a different company to the one you are talking about because they say there is sample Python code.\nI didn't sign up for a trial account just to see if the Python API requires a C library. Afterall mayb...
[ 0 ]
[]
[]
[ "google_app_engine", "payment_gateway", "python" ]
stackoverflow_0006416660_google_app_engine_payment_gateway_python.txt
Q: Limiting the text download content in pycurl I want to download site content using curl in python (pycurl). But I don't want the whole text of those sites just some part of the site. I want to reduce my time taken in downloading the whole text. Thankyou. A: You should set the relevant headers in your HTTP reque...
Limiting the text download content in pycurl
I want to download site content using curl in python (pycurl). But I don't want the whole text of those sites just some part of the site. I want to reduce my time taken in downloading the whole text. Thankyou.
[ "You should set the relevant headers in your HTTP request, see this question on how to do it with pycurl\nNOTE: This only works if you:\n\nKnow the data offset (in bytes) where in the result the data you want is\nThe web server supports this\n\n", "The delay in loading a page, generally, is not in the actual down...
[ 2, 0 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0006421422_pycurl_python.txt
Q: persistence of objects in python Till now I have done only procedural programming in C so I am rather unclear about both OOP and Python. I have a large project which contains a number of python files. File a.py defines a class called fobject I am using python 2.5 File b.py and c.py have classes called BProject and...
persistence of objects in python
Till now I have done only procedural programming in C so I am rather unclear about both OOP and Python. I have a large project which contains a number of python files. File a.py defines a class called fobject I am using python 2.5 File b.py and c.py have classes called BProject and CProject which have an object of fobj...
[ "You don't understand python. You need to understand variables (almost everything in python is basically a pointer), and namespaces.\nOK, so you don't understand when python creates new objects.\nIn 90% of cases, every time you see an object, it will be a new one.\nFor example:\na = [1,2,3]\nb = a + [4,5] \nprint a...
[ 3 ]
[]
[]
[ "oop", "python", "wxpython" ]
stackoverflow_0006420688_oop_python_wxpython.txt
Q: how to redirect to particular url on 404 @error(404) def error404(error): return 'Nothing here, sorry' This is the way to response 404 in bottle framework. But On 404 I want to redirect to particular url say http://abc.com/. Is it possible? A: @error(404) def error404(error): from bottle import redirect...
how to redirect to particular url on 404
@error(404) def error404(error): return 'Nothing here, sorry' This is the way to response 404 in bottle framework. But On 404 I want to redirect to particular url say http://abc.com/. Is it possible?
[ "@error(404)\ndef error404(error):\n from bottle import redirect\n # maybe test the error to see where you want to go next?\n redirect(new_url, 303) # HTTP 303 should be used in this case\n\nEDIT I'm not 100% sure this can be done, and I can't test it right now, but I'll test it later and update the answer...
[ 3, 3 ]
[ "import urllib\nurl = urllib.urlopen('www.google.com/testing') #a 404 address\nif url.code == 404:\n url = urllib.urlopen('www.google.com')\n\nWhen a urlobject is created the .code instance returns the code of the page,\n" ]
[ -3 ]
[ "bottle", "python" ]
stackoverflow_0004286632_bottle_python.txt
Q: Python: If is running even when condition is not met import imaplib, re import os while(True): conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) conn.login("xxx", "xxxx") unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1) print unreadCount if unreadCount > ...
Python: If is running even when condition is not met
import imaplib, re import os while(True): conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) conn.login("xxx", "xxxx") unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1) print unreadCount if unreadCount > 10: os.system('ls') Even when unreadCount is < 10, ...
[ "You might want to coerce that value to an integer, as per:\nunreadCount = int (re.search (blah, blah, blah).group (1))\n\nThe call to re.search is returning a string and, if you have a look at the following transcript:\n>>> x = \"7\"\n>>> if x > 10:\n... print \"yes\"\n... \nyes\n\n>>> if int(x) > 10:\n... ...
[ 7, 2, 2 ]
[]
[]
[ "gmail", "python" ]
stackoverflow_0006421981_gmail_python.txt
Q: Is there a way to copy a file over telnet preferably using python or shell. does not have to use telnet program but does need to use protocol since that is the simplest way in my case(no need to install stuff on "server" to transfer files over). Note this isn't directly connected to the outside world and security...
Is there a way to copy a file over telnet
preferably using python or shell. does not have to use telnet program but does need to use protocol since that is the simplest way in my case(no need to install stuff on "server" to transfer files over). Note this isn't directly connected to the outside world and security isn't a big deal.
[ "If the telnet protocol is all you can use than about the only way I can suggest is to use uuencode on the source side to output the file as regular text to standard output.\nThen have your terminal emulator capture the output to a file and use uudecode on your local box to decode it.\nThe advantage of this is that...
[ 4 ]
[ "How about using scp?\nscp someuser@somehost.somedomain.com:/path/to/file :.\n\n" ]
[ -1 ]
[ "python", "telnet" ]
stackoverflow_0006422148_python_telnet.txt
Q: Why thread is slower than subprocess ? when should I use subprocess in place of thread and vise versa In my application, I have tried python threading and subprocess module to open firefox, and I have noticed that subprocess is faster than threading. what could be the reason behind this? when to use them in place ...
Why thread is slower than subprocess ? when should I use subprocess in place of thread and vise versa
In my application, I have tried python threading and subprocess module to open firefox, and I have noticed that subprocess is faster than threading. what could be the reason behind this? when to use them in place of each other?
[ "Python (or rather CPython, the c-based implementation that is commonly used) has a Global Intepreter Lock (a.k.a. the GIL). \nSome kind of locking is necessary to synchronize memory access when several threads are accessing the same memory, which is what happens inside a process. Memory is not shared by between p...
[ 7 ]
[]
[]
[ "multithreading", "python", "subprocess" ]
stackoverflow_0006422187_multithreading_python_subprocess.txt
Q: What is this code doing? >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim' This from the python tutorial of this page, I don't understand the 2nd line. A: The python or operator can be defined as [1]: x or y : if x is false, the...
What is this code doing?
>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' >>> non_null = string1 or string2 or string3 >>> non_null 'Trondheim' This from the python tutorial of this page, I don't understand the 2nd line.
[ "The python or operator can be defined as [1]:\nx or y : if x is false, then y, else x\n\nWhen you do string1 or string2, string1 is an empty string, which Python translates as False (side node: some programming languages do this, others don't), so by the definition above it evaluates to the value of string2. When ...
[ 7, 4, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006422263_python.txt
Q: Python replacements for RVM/Bundler/Capistrano I'm just moving over from Ruby/Rails development to Python/Django and i'm trying to find the best replacements for RVM/Bundler/Capistrano but it seems to be a total mess? I've found these so far: pythonbrew virtualenv envwrapper pip easyinstall setuptools For capis...
Python replacements for RVM/Bundler/Capistrano
I'm just moving over from Ruby/Rails development to Python/Django and i'm trying to find the best replacements for RVM/Bundler/Capistrano but it seems to be a total mess? I've found these so far: pythonbrew virtualenv envwrapper pip easyinstall setuptools For capistrano I've found Fabric which seems to fit fairly we...
[ "pip is 'the' tool for Python packages, replacing easy_install. Most people are using virtualenv for multiple python environments.\n", "I have used pip/virtualenv/fabric extensively and am happy with it. You can't go wrong with this choice.\nI haven't used pythonbrew however, so I can't do any relative comparison...
[ 3, 3 ]
[]
[]
[ "development_environment", "env", "python", "ruby" ]
stackoverflow_0006422189_development_environment_env_python_ruby.txt
Q: Url Rewrite With Python Paste I'm hosting a Pylons application using Apache as a proxy to paste, which serves my app. I'm trying to set up a Rewrite Rule to force browsers to update modified css, js, and image files, as inspired by the latter half of section 10.8 in Chapter 10: Survive the Deep End. It works by wr...
Url Rewrite With Python Paste
I'm hosting a Pylons application using Apache as a proxy to paste, which serves my app. I'm trying to set up a Rewrite Rule to force browsers to update modified css, js, and image files, as inspired by the latter half of section 10.8 in Chapter 10: Survive the Deep End. It works by writing a view helper to automaticall...
[ "I don't know if you are running on top of Linux or not, but have you simply tried setting up a symlink?\n" ]
[ 0 ]
[]
[]
[ "apache2", "paste", "proxy", "pylons", "python" ]
stackoverflow_0005669829_apache2_paste_proxy_pylons_python.txt
Q: How do I filter out only items from a list which is in an even position? Instead of processing items based on its value, I need to run a function based on the item's position. This is an example of filtering based on the content of the list. only_words = filter(str.isalpha, my_list) I want to create a slice of th...
How do I filter out only items from a list which is in an even position?
Instead of processing items based on its value, I need to run a function based on the item's position. This is an example of filtering based on the content of the list. only_words = filter(str.isalpha, my_list) I want to create a slice of the list that contains only items in the even position, that is: new_list = [] p...
[ "You can use this: my_list[::2] (for odd — my_list[1::2])\n", "[v for k, v in enumerate(mylist) if k % 2 == 0]\n\n" ]
[ 20, 6 ]
[]
[]
[ "python" ]
stackoverflow_0006422752_python.txt
Q: Getting tag article count I want to get each tag's article count from taggitItem table; I have written the following but it doesn't work correctly. article_content_type = ContentType.objects.get_for_model(Article) articles = TaggedItem.objects.filter(content_type = article_content_type).annotate(count = Count('tag...
Getting tag article count
I want to get each tag's article count from taggitItem table; I have written the following but it doesn't work correctly. article_content_type = ContentType.objects.get_for_model(Article) articles = TaggedItem.objects.filter(content_type = article_content_type).annotate(count = Count('tag')) Please help.
[]
[]
[ "article_count = TaggedItem.objects.filter(content_type = article_content_type).count()\n\nPerhaps it is even better not to use the TaggedItem class, but do it via the Article class.\n" ]
[ -1 ]
[ "django", "python" ]
stackoverflow_0006422360_django_python.txt
Q: Scraping English Words using Python I would like to scrape all English words from, say, New York Times front page. I wrote something like this in Python: import re from urllib import FancyURLopener class MyOpener(FancyURLopener): version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071...
Scraping English Words using Python
I would like to scrape all English words from, say, New York Times front page. I wrote something like this in Python: import re from urllib import FancyURLopener class MyOpener(FancyURLopener): version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11' opener...
[ "Are you sure you want \"English\" words -- in the sense that they appear in some dictionary? For example, if you scraped an NYT article, would you want to include \"Obama\" (or \"Palin\" for you Blue-Staters out there), even though they probably don't appear in any dictionaries yet?\nBetter, in many cases, to par...
[ 4, 1, 1, 0, 0 ]
[]
[]
[ "nlp", "python", "urllib", "urllib2", "web_scraping" ]
stackoverflow_0006418785_nlp_python_urllib_urllib2_web_scraping.txt
Q: Is there a python version of JavaScript's String.fromCharCode? String.fromCharCode returns a string based on a list of unicode codepoint values. @see reference Is there an analog in Python ? A: You can use this: ''.join(map(unichr, lst)) Example: ''.join(map(unichr, [65,66,67])) # outputs ABC A: You can use th...
Is there a python version of JavaScript's String.fromCharCode?
String.fromCharCode returns a string based on a list of unicode codepoint values. @see reference Is there an analog in Python ?
[ "You can use this: ''.join(map(unichr, lst))\nExample:\n''.join(map(unichr, [65,66,67])) # outputs ABC\n\n", "You can use the chr() or unichr() for unicode values.\n" ]
[ 21, 11 ]
[]
[]
[ "python" ]
stackoverflow_0006423047_python.txt
Q: Invalid url's throw an exception - python import httplib import urlparse def getUrl(url): try: parts = urlparse.urlsplit(url) server = parts[1] path = parts[2] obj = httplib.HTTPConnection(server,80) obj.connect() obj.putrequest('HEAD',path) obj.putheader('Accept','*/*') ...
Invalid url's throw an exception - python
import httplib import urlparse def getUrl(url): try: parts = urlparse.urlsplit(url) server = parts[1] path = parts[2] obj = httplib.HTTPConnection(server,80) obj.connect() obj.putrequest('HEAD',path) obj.putheader('Accept','*/*') obj.endheaders() response = obj.getrespon...
[ "That's supposed to happen. An exception is being thrown because the URL cannot be resolved. This is thrown prior to your if response.status != 200 line which turns control over to your except block.\nYou need to spend some time looking into how Exceptions work. Here's an example of something you could try.\ndef...
[ 2, 2, 1 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0006414417_python_web_crawler.txt
Q: Error while trying to setup a Jython interpreter I wanted to boot up a Jython interpreter inside the plugin, then execute files inside the interpreter. package com.jakob.jython; import org.bukkit.plugin.java.JavaPlugin; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.io.IOE...
Error while trying to setup a Jython interpreter
I wanted to boot up a Jython interpreter inside the plugin, then execute files inside the interpreter. package com.jakob.jython; import org.bukkit.plugin.java.JavaPlugin; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.io.IOException; import java.io.InputStream; import java.util...
[ "Are you sure that EmbeddedJython.class.getResourceAsStream(\"MyPlugin.py\"); is finding the resource? \nIf it can't find the resource, getResourceAsStream will return a null, and it is possible that the Jython interpreter will treat that as an empty (closed) stream.\nYour application should probably check this, r...
[ 2, 0 ]
[]
[]
[ "inputstream", "java", "jython", "python" ]
stackoverflow_0006423550_inputstream_java_jython_python.txt
Q: How to get the current Python interpreter path from inside a Python script? I want to run a Python script from a Python script with subprocess, and I wish to do it using the same interpreter for each of them. I'm using virtualenv, so I'd like to do something like: subprocess.Popen('%s script.py' % python_bin) How...
How to get the current Python interpreter path from inside a Python script?
I want to run a Python script from a Python script with subprocess, and I wish to do it using the same interpreter for each of them. I'm using virtualenv, so I'd like to do something like: subprocess.Popen('%s script.py' % python_bin) How do I get python_bin? It should be /usr/bin/python outside a virtualenv, and /pat...
[ "The name of the interpreter is stored in the variable sys.executable\n", "I found it by:\n>>> import sys \n>>> help(sys)\n...\n\nDATA\n __stderr__ = <open file '<stderr>', mode 'w' at 0x110029140>\n __stdin__ = <open file '<stdin>', mode 'r' at 0x110029030>\n __stdout__ = <open file '<stdout>'...
[ 76, 7, 4 ]
[]
[]
[ "interpreter", "path", "python" ]
stackoverflow_0005927633_interpreter_path_python.txt
Q: Loading serialised object from YAML and replacing current object with it I have what I would have thought would be a fairly common problem, but I can't seem to find out how to do what I want. I have a class in Python that has a number of instance variables which contain parameters for a model. I have added two met...
Loading serialised object from YAML and replacing current object with it
I have what I would have thought would be a fairly common problem, but I can't seem to find out how to do what I want. I have a class in Python that has a number of instance variables which contain parameters for a model. I have added two methods to the class: def save_params(self, filename): f = open(filename, "w"...
[ "The problem is with your assignment to self, and it is explained very nicely here. In short, within the function, self is a local name, and thus, binding it to a different value has no effect outside of the function.\nTo overcome this, you could probably use self.__dict__ = obj.__dict__. This would only work if yo...
[ 1 ]
[]
[]
[ "python", "serialization" ]
stackoverflow_0006423982_python_serialization.txt
Q: Controlling a browser from Python I am looking for a way to control a browser from Python, i.e. fill out form fields and submit them, possibly call JS functions. I've looked around a bit, but as far as I could see PyWebKitGtk only lets you show the browser as a GUI element, not interface with it. Is there a way t...
Controlling a browser from Python
I am looking for a way to control a browser from Python, i.e. fill out form fields and submit them, possibly call JS functions. I've looked around a bit, but as far as I could see PyWebKitGtk only lets you show the browser as a GUI element, not interface with it. Is there a way to do this easily? I wrote my program l...
[ "You might try something like Selenium, which is an application to script browsers through various languages including Python - it's meant for cross-browser testing, but might do what you want.\n", "Why not just use Python to simulate a browser, parsing the HTML and building the appropriate HTTP requests as neces...
[ 3, 1, 1 ]
[]
[]
[ "browser", "javascript", "macros", "python", "webkit" ]
stackoverflow_0003033943_browser_javascript_macros_python_webkit.txt
Q: Calling OpenGL Extensions from Python I am using PyOpenGL 3 on Ubuntu Natty. I want to use the glDrawElementsBaseVertex function. I can see it listed in my glxinfo output, so I know my card has it. However, I cannot find how to actually invoke it. When I import OpenGL.GL I get a NameError if I try to use it. (As...
Calling OpenGL Extensions from Python
I am using PyOpenGL 3 on Ubuntu Natty. I want to use the glDrawElementsBaseVertex function. I can see it listed in my glxinfo output, so I know my card has it. However, I cannot find how to actually invoke it. When I import OpenGL.GL I get a NameError if I try to use it. (As distinct from it being None).
[ "Try to import the function through its extension name:\n>>> from OpenGL.GL.ARB.draw_elements_base_vertex import *\n>>> glDrawElementsBaseVertex\n<OpenGL.platform.baseplatform.glDrawElementsBaseVertex object at 0x031D7B30>\n\n", "OpenGL extensions must be provided by the binding itself, PyOpenGL has no support fo...
[ 5, 1 ]
[]
[]
[ "opengl", "pyopengl", "python" ]
stackoverflow_0006423994_opengl_pyopengl_python.txt
Q: etree get attribute as a value instead of a string For a given Element, I want to check whether the xsi:nil attribute is set to true. My current code is xsinil = dataFact.get('{http://www.w3.org/2001/XMLSchema-instance}nil', False) But instead of being True xsinil is of type string... What's the best solution? I ...
etree get attribute as a value instead of a string
For a given Element, I want to check whether the xsi:nil attribute is set to true. My current code is xsinil = dataFact.get('{http://www.w3.org/2001/XMLSchema-instance}nil', False) But instead of being True xsinil is of type string... What's the best solution? I don't think this is very elegant: xsinil=dataFact.get('{...
[ "This looks nicer:\nxsinil = dataFact.get('...', False) in ('true', '1')\n\nIt assigns True to xsinil variable only if result of get function is one of True, 'true' or '1'.\n", "The second arg of Element.get() is almost irrelevant -- just don't use True.\nAll that you need is:\nxsinil = dataFact.get('......') in ...
[ 1, 1 ]
[]
[]
[ "elementtree", "lxml", "python" ]
stackoverflow_0006422860_elementtree_lxml_python.txt
Q: how to make save / load game functions in pygame? I need to make save / load game functions for my rpg. I can save the location of my player, but what I want is to freeze the entire screen at one point like it is done in emulators like vba and snes9x. Or maybe to make save locations where I can save the game and s...
how to make save / load game functions in pygame?
I need to make save / load game functions for my rpg. I can save the location of my player, but what I want is to freeze the entire screen at one point like it is done in emulators like vba and snes9x. Or maybe to make save locations where I can save the game and start again from. Can anyone tell me how you do these th...
[ "You can use pickle to serialize Python data. This has nothing to do with pygame.\nSo if your game state is completely stored in the object foo, to save to file \"savegame\" (import pickle first):\nwith open(\"savegame\", \"wb\") as f:\n pickle.dump(foo, f)\n\nTo load:\nwith open(\"savegame\", \"rb\") as f:\n ...
[ 20 ]
[]
[]
[ "load", "pygame", "python", "save" ]
stackoverflow_0006420311_load_pygame_python_save.txt
Q: Django/html table: Description inside header row shifts to the right I seem too be having a strange problem. I have a django app that can crate a note from a form. All of these notes that are entered from this form are stored in a table list. Like so. <div style="overflow:auto; height:100px; width:721px; padding:1...
Django/html table: Description inside header row shifts to the right
I seem too be having a strange problem. I have a django app that can crate a note from a form. All of these notes that are entered from this form are stored in a table list. Like so. <div style="overflow:auto; height:100px; width:721px; padding:12px; border:1px solid #C0C0C0"> {% for note in notes %} <table sty...
[ "By default a th will center it's text. So you should left align it instead:\n<tr><th style=\"text-align: left\">{{note.datetime}} {{note.datetime.time}} - Posted by {{note.user}}</th></tr>\n\nOf course I am also obliged to tell you that adding style attributes to tags like this should be avoided. Really your css...
[ 3 ]
[]
[]
[ "css", "django", "html", "html_table", "python" ]
stackoverflow_0006424457_css_django_html_html_table_python.txt
Q: Processing a list of lists I have a list of lists, say: arr = [[1, 2], [1, 3], [1, 4]] I would like to append 100 to each of the inner lists. Output for the above example would be: arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]] I can of course do: for elem in arr: elem.append(100) But is ther...
Processing a list of lists
I have a list of lists, say: arr = [[1, 2], [1, 3], [1, 4]] I would like to append 100 to each of the inner lists. Output for the above example would be: arr = [[1, 2, 100], [1, 3, 100], [1, 4, 100]] I can of course do: for elem in arr: elem.append(100) But is there something more pythonic that c...
[ "The second version should be written like arr = [elem + [100] for elem in arr]. But the most pythonic way if you ask me is the first one. The for construct has it's own use, and it suits very well here.\n", "Note that your code also works - the only thing you have to know is that there is no need to assign resul...
[ 5, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006424676_python.txt
Q: Wring file retrieved using Blobstore I have form upload and handler which allows download uploaded files from blobstore. The problem is when I click Download button of any related-field it downloads the same file every time. I.e. I've uploaded 3 files (1.txt, 2.txt, 3.txt) and it always downloads only 1.txt whenev...
Wring file retrieved using Blobstore
I have form upload and handler which allows download uploaded files from blobstore. The problem is when I click Download button of any related-field it downloads the same file every time. I.e. I've uploaded 3 files (1.txt, 2.txt, 3.txt) and it always downloads only 1.txt whenever I clicked another Download buttons. You...
[ "Of course it's always the first. You're declaring three hidden fields with the same name but various values. How could the server understand you want “the hidden field nearest to the download button I clicked”?\nYou could do this with Javascript but it's overkill. Maybe you should rather create forms for each item...
[ 0, 0 ]
[]
[]
[ "blobstore", "jinja2", "python", "tipfy" ]
stackoverflow_0005603443_blobstore_jinja2_python_tipfy.txt
Q: how to get the values from a dictionary in the sorted-order of the keys? i have a problem with my python class. it contains a method that goes through all the keys of a multi_dimensional dictionary. The dictionary keys may be in the following order (1->(2,3),2->(5,6)). the problem is when the method att...
how to get the values from a dictionary in the sorted-order of the keys?
i have a problem with my python class. it contains a method that goes through all the keys of a multi_dimensional dictionary. The dictionary keys may be in the following order (1->(2,3),2->(5,6)). the problem is when the method attempts to get the keys, sometimes it gets them in the right order (1,2) and som...
[ "Note that dictionaries are unordered so in order to be sure that values would be handled in the ordered format you need to sort them first. Please find sample below:\nd={1:{2:'tst', 3:'tst2'}, 4:{...} }\n\nfor key in sorted(d):\n for skey in sorted(d[key]):\n #do something\n\nOR something like this:\nfro...
[ 3, 1 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0006425335_dictionary_python_sorting.txt
Q: Applying arithmetic functions to elements of sublists where the first element of each sublist is the same Here is my problem. I have a list of lists, as follows: linesort=[ ['Me', 1, 596], ['Mine', 1, 551], ['Myself', 1, 533], ['Myself', 1, 624], ['Myself', 1, 656], ['Myself', 1, 928], ['Theirs...
Applying arithmetic functions to elements of sublists where the first element of each sublist is the same
Here is my problem. I have a list of lists, as follows: linesort=[ ['Me', 1, 596], ['Mine', 1, 551], ['Myself', 1, 533], ['Myself', 1, 624], ['Myself', 1, 656], ['Myself', 1, 928], ['Theirs', 1, 720], ['Theirs', 1, 1921], ['Them', 1, 716], ['Themselves', 1, 527] ] Each of the sublists repr...
[ "Not the beautiful one but:\nfrom collections import defaultdict\n\nlinesort = [['Me', 1, 596], ['Mine', 1, 551], ['Myself', 1, 533], ['Myself', 1, 624],\n ['Myself', 1, 656], ['Myself', 1, 928], ['Theirs', 1, 720], \n ['Theirs', 1, 1921], ['Them', 1, 716], ['Themselves', 1, 527]]\n\nd = defau...
[ 3, 1, 1 ]
[]
[]
[ "python", "sublist", "text_processing" ]
stackoverflow_0006424873_python_sublist_text_processing.txt
Q: python string to code for function arg? I have a function names "myfunction". I have a string "a", I need to pass it to "myfunction" so it will give the same result as if my string was a python object name, myfunction(a) So I have def myfunction(var): print var a = 1 mystring = "a" I need to pass "mystring" t...
python string to code for function arg?
I have a function names "myfunction". I have a string "a", I need to pass it to "myfunction" so it will give the same result as if my string was a python object name, myfunction(a) So I have def myfunction(var): print var a = 1 mystring = "a" I need to pass "mystring" to "myfuntion" so it will behave as variable "...
[ "It would be eval(), not exec:\nmyfunction(eval(mystring))\n\nAlternatively:\nmyfunction(locals()[mystring])\n\nMost probably you have a fundamental design problem if you think you need something like this.\n", "No needs in exec or eval:\n>>> def myfunc(var):\n... print globals()[var] * 2\n...\n>>> a = 12\n>>...
[ 4, 1 ]
[]
[]
[ "arguments", "exec", "function", "python", "string" ]
stackoverflow_0006425690_arguments_exec_function_python_string.txt
Q: How can I use the py2exe to change the python3.2's code to exe Possible Duplicate: py2exe for Python 3.0 I read py2exe can create a standalone program using a Python version before the 3. How, using Python 3.2, create e.g. "Hello world.exe", please?? A: p2exe is pretty much dead, unless you are using 2.7 or le...
How can I use the py2exe to change the python3.2's code to exe
Possible Duplicate: py2exe for Python 3.0 I read py2exe can create a standalone program using a Python version before the 3. How, using Python 3.2, create e.g. "Hello world.exe", please??
[ "p2exe is pretty much dead, unless you are using 2.7 or less.\n1) Look into cx-freeze\n2) Install cx-freeze\n3) Create your script (test.py):\nprint(\"Hello there, anyone else hate hello worlds?\")\n\n\n4) Create your setup.py file\nfrom cx_Freeze import setup, Executable\n\n setup(\n name = \"hatefulworld\"...
[ 9 ]
[]
[]
[ "exe", "python" ]
stackoverflow_0006425869_exe_python.txt
Q: xml.parsers.expat.ExpatError on parsing XML I have been trying to retrieve information through HTTP queries, as an example http://www.opencellid.org/cell/get?key=xxxxxxxxxxxxx&mnc=1&mcc=228&lac=101&cellid=7283 returns me a response in XML format, like <rsp stat="ok"> <cell nbSamples="1" mnc="1" lac="101" lat="46....
xml.parsers.expat.ExpatError on parsing XML
I have been trying to retrieve information through HTTP queries, as an example http://www.opencellid.org/cell/get?key=xxxxxxxxxxxxx&mnc=1&mcc=228&lac=101&cellid=7283 returns me a response in XML format, like <rsp stat="ok"> <cell nbSamples="1" mnc="1" lac="101" lat="46.52079" lon="6.56676" cellId="7283" mcc="228" rang...
[ "You forgot to call content on the response object. That's how you get the actual xml.\ncontent = requests.get(url = url).content\nrss = parse(content).getroot()\n\n", "First thing I'd advise would be to save a text file only with the content of the xml: \n <rsp stat=\"ok\">\n <cell nbSamples=\"1\" mnc=\"1\" l...
[ 1, 0 ]
[]
[]
[ "elementtree", "httpwebrequest", "python", "xml", "xml_parsing" ]
stackoverflow_0006425631_elementtree_httpwebrequest_python_xml_xml_parsing.txt
Q: Can I get psycopg2 to work on Windows with a python built with vc9? I have a question similar to ImportError: DLL load failed : - when trying to import psycopg2 library I'm trying to run psycopg2 with Python 2.6.5, built with Visual Studio 2008 (vc9). I get this error: from _psycopg import BINARY, NUMBER, STRING,...
Can I get psycopg2 to work on Windows with a python built with vc9?
I have a question similar to ImportError: DLL load failed : - when trying to import psycopg2 library I'm trying to run psycopg2 with Python 2.6.5, built with Visual Studio 2008 (vc9). I get this error: from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: DLL load failed: The operating system canno...
[ "maybe you should install windows SDK 7.0.\nI have vs2005/vs2008/vc2010 and some windows SDK installed in my system, \nand when I install psycopg2-2.4.2 python package use \"python setup.py install\",\nit prompt me need \"mt.exe\";\nso I add \"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v7.0A\\Bin\" to p...
[ 2 ]
[]
[]
[ "postgresql", "psycopg2", "python", "windows" ]
stackoverflow_0002701459_postgresql_psycopg2_python_windows.txt
Q: Creation of a simple HTML file upload page First, I don't need any functions more than upload a file. No progress bar, no file type, or size check, no multiple files. What I want is the most simple HTML webpage to handle the upload and save the file with the name I specified. I tried to use this: <form action="../...
Creation of a simple HTML file upload page
First, I don't need any functions more than upload a file. No progress bar, no file type, or size check, no multiple files. What I want is the most simple HTML webpage to handle the upload and save the file with the name I specified. I tried to use this: <form action="../cgi-bin/upload.py" method="post" enctype="multip...
[ "The filedata object will wrap a file-like object that can be treated like a regular file. Basically you would do this:\nif filedata.file: # field really is an upload\n with file(\"Beautiful.mp3\", 'w') as outfile:\n outfile.write(filedata.file.read())\n\nOr, you could do just about anything else with it...
[ 9 ]
[]
[]
[ "file_upload", "html", "python" ]
stackoverflow_0006425365_file_upload_html_python.txt
Q: Django url tag : maximum recursion depth exceeded I'm struggling around the following problem: I've two urls files : The root one : urlpatterns = patterns('', ... (r'^demonstrator/', include('powernest.demonstrator.urls')), ... ) and the application one : urlpatterns += patt...
Django url tag : maximum recursion depth exceeded
I'm struggling around the following problem: I've two urls files : The root one : urlpatterns = patterns('', ... (r'^demonstrator/', include('powernest.demonstrator.urls')), ... ) and the application one : urlpatterns += patterns('demonstrator.views', ... url(r'^d...
[ "You are including your app.urls and using += in your app urls.py. This is causing the max recursion depth exceeded errors.\nLeave your urls.py as it is and change your app/urls.py to:\nurlpatterns = patterns('demonstrator.views',\n ...\n url(r'^choices/$', 'demo_choices', d_demo_choice, name=\"demo_choices\...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006423534_django_python.txt
Q: error: integer required readlines() I'm trying to open a CSV document using readlines() in Python. The document contains a list of words, but I'm getting the error that an integer is required. Here's what I wrote and the error message I received: >>> f = open('mike_only_genes.csv') >>> a = f.readlines('mike_only_...
error: integer required readlines()
I'm trying to open a CSV document using readlines() in Python. The document contains a list of words, but I'm getting the error that an integer is required. Here's what I wrote and the error message I received: >>> f = open('mike_only_genes.csv') >>> a = f.readlines('mike_only_genes.csv') Traceback (most recent call l...
[ "you are calling it wrong:\nf.readlines('mike_only_genes.csv')\n\nshould be:\nf.readlines()\n\n", "Because readlines can be executed alone or with an integer, if you want to read all lines, just use readlines().\nwith open('mike_only_genes.csv') as f:\n lines = f.readlines()\n\n", "Read more about readlines ...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006426498_python.txt
Q: How to play videos with pygame? I am trying to make Pygame run some mpg vids for the intro of my rpg. But it isnt working. I have read the pygame docs and it says that video support is currently unstable and that i should use pymedia instead. I personally cannot make heads nor tails of pymedia. So is there ANY way...
How to play videos with pygame?
I am trying to make Pygame run some mpg vids for the intro of my rpg. But it isnt working. I have read the pygame docs and it says that video support is currently unstable and that i should use pymedia instead. I personally cannot make heads nor tails of pymedia. So is there ANY way to play videos with pygame?
[ "(I decided to risk posting this as an answer rather than a comment.)\nThe three \"hopeful\" candidates for video editing/processing in Python that I have found are PyMedia (which I gave up on), PyGame (which may meet your needs but did not meet mine) and pyffmpeg (which is very promising but depends on Cython, and...
[ 3 ]
[]
[]
[ "pygame", "python", "video" ]
stackoverflow_0006400986_pygame_python_video.txt
Q: How do I print out objects in an array in python? I'm writing a code which performs a k-means clustering on a set of data. I'm actually using the code from a book called collective intelligence by O'Reilly. Everything works, but in his code he uses the command line and i want to write everything in notepad++. A...
How do I print out objects in an array in python?
I'm writing a code which performs a k-means clustering on a set of data. I'm actually using the code from a book called collective intelligence by O'Reilly. Everything works, but in his code he uses the command line and i want to write everything in notepad++. As a reference his line is >>>kclust=clusters.kcluster(d...
[ "I assume you want to run this as a program? Simplest way is to simply add those lines at the bottom:\nkclust=clusters.kcluster(data,k=10)\nprint [rownames[r] for r in k[0]]\n\nYou might want to add a main function later if you are planning to expand though.\nEDIT: There is a good description of main functions by G...
[ 2 ]
[]
[]
[ "arrays", "cluster_analysis", "k_means", "printing", "python" ]
stackoverflow_0006426648_arrays_cluster_analysis_k_means_printing_python.txt
Q: Problem with nontypical rounding in python I'm testing a system where is specific rounding - last number is always rounded up e.g. 123,459 should yield 123,46 99,9911 should yield 100,00 How can I implement it in python? EDIT The most important thing - those numbers are prices A: import math def myRounding(x)...
Problem with nontypical rounding in python
I'm testing a system where is specific rounding - last number is always rounded up e.g. 123,459 should yield 123,46 99,9911 should yield 100,00 How can I implement it in python? EDIT The most important thing - those numbers are prices
[ "import math\ndef myRounding(x):\n return math.ceil(x*100) / 100.0\n\nNote that due to floating point not being able to express all decimal fractions, some results won't be able to be expressed in floating point numbers. If this is an issue, calculate in fixed-point numbers (i.e. 1.23 is represented by 123, with ...
[ 4, 0 ]
[ "You can do it using formatter\nNSNumber *Numero = 99.99\nNSNumberFormatter *Formatter = [[NSNumberFormatter alloc] init] ;\n[Formatter setNumberStyle:NSNumberFormatterDecimalStyle]; \n\n//Formatter ROUNDING MODE\n[Formatter setRoundingMode:NSNumberFormatterRoundUp];\n\n[Formatter setMinimumFractionDigits:2];\n...
[ -1 ]
[ "math", "python", "rounding" ]
stackoverflow_0006382892_math_python_rounding.txt
Q: Filename formatting in Python under Windows I have two distincts files called: '╠.txt' and '¦.txt' Such simple code: files = os.listdir('E:\pub\private\desktop\') for f in files: print f, repr(f), type (f) which would return ¦.txt '\xa6.txt' <type 'str'> ¦.txt '\xa6.txt' <type 'str'> I don't get why I am...
Filename formatting in Python under Windows
I have two distincts files called: '╠.txt' and '¦.txt' Such simple code: files = os.listdir('E:\pub\private\desktop\') for f in files: print f, repr(f), type (f) which would return ¦.txt '\xa6.txt' <type 'str'> ¦.txt '\xa6.txt' <type 'str'> I don't get why I am getting the code 0xA6 for the ╠ character instea...
[ "You have to pass a unicode string to os.listdir and Python will return unicode filenames:\n# a string that is unicode+raw (escapes \\)\npath = ur\"E:\\pub\\private\\desktop\"\nprint os.listdir(path)\n# [u'\\xa6.txt', u'\\u2560.txt']\n\nWindows NT actually uses unicode for filenames, but I guess Python tries to enc...
[ 4 ]
[]
[]
[ "codepages", "mbcs", "python", "unicode" ]
stackoverflow_0006425824_codepages_mbcs_python_unicode.txt
Q: WTForms - multi-value string to SelectMultipleField I have a WTForm called TestForm with the following property: areas = SelectMultipleField(u'Test Areas', choices=TestArea.names()) When I create a new instance of TestForm and pass in an object with an areas property, the object doesn't have a list of values for ...
WTForms - multi-value string to SelectMultipleField
I have a WTForm called TestForm with the following property: areas = SelectMultipleField(u'Test Areas', choices=TestArea.names()) When I create a new instance of TestForm and pass in an object with an areas property, the object doesn't have a list of values for areas, but rather a string with a value like Area1;Area2;...
[ "My workaround for now is to have the following setup in my SQLAlchemy model:\nareas = Column(u'AREAS', VARCHAR(80))\n\n@property\ndef areasList(self):\n return self.areas.split(';')\n\n@areasList.setter\ndef areasList(self, areas):\n self.areas = ';'.join(areas)\n\nThen in my WTForms form:\nareasList = Selec...
[ 1 ]
[]
[]
[ "multivalue", "python", "wtforms" ]
stackoverflow_0006426335_multivalue_python_wtforms.txt
Q: PyQt event emmitted twice I'm trying to implement drag-n-drop'in' items from QListWidget to QGraphicsView. I've inherited my own class MooView from QGraphicsView and encapsulated dragMove, dragEnter and drop events. But while testing this out, i've noticed that each event is emmitted twice. Here's my MooView code:...
PyQt event emmitted twice
I'm trying to implement drag-n-drop'in' items from QListWidget to QGraphicsView. I've inherited my own class MooView from QGraphicsView and encapsulated dragMove, dragEnter and drop events. But while testing this out, i've noticed that each event is emmitted twice. Here's my MooView code: from PyQt4 import QtCore, QtGu...
[ "As i've read somewhere in the web, QGraphicsView could pass events to its QGraphicsScene in some cases. So it did here: when i inherited my class from QGraphicsScene and used it as default for QGraphicsView (replaced MooView with QGraphicsView; read the rest of this answer for details) it worked as i was expecting...
[ 2 ]
[]
[]
[ "pyqt", "python", "qt", "signals" ]
stackoverflow_0006424404_pyqt_python_qt_signals.txt
Q: Importing from Python subdirectories This should be straight forward, but I'm not sure whether it's my Eclipse config or my Python. I've got a 2 files /trunk/shared/foo/bar.py and /trunk/shared/foo/io.py There is an __init__.py there too and in shared. All I want to do is import io.py in bar.py. I've tried import...
Importing from Python subdirectories
This should be straight forward, but I'm not sure whether it's my Eclipse config or my Python. I've got a 2 files /trunk/shared/foo/bar.py and /trunk/shared/foo/io.py There is an __init__.py there too and in shared. All I want to do is import io.py in bar.py. I've tried import io, import foo.io and import shared.foo.i...
[ "To allow something like this : \nimport share.foo.bar\nYou should have something like this :\ntrunk/\n shared/__init__.py\n foo/__init__.py\n bar.py\n io.py\n\nThe __init__.py (they must be empty in this case) files are needed to tell to python that it found a pytho...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0006427077_python.txt
Q: Inline-like solution for Django Admin where Admin contains ForeignKey to other model I have several Customers who book Appointments. Each Appointment has exactly one customer, though a customer can be booked for multiple appointments occurring at different times. class Customer(model.Model): def __unicode__(s...
Inline-like solution for Django Admin where Admin contains ForeignKey to other model
I have several Customers who book Appointments. Each Appointment has exactly one customer, though a customer can be booked for multiple appointments occurring at different times. class Customer(model.Model): def __unicode__(self): return u'%s' % (self.name,) name = models.CharField(max_length=30) #...
[ "There is no easy way to do this with django. The inlines are designed to follow relationships backwards. \nPotentially the best substitute would be to provide a link to the user object. In the list view this is pretty trivial:\nAdd a method to your appointment model like:\ndef customer_admin_link(self):\n re...
[ 7, 4, 1 ]
[]
[]
[ "django", "django_admin", "foreign_keys", "python" ]
stackoverflow_0006419248_django_django_admin_foreign_keys_python.txt
Q: in a Python regex matchobj, how to do a substring match, and assign the match to a variable? Given this re.sub and 'replace' function - thanks, Ignacio, for the pointer! - I am able to replace all matches in my very long text blob with the string '* NONSENSE *' - so far, so good! Along the way, I'd like to find th...
in a Python regex matchobj, how to do a substring match, and assign the match to a variable?
Given this re.sub and 'replace' function - thanks, Ignacio, for the pointer! - I am able to replace all matches in my very long text blob with the string '* NONSENSE *' - so far, so good! Along the way, I'd like to find the substring within the matchobj, calling it 'findkey', so I can do additional work with it... Ho...
[ "Are you looking for \nfindkey = re.search(':::([A-Z,a-z]+):::', tag).group()\n\nNote the group() and also this document can help.\n", "Try this. You can match the inner part as part of the initial sub call.\nimport re\n\ndata = \":::::::::::BLAH:::::::::, ::::::::MORE:::::::\"\n\ndef replace(matchobj):\n # thi...
[ 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006419478_python_regex.txt
Q: Django for Facebook Application I've just developed a website with Django, which uses a database. Now I would like to implement my application as a Facebook App, usable in Facebook Canvas. I'm totally a newbie in this area. I've searched all day, but I've not found any good docs or tutorial for an example. Is it s...
Django for Facebook Application
I've just developed a website with Django, which uses a database. Now I would like to implement my application as a Facebook App, usable in Facebook Canvas. I'm totally a newbie in this area. I've searched all day, but I've not found any good docs or tutorial for an example. Is it so difficult? Can you give me some hin...
[ "At the moment Facebook only requires you to work under an Iframe; so you have to show \"normal\" html content, with no extra stuff. Before you could use FBML -a weird facebook markup language- OR Iframe. Now only iframe. So actually any HTML & CSS page you create -with any javascript- will work.\nFor Opengraph, th...
[ 4, 3, 2 ]
[]
[]
[ "django", "facebook", "python" ]
stackoverflow_0006426420_django_facebook_python.txt
Q: Python equivialent of C programming techniques (while loops) In the C programming language, I often have done the following: while ((c = getch()) != EOF) { /* do something with c */ } In Python, I have not found anything similar, since I am not allowed to set variables inside the evaluated expression. I usually ...
Python equivialent of C programming techniques (while loops)
In the C programming language, I often have done the following: while ((c = getch()) != EOF) { /* do something with c */ } In Python, I have not found anything similar, since I am not allowed to set variables inside the evaluated expression. I usually end up with having to setup the evaluated expression twice! c = sy...
[ "You would usually use a for loop in Python:\nfor c in sys.stdin.read():\n # whatever\n\nIf you don't want to buffer the whole stdin in memory at once, you can also add some buffering with a smaller buffer yourself.\nNote that the constant EOF does not exist in Python. read() will simply return an empty string ...
[ 18, 14, 3 ]
[]
[]
[ "c", "python" ]
stackoverflow_0006427161_c_python.txt
Q: Can I improve the speed of random access in a bounded-length deque (circular buffer) in Python? I'm working on writing a small log scraping program in Python, which processes a rolling logfile and stores the offsets in the file for lines of interest. My original solution was running rather quickly on large files b...
Can I improve the speed of random access in a bounded-length deque (circular buffer) in Python?
I'm working on writing a small log scraping program in Python, which processes a rolling logfile and stores the offsets in the file for lines of interest. My original solution was running rather quickly on large files but I didn't have a method for clearing the storage which means that if the program were to continue r...
[ "As with all double-linked lists, random access in a collections.deque is O(n). Consider using a list of bounded lists so that clearing of old entries (del outer[0]) can still proceed in a timely manner even with hundreds of thousands of entries.\n" ]
[ 2 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0006427985_data_structures_python.txt
Q: Python comprehension consolidation I feel there must be an easier (cleaner) way to use comprehensions to parse the meminfo file on linux. The format of the file is: MemTotal: 3045588 kB MemFree: 1167060 kB Buffers: 336752 kB Cached: 721980 kB SwapCached: 0 kB Active: ...
Python comprehension consolidation
I feel there must be an easier (cleaner) way to use comprehensions to parse the meminfo file on linux. The format of the file is: MemTotal: 3045588 kB MemFree: 1167060 kB Buffers: 336752 kB Cached: 721980 kB SwapCached: 0 kB Active: 843592 kB Inactive: 752...
[ "d = {}\nwith open(f) as fin:\n for l in fin:\n x = l.split()\n d[x[0][:-1]] = int(x[1])\nreturn d\n\n", "I find this version much more readable:\ndef parse_mem_file(memfile='/proc/meminfo'):\n data = {}\n with open(memfile, 'r') as f:\n for line in f:\n key, value, size =...
[ 6, 1, 0, 0 ]
[]
[]
[ "list_comprehension", "parsing", "python" ]
stackoverflow_0006427820_list_comprehension_parsing_python.txt
Q: Using python to check existing accounts in several services I'm trying to use urllib and urlib2 to check if a public user profile exists in various socialnets. Now i'm stuck trying to checking www.live.com. If i visit for example this url http://spaces.live.com/profile.aspx?mem=Example@hotmail.com, and the email ...
Using python to check existing accounts in several services
I'm trying to use urllib and urlib2 to check if a public user profile exists in various socialnets. Now i'm stuck trying to checking www.live.com. If i visit for example this url http://spaces.live.com/profile.aspx?mem=Example@hotmail.com, and the email of mem param exists, it redirects to the profile of this account,...
[ "consider using the mechanize module. \nIt exports the interface of urllib2, and also includes a lot of handy stuff for navigating web sites (content parsing, forms, redirects, cookies, etc).\n", "I would add a comment asking for clarification and a code sample, but alas I can't add comments yet. However I'll ta...
[ 0, 0 ]
[]
[]
[ "hotmail", "python", "urllib", "urllib2" ]
stackoverflow_0006427537_hotmail_python_urllib_urllib2.txt
Q: Can I express this as a generator / coroutine? Suppose I have the following class: class MyGen(object): def next(self): return X() def send(self, x): return f(x) Is it possible to express it as a single function, using the yield keyword? Suppose I have g = MyGen(). Note that g.next() shouldn't call f...
Can I express this as a generator / coroutine?
Suppose I have the following class: class MyGen(object): def next(self): return X() def send(self, x): return f(x) Is it possible to express it as a single function, using the yield keyword? Suppose I have g = MyGen(). Note that g.next() shouldn't call f(), and g.send(x) shouldn't call X(), but f() and X(...
[ "This code will be almost equivalent:\ndef my_gen(x=None):\n while True:\n if x is None:\n x = yield X()\n else:\n x = yield f(x)\n\nOne difference is that you can't send a value (other than None) to a generator before calling next() for the first time. Another difference is ...
[ 3, 1 ]
[]
[]
[ "coroutine", "generator", "python" ]
stackoverflow_0006428164_coroutine_generator_python.txt
Q: Django model with crud operations Working with Django and stuck on how to make my model c.r.u.d operations using Models.Manager. The fields I'm working with are zipcode, city, latitude, longitude, coordinates and current time. I would like to insert a new entry with zipcode, city, latitude, longitude and current t...
Django model with crud operations
Working with Django and stuck on how to make my model c.r.u.d operations using Models.Manager. The fields I'm working with are zipcode, city, latitude, longitude, coordinates and current time. I would like to insert a new entry with zipcode, city, latitude, longitude and current time. Also, would like to update an exis...
[ "You should read the django documentation some more https://docs.djangoproject.com/en/1.3/. The tutorial has a portion talking about saving and updating models. However, in answer to your question...\nfrom models import Name\nfrom datetime import datetime\n\n# create a new model\nname = Name(city='New York', state=...
[ 3, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0006419083_django_django_models_python.txt
Q: tkinter: mouse lag on links Writing an application in python/Tkinter, I sometimes have a page with a number of hyperlinks (defined by the class HyperlinkManager, in http://effbot.org/zone/tkinter-text-hyperlink.htm). I noticed that if a large number of links is present, the mouse develops a bit of lag when hoverin...
tkinter: mouse lag on links
Writing an application in python/Tkinter, I sometimes have a page with a number of hyperlinks (defined by the class HyperlinkManager, in http://effbot.org/zone/tkinter-text-hyperlink.htm). I noticed that if a large number of links is present, the mouse develops a bit of lag when hovering on the links. Do you know if th...
[ "There is no particular slowness in Tkinter's handling of tag enter and leave bindings for a reasonable number of tags that I'm aware of, though there may be inefficiencies in the implementation of the HyperlinkManager class. And certainly, what you do with those enter/leave events can introduce some lag. Since ent...
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006426516_python_tkinter.txt
Q: Debugging RadioButtons program in Python from Tkinter import * class Application (Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Select the last book you read.").grid (row = ...
Debugging RadioButtons program in Python
from Tkinter import * class Application (Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): Label(self, text = "Select the last book you read.").grid (row = 0, column = 0, sticky = W) self.choi...
[ "Take a look at the previous line - I only count one closing parenthesis, while you should have two:\n Radiobutton (self,\n text = \"Cat's Cradle by Kurt Vonnegut\",\n variable = self.choice,\n value = \" \\\"Here we are, trapped in the amber of the moment. There is n...
[ 2 ]
[]
[]
[ "python", "radio_button", "tkinter" ]
stackoverflow_0006427245_python_radio_button_tkinter.txt
Q: Reading line by line from a zipped file in python I am trying to read a zipped file in python. I want to read only files with "debug" in their names and only print lines which have BROKER_LOGON in them. It somehow does not read line by line, but prints the entire file which has BROKER_LOGON in it. Please tell me i...
Reading line by line from a zipped file in python
I am trying to read a zipped file in python. I want to read only files with "debug" in their names and only print lines which have BROKER_LOGON in them. It somehow does not read line by line, but prints the entire file which has BROKER_LOGON in it. Please tell me if there is a way to read line by line from a zipped fil...
[ "You can open() a file directly within zipfile\ntry something like this:\ntry:\n root = zipfile.ZipFile(\"C:/Documents and Settings/Desktop/20110526-1708-server.zip\", \"r\")\nexcept:\n root = \".\" \nfor name in root.namelist():\n i = name.find(\"debug\")\n if i>0:\n lines = root.open(name).rea...
[ 4, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006428864_python.txt
Q: Blobstore upload with javascript This is the minimal declaration for the HTML in order to upload a file in Blobstore in the upload_url. What is required with this solution is required to click the Submit button in order the content to be submitted and get redirected. How can I do the post in the background with ja...
Blobstore upload with javascript
This is the minimal declaration for the HTML in order to upload a file in Blobstore in the upload_url. What is required with this solution is required to click the Submit button in order the content to be submitted and get redirected. How can I do the post in the background with javascript or jQuery without losing the ...
[ "The jQuery Form plugin allows you to submit multipart forms in the background with Ajax.\nExample:\n$('#upload_file').submit(function() { \n var options = { \n clearForm: true // clear all form fields after successful submit \n }; \n $(this).ajaxSubmit(options);\n return false; \n});\n\n$...
[ 4 ]
[]
[]
[ "blobstore", "google_app_engine", "html", "javascript", "python" ]
stackoverflow_0006428911_blobstore_google_app_engine_html_javascript_python.txt
Q: Problem 97 - Project Euler : What's wrong with my code? I'm trying to solve problem 97 from project Euler, using python. The goal is to find the last 10 digits of 28433×2^7830457+1 but my solution seems off, and i can't pinpoint what's wrong. I thought about an off-by-one error in my loop, but adding or removing o...
Problem 97 - Project Euler : What's wrong with my code?
I'm trying to solve problem 97 from project Euler, using python. The goal is to find the last 10 digits of 28433×2^7830457+1 but my solution seems off, and i can't pinpoint what's wrong. I thought about an off-by-one error in my loop, but adding or removing one still gives wrong answers, and anyway this one seems logic...
[ "For the sake of clarity, I'll point out that python's built-in pow does modular exponentation. And it's fast.\n>>> pow(2, 5, 30)\n2\n>>> pow(2, 7830456, 6542)\n5778\n>>> timeit.timeit(stmt='pow(2, 5, 30)', number=100000)\n0.031174182891845703\n>>> timeit.timeit(stmt='pow(2, 7830456, 6542)', number=100000)\n0.11496...
[ 6, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0006429083_python.txt
Q: How to rewrite the code more elegantly The code below reads lines from a file, then it executes the custom function (My_Function) and return values to the variables(e.g. condition_A) for line in input_file: if condition_A: condition_A = My_Function(A_tuple[0], B_tuple[0]) if condition_B: ...
How to rewrite the code more elegantly
The code below reads lines from a file, then it executes the custom function (My_Function) and return values to the variables(e.g. condition_A) for line in input_file: if condition_A: condition_A = My_Function(A_tuple[0], B_tuple[0]) if condition_B: condition_B = My_Function(A_tuple[1], B_t...
[ "Instead of having 5 variables condition_*, use a list, conditions:\nconditions=[1]*5 # initialize conditions as you wish\nfor line in input_file:\n for i,condition in enumerate(conditions):\n if condition:\n conditions[i]=My_Function(A_tuple[i],B_tuple[i])\n\n", "What about something like\nc...
[ 8, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006429108_python.txt
Q: Conditional elif statement is not yielding the correct results The elif stament should print the log files and path that were not found in a search that I conduct. However, they yield every line that is searched in a single file (a plethora of info). What am I doing wrong? for line in fileinput.input(walk_dir(dir...
Conditional elif statement is not yielding the correct results
The elif stament should print the log files and path that were not found in a search that I conduct. However, they yield every line that is searched in a single file (a plethora of info). What am I doing wrong? for line in fileinput.input(walk_dir(directory, (".log", ".txt"))): result = regex.search(whitespace.s...
[ "You're iterating over every line of every file passed to fileinput.input(...), right? And you perform the if statement for every line. If the condition is true, then you break, but if the condition is false, you don't break, but write to temp. So for every line in fileinput.input that doesn't match the condition, ...
[ 1 ]
[]
[]
[ "conditional", "python" ]
stackoverflow_0006429380_conditional_python.txt
Q: Videochat using Django? or other Python framework? i wanna make an application with videochat. Something like google chat, with text chat and an option to start live video chat. What do you recommend to me? i don't know where i can start, help me please. Thanks in advance A: I would start by using something el...
Videochat using Django? or other Python framework?
i wanna make an application with videochat. Something like google chat, with text chat and an option to start live video chat. What do you recommend to me? i don't know where i can start, help me please. Thanks in advance
[ "I would start by using something else in your application. Once you've mastered using others and have become familiar with how they work, then perhaps explore how to make your own. I believe for now, the only way of really doing this is to use Flash in some form. I don't believe javascript can grab frames from web...
[ 2 ]
[]
[]
[ "comet", "django", "javascript", "python", "videochat" ]
stackoverflow_0006429342_comet_django_javascript_python_videochat.txt
Q: python objects, garbage collection I have a python object which collects some request data so I can create the model queries based on the filters and sorters I receive via GET method. (sort=id&order=DESC...) class Search( object ): sorters = [] filters = [] If the request has filters and sorters the clas...
python objects, garbage collection
I have a python object which collects some request data so I can create the model queries based on the filters and sorters I receive via GET method. (sort=id&order=DESC...) class Search( object ): sorters = [] filters = [] If the request has filters and sorters the class properties get filled with the right p...
[ "Because you are creating class variables rather than member variables this way. Class variables are shared among every instance (they belong to the class, not an instance); they are similar to static member variables in other languages.\nTo create member variables, you need to initialise them in the constructor, l...
[ 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006429627_python.txt
Q: Python: Socket: Handling TCP connections over a cell network I am doing some socket programming in python in which I develop a client TCP/IP socket to communicate with a slow embedded device. So sometimes, when the response is supposed to be only one package, it is broken in to two packages. My current solution to...
Python: Socket: Handling TCP connections over a cell network
I am doing some socket programming in python in which I develop a client TCP/IP socket to communicate with a slow embedded device. So sometimes, when the response is supposed to be only one package, it is broken in to two packages. My current solution to that is to sleep() the python program, waiting to make sure that ...
[ "Use a networking library like twisted or zeromq.\n", "If it is a single device, you should use a solution that handles the low-level socket interactions for you... python has several like pexpect, exscript, or paramiko (ssh only)... if it is multiple devices and you need asynchronous communication, use @zeekay'...
[ 1, 1, 0 ]
[]
[]
[ "pexpect", "python", "sockets", "tcp" ]
stackoverflow_0006429559_pexpect_python_sockets_tcp.txt
Q: Grouping in Python Regular Expressions So I'm playing around with regular expressions in Python. Here's what I've gotten so far (debugged through RegExr): @@(VAR|MVAR):([a-zA-Z0-9]+)+(?::([a-zA-Z0-9]+))*@@ So what I'm trying to match is stuff like this: @@VAR:param1@@ @@VAR:param2:param3@@ @@VAR:param4:param5:pa...
Grouping in Python Regular Expressions
So I'm playing around with regular expressions in Python. Here's what I've gotten so far (debugged through RegExr): @@(VAR|MVAR):([a-zA-Z0-9]+)+(?::([a-zA-Z0-9]+))*@@ So what I'm trying to match is stuff like this: @@VAR:param1@@ @@VAR:param2:param3@@ @@VAR:param4:param5:param6:0@@ Essentially, you have either VAR o...
[ "If this format is fixed, you don't need regex, it just makes it harder. Just use split:\ntext.strip('@').split(':')\n\nshould do it.\n", "The number of groups in a regular expression is fixed. You will need to postprocess somehow.\n" ]
[ 3, 1 ]
[]
[]
[ "grouping", "python", "regex" ]
stackoverflow_0006430135_grouping_python_regex.txt
Q: How do Python parsers handle indentation? When parsing a freeform language like C, it is easy for the parser to determine when several expressions are related to one another simply by looking at the symbols emitted by the parser. For example, in the code if (x == 5) { a = b; c = d; } The parser can tell ...
How do Python parsers handle indentation?
When parsing a freeform language like C, it is easy for the parser to determine when several expressions are related to one another simply by looking at the symbols emitted by the parser. For example, in the code if (x == 5) { a = b; c = d; } The parser can tell that a = b; and c = d; are part of the same blo...
[ "The indentations are handled with two \"pseudo tokens\" - INDENT and DEDENT. There are some details here. For more information, you should look at the source for the python tokeniser and parser. \n" ]
[ 25 ]
[]
[]
[ "parsing", "python", "whitespace" ]
stackoverflow_0006430297_parsing_python_whitespace.txt
Q: Accessing Facebook Profile URLs The goal here, given a user facebook profile url, access and open the profile page. Some simple python code: from urllib2 import urlopen url = "http://www.facebook.com/username" page = urlopen(url) The problem is that for some "username" this causes HTTP ERROR 404. I noticed this e...
Accessing Facebook Profile URLs
The goal here, given a user facebook profile url, access and open the profile page. Some simple python code: from urllib2 import urlopen url = "http://www.facebook.com/username" page = urlopen(url) The problem is that for some "username" this causes HTTP ERROR 404. I noticed this error only happening when the path inc...
[ "This is a privacy feature of Facebook. Users have the ability to hide their profile page so that only logged in users can view their page. Accessing the page with /profile.php?id=XXX or with /username makes no difference. You must be logged-in in order to view the HTML page.\nIn your context, you'd have to firs...
[ 1, 0, 0, 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0006202795_facebook_python.txt
Q: How does get the title and content of this code? I get this string: {'id': 1, 'weight': 101, 'attrs': {'date_added': 1265274382, 'group_id': 1}}{'id': 2, 'weight': 100, 'attrs': {'date_added': 1265274382, 'group_id': 1}}{'id': 4, 'weight': 100, 'attrs': {'date_added': 1265274382, 'group_id': 2}} I want to get the...
How does get the title and content of this code?
I get this string: {'id': 1, 'weight': 101, 'attrs': {'date_added': 1265274382, 'group_id': 1}}{'id': 2, 'weight': 100, 'attrs': {'date_added': 1265274382, 'group_id': 1}}{'id': 4, 'weight': 100, 'attrs': {'date_added': 1265274382, 'group_id': 2}} I want to get the real data (title and content). My view is: from djang...
[ "I think this link should be helpful for you http://pkarl.com/articles/guide-django-full-text-search-sphinx-and-django-sp/\nAccording to the information provided:\n\nYou have to slice the results before you can use them\n\nSo you would have\nlist(queryset)\n\n" ]
[ 1 ]
[]
[]
[ "django", "python", "sphinx" ]
stackoverflow_0002205466_django_python_sphinx.txt
Q: How do I use the pearsonr function in scipy to find the correlation and P-Value of dictionary values? I have some Python code below: a = dict.values(histodict[str(start)]) b = dict.values(histodict[str(end)]) print pearsonr(a,b) Both variables a and b will print properly as a list when the script is instructed to...
How do I use the pearsonr function in scipy to find the correlation and P-Value of dictionary values?
I have some Python code below: a = dict.values(histodict[str(start)]) b = dict.values(histodict[str(end)]) print pearsonr(a,b) Both variables a and b will print properly as a list when the script is instructed to do so but they will not respond in the pearsonr function in scipy. I am wondering why this doesn't work. T...
[ "From your comment your values are not integers / floats:\na = [float(x) for x in histodict[str(start)].itervalues()]\nb = [float(x) for x in histodict[str(end)].itervalues()]\nprint pearsonr(a,b)\n\n" ]
[ 3 ]
[]
[]
[ "correlation", "dictionary", "python", "scipy" ]
stackoverflow_0006419930_correlation_dictionary_python_scipy.txt
Q: Randomly selecting an object with a weighted probability in Python Possible Duplicates: Random weighted choice Select random k elements from a list whose elements have weights Let's say I have a set of N objects, set = range(a,b) = [a,a+1,...b-2, b-1] To select M number of objects with probability 1/len(N), I c...
Randomly selecting an object with a weighted probability in Python
Possible Duplicates: Random weighted choice Select random k elements from a list whose elements have weights Let's say I have a set of N objects, set = range(a,b) = [a,a+1,...b-2, b-1] To select M number of objects with probability 1/len(N), I can do: random.sample(set, M). I want to able to select objects at rand...
[ "You can use code like this to weigh items, by just adding them multiple times to a different set.\nset = [1,2,3,4,5,6,7,8,9,10]\nweight = 5\nweighted_set = []\nfor i in set: \n if i % 5 == 0:\n weighted_set += weight*[i]\n else:\n weighted_set += [i]\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0006430578_python.txt
Q: Remove blank output being added by lazy method for reading big files I am using the Lazy Method for reading big files to get extract information from text files to store it on a database. def read_in_chunks(file_object, chunk_size=1024): """Lazy function (generator) to read a file piece by piece. Default chunk siz...
Remove blank output being added by lazy method for reading big files
I am using the Lazy Method for reading big files to get extract information from text files to store it on a database. def read_in_chunks(file_object, chunk_size=1024): """Lazy function (generator) to read a file piece by piece. Default chunk size: 1k.""" while True: data = file_object.read(chunk_size) if not d...
[ "There's a couple of issues with what you have. If you use findall, then data could be a list of strings. That won't insert into the database very well like that. \nThe other issue is that the regex could be broken up between the chunks you're reading. You want to look for the pattern, and then use any remainde...
[ 1, 0 ]
[]
[]
[ "database", "lazy_evaluation", "methods", "python", "whitespace" ]
stackoverflow_0006429701_database_lazy_evaluation_methods_python_whitespace.txt
Q: Python: Catch exception and repeat code I have this code: import imaplib, re import os import time conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) conn.login("ddd", "dddd") while(True): unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1) print unreadCount ...
Python: Catch exception and repeat code
I have this code: import imaplib, re import os import time conn = imaplib.IMAP4_SSL("imap.gmail.com", 993) conn.login("ddd", "dddd") while(True): unreadCount = re.search("UNSEEN (\d+)", conn.status("INBOX", "(UNSEEN)")[1][0]).group(1) print unreadCount if int(unreadCount) > 10: ...
[ "import imaplib, re\nimport os\nimport time\n\nwhile True:\n try:\n conn = imaplib.IMAP4_SSL(\"imap.gmail.com\", 993)\n conn.login(\"ddd\", \"dddd\")\n\n while True :\n unreadCount = re.search(\"UNSEEN (\\d+)\", conn.status(\"INBOX\", \"(UNSEEN)\")[1][0]).group(1)\n ...
[ 4, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006430839_python.txt
Q: Implementing logic from text I have a program which recieves inputs in the form of text for example : IF (A.4.1-1/1 OR A.4.1-1/2) AND A.4.4-1/9 AND (A.4.4-1/12 OR A.4.4-1/13 OR A.4.4-1/14 OR A.4.4-1/15) THEN R ELSE N/A where A.4.1-1/1 etc. are variables with a value TRUE or FALSE. so far i have parsed up the text...
Implementing logic from text
I have a program which recieves inputs in the form of text for example : IF (A.4.1-1/1 OR A.4.1-1/2) AND A.4.4-1/9 AND (A.4.4-1/12 OR A.4.4-1/13 OR A.4.4-1/14 OR A.4.4-1/15) THEN R ELSE N/A where A.4.1-1/1 etc. are variables with a value TRUE or FALSE. so far i have parsed up the text into the logical parts for the ab...
[ "This sounds like a task for Pyparsing:\n\nThe pyparsing module is an alternative\n approach to creating and executing\n simple grammars, vs. the traditional\n lex/yacc approach, or the use of\n regular expressions. The pyparsing\n module provides a library of classes\n that client code uses to construct the\...
[ 6, 1 ]
[]
[]
[ "logic", "parsing", "python" ]
stackoverflow_0006430904_logic_parsing_python.txt