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: Gathering data using twitter search API So part of my university project is to collect data from twitter for processing (mainly using the natural language toolkit). I am supposed to collect random samplings for specific hashtags and saving them into a mySQL database. I have been reading articles online and it see...
Gathering data using twitter search API
So part of my university project is to collect data from twitter for processing (mainly using the natural language toolkit). I am supposed to collect random samplings for specific hashtags and saving them into a mySQL database. I have been reading articles online and it seems like Python is rather popular for this kin...
[ "A quick Google search for \"python twitter api getting started\" yields the following:\nhttp://popdevelop.com/2010/07/an-example-on-how-to-use-oauth-and-python-to-connect-to-twitter/\nhttp://code.google.com/p/tweepy/wiki/GettingStarted/\nhttp://www.webmonkey.com/2010/02/get_started_with_the_twitter_api/\nThe Twitt...
[ 0 ]
[]
[]
[ "mysql", "python", "twitter" ]
stackoverflow_0008040365_mysql_python_twitter.txt
Q: Add a subject line to django-contact-form I've been trying to add a subject line to Django-Contact-Form (https://bitbucket.org/ubernostrum/django-contact-form/overview), but I'm having no such luck. The module is by default set to read the subject from a text file, but I want the user to be able to write it into a...
Add a subject line to django-contact-form
I've been trying to add a subject line to Django-Contact-Form (https://bitbucket.org/ubernostrum/django-contact-form/overview), but I'm having no such luck. The module is by default set to read the subject from a text file, but I want the user to be able to write it into a form. Here's what I'm editing in forms.py: ...
[ "Reading the code here, the text file (contact_form/contact_form_subject.txt) is not simply just read in, it's rendered as a template and then inserted into the result. The subject template is passed the full context:\n By default, this context includes:\n\n * All of the validated values in the form, as varia...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008040511_django_python.txt
Q: how to select date from dropdown calender using selenium I have a dropdown calendar and I need to select a date from it using Selenium. I'm using python as my scripting Language. I'm also new to this selenium. A: For the following HTML: <select id="edit-birthday-day" class="form-select" name="birthday[day]"> <o...
how to select date from dropdown calender using selenium
I have a dropdown calendar and I need to select a date from it using Selenium. I'm using python as my scripting Language. I'm also new to this selenium.
[ "For the following HTML:\n<select id=\"edit-birthday-day\" class=\"form-select\" name=\"birthday[day]\">\n <option selected=\"selected\" value=\"\">-</option>\n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n</select>\n\nuse you can use the following scripting in Python:\n sel.select(\"id=edit-...
[ 1 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0007537464_python_selenium.txt
Q: Problem with sh profile in IPython on Mac I recently heard about profiles in python and quickly discovered the sh profile. I went to invoke it to try it out and got the following error on my Mac running Snow Leopard and the system Python2.6. Anyone else see this before? I was thinking about trying to reinstall the...
Problem with sh profile in IPython on Mac
I recently heard about profiles in python and quickly discovered the sh profile. I went to invoke it to try it out and got the following error on my Mac running Snow Leopard and the system Python2.6. Anyone else see this before? I was thinking about trying to reinstall the IPython egg to see if it fixed it, but thought...
[ "I had success running ipython --profile=sh. However, the features of the sh profile (as advertised here) weren't available.\n" ]
[ 0 ]
[]
[]
[ "profile", "python", "shell" ]
stackoverflow_0003553752_profile_python_shell.txt
Q: Import parent module package The directory structure: [app] start.py import package1 [package1] __init__.py print('Init package1') import module1 import subpackage1 module1.py print('package1.module1') import package1 # thi...
Import parent module package
The directory structure: [app] start.py import package1 [package1] __init__.py print('Init package1') import module1 import subpackage1 module1.py print('package1.module1') import package1 # this works OK [subpackage1] ...
[ "I used this hack, which worked for me:\n#import package1.subpackage1 as subpackage1 # AttributeError: 'module' object has no attribute 'subpackage1'\nsubpackage1 = sys.modules[__name__.rpartition('.')[0]] # parent module\n\nOr you can try this:\nfrom package1 import subpackage1\n\nwhich works in some cases: https:...
[ 2, 1 ]
[]
[]
[ "import", "python", "python_3.x" ]
stackoverflow_0008022033_import_python_python_3.x.txt
Q: How do you insert an HTML block (with python) into a currently working website....? Right now I have a solution that works from looking at some examples. It looks like this pagetemp = string.Template(open("index_template.html").read()) #print pagetemp.template f = open("index.html","w") f.write(pagetemp.substitu...
How do you insert an HTML block (with python) into a currently working website....?
Right now I have a solution that works from looking at some examples. It looks like this pagetemp = string.Template(open("index_template.html").read()) #print pagetemp.template f = open("index.html","w") f.write(pagetemp.substitute(sean_final_output=sean_final_output)) f.close() return 1 sean_final_output is an html...
[ "What you are doing is just fine, for a single simple replacement. However, if you're going to do anything more complex, this method will quickly become clumsy.\nIt is worth noting that there are quite a few existing solutions for creating text from templates, especially HTML. Jinja and Django Templates are two exa...
[ 2 ]
[]
[]
[ "html", "python", "substitution" ]
stackoverflow_0008039401_html_python_substitution.txt
Q: Compute the average of the same index in the list, python I have a list as follows: A= [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)] From the list A, I would like to generate the output list like this: Average = [('1', 5), ('2', 6), ('3', 2)] Any tips would be really grateful! =) A: from collect...
Compute the average of the same index in the list, python
I have a list as follows: A= [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)] From the list A, I would like to generate the output list like this: Average = [('1', 5), ('2', 6), ('3', 2)] Any tips would be really grateful! =)
[ "from collections import defaultdict\na = [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)]\nd = defaultdict(list)\nfor k, v in a:\n d[k].append(v)\navg = [(k, sum(v) // len(v)) for k, v in d.iteritems()]\nprint avg\n\nprints\n[('1', 5), ('3', 3), ('2', 6)]\n\nNote that this uses integer division to c...
[ 2, 1, 0 ]
[ "One-liner.\na= [('1', 3), ('2', 7), ('3', 5), ('1', 7), ('2', 5), ('3', 1)]\nmap(lambda f:(f[0][0], (lambda g:sum(g)/len(g))(f[1])), map(lambda e:zip(*e), map(lambda c:filter(lambda d:d[0]==c, a), set(map(lambda b:b[0], a)))))\n\n" ]
[ -1 ]
[ "list", "python" ]
stackoverflow_0008038980_list_python.txt
Q: Python Mechanize: how to select a dropdown list when two have the same name in web page? The html that I'm trying to make mechanize parse is: <select id="topic_id2" name="topics[]" title="blabla" tabindex="4" class="createSelect"> here go options But then right below it there is another dropdown, with the followi...
Python Mechanize: how to select a dropdown list when two have the same name in web page?
The html that I'm trying to make mechanize parse is: <select id="topic_id2" name="topics[]" title="blabla" tabindex="4" class="createSelect"> here go options But then right below it there is another dropdown, with the following code: <select id="topic_id3" name="topics[]" title="optional" tabindex="5" class="createSel...
[ "The external documentation for mechanize is quite small and contains just a few examples, but the in-code documentation is far more extensive.\nNot having tested this, with an HTMLForm instance called form you should be able to call form.find_control(id=\"topic_id3\") and get what you want. I'm not sure how to do ...
[ 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0007459488_mechanize_python.txt
Q: Python, How should this regex work I have a regex that should find all the "heading lines" that contain some text that do not end with a period or ? or !: tit_pat = re.compile(r"([\w ]+?)(?![!?.])\n",re.UNICODE) res = tit_par.findall(data) : Example: Chapter 1x test This a test a test test test test. This a te...
Python, How should this regex work
I have a regex that should find all the "heading lines" that contain some text that do not end with a period or ? or !: tit_pat = re.compile(r"([\w ]+?)(?![!?.])\n",re.UNICODE) res = tit_par.findall(data) : Example: Chapter 1x test This a test a test test test test. This a test with some text and more text.This a...
[ "Your regex basically means \"find as few words as possible, such that there is no unwanted character after the words, and then find a newline immediately after those words\". The word-checking part will not find the unwanted characters because they are not part of words, and the lookahead assertion is redundant be...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008041159_python_regex.txt
Q: In WSGI, send response without returning Is there any way to wrap a WSGI application method such the server will send a response when a particular method is called, rather than when the application method returns a sequence? Basically, I'd like to have the equivalent of a finish_response(responseValue) method. A:...
In WSGI, send response without returning
Is there any way to wrap a WSGI application method such the server will send a response when a particular method is called, rather than when the application method returns a sequence? Basically, I'd like to have the equivalent of a finish_response(responseValue) method.
[ "WSGI app must return an iterable, one way or another. If you want to send partial responses, turn your application into a generator (or return an iterator):\nimport wsgiref, wsgiref.simple_server, time\n\ndef app(environ, start):\n start('200 OK', [('Content-Type', 'text/plain')])\n\n yield 'hello '\n tim...
[ 3 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0008041001_python_wsgi.txt
Q: Python - loading Module in a Python Webserver im trying to get Python to load a module depening on what page is requested from a browser, I have it working if the .py file is in the root of the script, but cant seem to get it working if its in a subdirectory. html files work everywhere, Id appreciate it if someone...
Python - loading Module in a Python Webserver
im trying to get Python to load a module depening on what page is requested from a browser, I have it working if the .py file is in the root of the script, but cant seem to get it working if its in a subdirectory. html files work everywhere, Id appreciate it if someone could help me get the python files to work aswell ...
[ "The first thing to do is to make sure the sub-directory has a file named\n__init__.py\n\nin it. This file can be blank, but you won't be able to do imports without it. Then, you should know that if you're importing from a sub-directory, you'll have to include something like \nmodule = __import__(\"subdirectory.jac...
[ 2 ]
[]
[]
[ "module", "python", "webserver", "windows" ]
stackoverflow_0008041269_module_python_webserver_windows.txt
Q: How can I get a value that's inside parentheses in a string in Python? I've got something like this: a = '2(3.4)' b = '12(3.5)' I only want the value inside the brackets. I used regex, and it worked, but my teacher won't allow it. How can I do this? A: >>> a = '2(3.4)' >>> a[a.index("(") + 1:a.rindex(")")] '3.4...
How can I get a value that's inside parentheses in a string in Python?
I've got something like this: a = '2(3.4)' b = '12(3.5)' I only want the value inside the brackets. I used regex, and it worked, but my teacher won't allow it. How can I do this?
[ ">>> a = '2(3.4)'\n>>> a[a.index(\"(\") + 1:a.rindex(\")\")]\n'3.4'\n\n", ">>> a, b = '2(3.4)', '12(3.5)'\n>>> def extract(string, start='(', stop=')'):\n return string[string.index(start)+1:string.index(stop)]\n\n>>> extract(a), extract(b)\n('3.4', '3.5')\n>>> \n\n" ]
[ 18, 4 ]
[]
[]
[ "python" ]
stackoverflow_0008040795_python.txt
Q: Cython compilation error for free function (Cannot convert Python object argument to type 'FooBar *') I am using Cython (0.15.2) to create an extension for Python (2.6.5). I have created a pxd file and a pyx file. Here are the contents of my pyx file: cimport capifuncs cdef class myArray: cdef capifuncs.myArr...
Cython compilation error for free function (Cannot convert Python object argument to type 'FooBar *')
I am using Cython (0.15.2) to create an extension for Python (2.6.5). I have created a pxd file and a pyx file. Here are the contents of my pyx file: cimport capifuncs cdef class myArray: cdef capifuncs.myArray *_my_array def __cinit__(self, size): self._my_array = capifuncs.array_new(size) if ...
[ "A function defined as cpdef is callable from both Python and C.\nIf the arguments are declared as C data types, Cython will attempt to automatically convert the objects passed into the function when it's called from Python. But such conversions are only possible for numeric and string types - all other types will ...
[ 4 ]
[]
[]
[ "cython", "python", "python_extensions" ]
stackoverflow_0008040526_cython_python_python_extensions.txt
Q: Showing Mouseposition with python I want to track my mouse-position and show that in a tiny window. For that, I created this piece of code: #! /usr/bin/python from Tkinter import * from Xlib import display def mousepos(): data = display.Display().screen().root.query_pointer()._data return data["root_x"],...
Showing Mouseposition with python
I want to track my mouse-position and show that in a tiny window. For that, I created this piece of code: #! /usr/bin/python from Tkinter import * from Xlib import display def mousepos(): data = display.Display().screen().root.query_pointer()._data return data["root_x"], data["root_y"] root = Tk() strl = "mo...
[ "\nUse root.after to call update periodically.\nUse strl = tk.StringVar() and tk.Label(...,textvariable=strl) to\nallow the Label text to change. \nCall strl.set() to change the Label text.\nA default value for screenroot equal to display.Display().screen().root was added\nto mousepos so that most of that long chai...
[ 2 ]
[]
[]
[ "linux", "python", "tkinter", "xlib" ]
stackoverflow_0008041389_linux_python_tkinter_xlib.txt
Q: Rolling a random die twice python I need to run a random 6 sided dice twice and return the sum of them. I am not sure if this is right but I don't think it is, I am still learning python so I am pretty new when it comes to this kind of stuff. import random def roll_die(): roll1 = random.randint(1,6) roll...
Rolling a random die twice python
I need to run a random 6 sided dice twice and return the sum of them. I am not sure if this is right but I don't think it is, I am still learning python so I am pretty new when it comes to this kind of stuff. import random def roll_die(): roll1 = random.randint(1,6) roll2 = random.randint(1,6) total = rol...
[ "It works.\nIt is also best practice to initialize the random generator by calling:\nrandom.seed()\n\nat the beginning of your script, even if it is not necessary, and it is not a mistake to omit it.\nIf you want to test it, add the following:\nprint(roll_die())\n\nat the end of the script, to print the result, sin...
[ 2, 0, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0008041512_python_random.txt
Q: Python BadStatusLine error on certain DELETE requests I am trying to use the python-rest-client ( http://code.google.com/p/python-rest-client/wiki/Using_Connection ) to perform testing of some RESTful webservices. Since I'm just learning, I've been pointing my tests at the sample services provided at http://www.pr...
Python BadStatusLine error on certain DELETE requests
I am trying to use the python-rest-client ( http://code.google.com/p/python-rest-client/wiki/Using_Connection ) to perform testing of some RESTful webservices. Since I'm just learning, I've been pointing my tests at the sample services provided at http://www.predic8.com/rest-demo.htm. I have no problems with creating e...
[ "Apparently the issue is that the server expects there to be some message body for DELETE requests. That's an unusual expectation for a DELETE, but by specifying Content-Length:0 in the headers, I'm able to successfully perform DELETEs.\nSomewhere along the way (in python-rest-client or httplib2), the Content-Leng...
[ 4, 1 ]
[]
[]
[ "httplib2", "python", "rest" ]
stackoverflow_0008031636_httplib2_python_rest.txt
Q: Python creating a game help, (lists) The pseudo code is in notes but I need to define a function that checks the valid moves left in my peg game. The game pretty much randoms two die and it takes the sum of those two numbers and the person pegs the numbers in the list from 1-10 that they roll. In this portion of...
Python creating a game help, (lists)
The pseudo code is in notes but I need to define a function that checks the valid moves left in my peg game. The game pretty much randoms two die and it takes the sum of those two numbers and the person pegs the numbers in the list from 1-10 that they roll. In this portion of it I need to return the portion of the li...
[ "This logic might work:\nvalidMoves = [item for item in pegholes if item != PEGGED]\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008041768_python.txt
Q: if 'x' and 'y' in 'z': I'm making sort of a Q&A script in python. It gets raw_input, and sets it as theQuestion. I tried if 'var1' and 'var2' in theQuestion:, but it looks for either string, not both. Is there a way I can make this work in one 'if' statement? (not 'if x: if y: then z). A: and is a logic...
if 'x' and 'y' in 'z':
I'm making sort of a Q&A script in python. It gets raw_input, and sets it as theQuestion. I tried if 'var1' and 'var2' in theQuestion:, but it looks for either string, not both. Is there a way I can make this work in one 'if' statement? (not 'if x: if y: then z).
[ "and is a logical AND, not a natural-language one. Therefore, your code gets interpreted as:\n'var1' and 'var2' in theQuestion\nTrue and 'var2' in theQuestion # Since bool('var1') == True\n 'var2' in theQuestion\n\nYou want to connect the two tests with a logical AND:\nif 'var1' in theQuestion and 'var2...
[ 17, 2 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0008041944_if_statement_python.txt
Q: Forwarded Email parsing in Python/Any other language? I have some mails in txt format, that have been forwarded multiple times. I want to extract the content/the main body of the mail. This should be at the last position in the hierarchy..right? (Someone point this out if I'm wrong). The email module doesn't giv...
Forwarded Email parsing in Python/Any other language?
I have some mails in txt format, that have been forwarded multiple times. I want to extract the content/the main body of the mail. This should be at the last position in the hierarchy..right? (Someone point this out if I'm wrong). The email module doesn't give me a way to extract the content. if I make a message obje...
[ "\nThe email module doesn't give me a way to extract the content. if I make a message object, the object doesn't have a field for the content of the body.\n\nOf course it does. Have a look at the Python documentation and examples. In particular, look at the walk and payload methods.\n", "Try get_payload on the ...
[ 0, 0 ]
[]
[]
[ "email", "parsing", "python" ]
stackoverflow_0008041852_email_parsing_python.txt
Q: Trouble getting field data from AJAX call What I am trying to do, is when the financial institution is selected from the dropdown, I want to make an AJAX call to compare the selected FI against my query. When I try to print out the selected data, I get None everytime. Here is what I have so far. edit.html javasc...
Trouble getting field data from AJAX call
What I am trying to do, is when the financial institution is selected from the dropdown, I want to make an AJAX call to compare the selected FI against my query. When I try to print out the selected data, I get None everytime. Here is what I have so far. edit.html javascript: q = $("#investment_form").serialize(); f...
[ "I guess the response you get is a 403 (Forbidden), you need to add a @csrf_exempt to your view (1). \n" ]
[ 0 ]
[]
[]
[ "ajax", "django", "django_views", "python" ]
stackoverflow_0008039940_ajax_django_django_views_python.txt
Q: Process.start not working on windows I am running python version 2.7.2 on a linux & windows box. I am running a script which generates child processes using multiprocessing.Process and wait for it do the desire task & then exit eventually. This works fine on Linux but on windows it is giving and error while doing ...
Process.start not working on windows
I am running python version 2.7.2 on a linux & windows box. I am running a script which generates child processes using multiprocessing.Process and wait for it do the desire task & then exit eventually. This works fine on Linux but on windows it is giving and error while doing process.start. The following is the sample...
[ "Since Windows doesn't have a fork() system call, the multiprocessing module has to do some black magic to fork the process. Basically, it tries to guess the entry point to your program, and skips all code executed before the fork is supposed to happen.\nProbably you didn't include a\nif __name__ == '__main__':\n\...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0008042226_python.txt
Q: How to obtain a list of strings such that it represents all the strings in a given list? I have a list of strings. From this list i want to generate a new list of strings such that all the strings are unique (i know i can use the set to do this), but this new list should be such that no string in the new list can...
How to obtain a list of strings such that it represents all the strings in a given list?
I have a list of strings. From this list i want to generate a new list of strings such that all the strings are unique (i know i can use the set to do this), but this new list should be such that no string in the new list can be subset of any other string in the list. EDIT From the comments that i have received, i wil...
[ "I think this should work:\ndef unique_sublist(lst):\n sorted_lst = sorted(lst, key=len, reverse=True)\n subs = set()\n result = []\n for s in sorted_lst:\n if s not in subs:\n subs.update(s[i:j] for i in range(0, len(s))\n for j in range(i+1, len(s)+1))\n ...
[ 2, 2, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008041425_list_python.txt
Q: From where can I get python27.dll and wxmsw dll Our current project is made up of Python2.3 and wxPython-2.4.1.2. It is working fine. But now we are upgrading it to Python2.7 and wxPython2.8.12.1. As I am new to Python and installation dlls, I need little guidence. There are following files present in my NSIS inst...
From where can I get python27.dll and wxmsw dll
Our current project is made up of Python2.3 and wxPython-2.4.1.2. It is working fine. But now we are upgrading it to Python2.7 and wxPython2.8.12.1. As I am new to Python and installation dlls, I need little guidence. There are following files present in my NSIS installation folder for old Python: python23.dll wxmsw24h...
[ "Python DLL:\nc:\\WINDOWS\\system32\\python27.dll\n\nor:\nC:\\Windows\\SysWOW64\\python27.dll\n\nwxPython DLLs:\nc:\\Python27\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\wxbase28uh_net_vc.dll\nc:\\Python27\\Lib\\site-packages\\wx-2.8-msw-unicode\\wx\\wxbase28uh_vc.dll\nc:\\Python27\\Lib\\site-packages\\wx-2.8-msw-...
[ 3 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0008042235_python_wxpython.txt
Q: Set minimum length of a list? I have a list in Python. I don't know exactly how long it is, but I know it's less than 15 items long. I want to pad it out to exactly 15 items long, appending empty strings for all the items that I need to add. Is there an efficient way to do this in Python? I was hoping: myarr = my...
Set minimum length of a list?
I have a list in Python. I don't know exactly how long it is, but I know it's less than 15 items long. I want to pad it out to exactly 15 items long, appending empty strings for all the items that I need to add. Is there an efficient way to do this in Python? I was hoping: myarr = myarr[:15] might work, but it doesn'...
[ "myarr += [\"\"] * (15 - len(myarr))\n\n", "in a oneliner way : \nmyarr.extend([\"\"]* (15 - len(myarr)))\n\n", "To use pure slicing (no call to len):\npadded = (source + [''] * MAX_LEN)[:MAX_LEN]\n\nIf this is called many times, then initialize an ALL_EMPTY list once at module scope. Then do:\npadded = (source...
[ 9, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0008041212_python.txt
Q: Python and Bash: how to automate user input? I downloaded some scripts in both python and bash that prompt the user for command line input. Since I run these scripts often, I would like to automatically supply the input to the programs. I prefer not to modify the scripts. Is there a way to do it without modifyi...
Python and Bash: how to automate user input?
I downloaded some scripts in both python and bash that prompt the user for command line input. Since I run these scripts often, I would like to automatically supply the input to the programs. I prefer not to modify the scripts. Is there a way to do it without modifying the original code? [UPDATE] thanks to EnabrenTa...
[ "Like this on bash: $ ./python_script < input.txt\nedit:\nAlternatively you could write your scripts to take ARGV as a file name to read from. You could reopen STDIN to the file and not have to change any other lines.\n", "Since the responses in via stdin: \ncat answers | yourscript.py\n", "Due to the password ...
[ 3, 1, 1 ]
[]
[]
[ "bash", "python" ]
stackoverflow_0008016175_bash_python.txt
Q: Python while loop/range I need to ask a number from the user and have then if it is in the range of the low/high number then it returns the number and if it isnt in the range, it loops until the number entered is in the range. I don't really know how exactly to do this but I think I have part of it right. My mai...
Python while loop/range
I need to ask a number from the user and have then if it is in the range of the low/high number then it returns the number and if it isnt in the range, it loops until the number entered is in the range. I don't really know how exactly to do this but I think I have part of it right. My main concern is the line "while ...
[ "In this case, the easiest solution is to use True as the condition in the while loop, and an if inside the loop to break out if the number is fine:\ndef ask_number(low, high):\n while True:\n try:\n number = int(raw_input(\"Enter a number within the range: \"))\n except ValueError:\n ...
[ 3, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008042609_python.txt
Q: How to to read a jinja context variable In my mainline I want to read a variable from the current template context, after the template was rendered. This variable has been "set" bij the template. I can access the variable in a context function, but how to access it in my mainline. result = template.render({'a' :...
How to to read a jinja context variable
In my mainline I want to read a variable from the current template context, after the template was rendered. This variable has been "set" bij the template. I can access the variable in a context function, but how to access it in my mainline. result = template.render({'a' : "value-1" }) # in the template {% set b = "v...
[ "I found out, with the help of the webapp2-extras source, that accessing the current jinja context is possible in the python mainline. See also : class jinja2.Template in the jinja documentation.\nPython mainline :\nresult = template.render({'a' : \"value-1\" })\n# in the template {% set b = \"value-2\" %}\nb = tem...
[ 3, 0 ]
[]
[]
[ "jinja2", "python" ]
stackoverflow_0008035006_jinja2_python.txt
Q: Running python unit test over LSF I need to parallelize my python unit-tests which I wrote using the default unittest module. I'm trying to decide between two approaches: keep using unittest but use a custom 'multiprocess' runner which can spawn a test using Platform LSF (remote execution tool) an example can be ...
Running python unit test over LSF
I need to parallelize my python unit-tests which I wrote using the default unittest module. I'm trying to decide between two approaches: keep using unittest but use a custom 'multiprocess' runner which can spawn a test using Platform LSF (remote execution tool) an example can be found in the TestOOB project. Use py.te...
[ "i'd first try to simply install \"pytest-xdist\" from pypi and run your existing tests with \"py.test -n 5\" in 5 parallel processes. If that basically works it means that modifying pytest-xdist to use the LSF transport is a worthwhile option. Effectively you will need to look into extending execnet (http://codes...
[ 1 ]
[]
[]
[ "pytest", "python", "unit_testing", "unittest2" ]
stackoverflow_0007206329_pytest_python_unit_testing_unittest2.txt
Q: Python utility to monitor website uptime (including resources) I'd like to have a utility running to periodically check our websites to make sure they're up and responding. Python is my preferred quick utility environment. I know I can ping the server with urllib2 or something, but I really want to test that all t...
Python utility to monitor website uptime (including resources)
I'd like to have a utility running to periodically check our websites to make sure they're up and responding. Python is my preferred quick utility environment. I know I can ping the server with urllib2 or something, but I really want to test that all the resources are there and available as well (CSS, JS, images, etc)....
[ "For availability monitoring I'd recommend a 3rd party service like newrelic.com or site24x7.com.\nIf you want to roll your own (which isn't so hard if you have only basic needs) just use an HTML parser and iterate over the DOM to request your linked resources. Just don't use regexes.\n" ]
[ 1 ]
[]
[]
[ "monitoring", "python" ]
stackoverflow_0008041954_monitoring_python.txt
Q: Execute a PyDev project in the Python Interactive Console? I'm a begginer in Python and PyDev. I recently made the "helloworld" program in PyDev. My question is: how do I execute it or open it in the interactive Python mode (in Linux terminal) I tried many commands, like ./hello.py, import hello.py, python hello.p...
Execute a PyDev project in the Python Interactive Console?
I'm a begginer in Python and PyDev. I recently made the "helloworld" program in PyDev. My question is: how do I execute it or open it in the interactive Python mode (in Linux terminal) I tried many commands, like ./hello.py, import hello.py, python hello.py, but the only thing I got was SyntaxError: invalid syntax, or ...
[ "To configure PyDev, make sure you read its getting started manual: http://pydev.org/manual_101_root.html\nNow, probably you're having a syntax error because you're using Python 3, where print is no longer a keyword, but a function (so, you have to use print() as a function call), and also have in mind that raw_inp...
[ 0, 0, 0 ]
[]
[]
[ "console", "interactive", "pydev", "python" ]
stackoverflow_0008042866_console_interactive_pydev_python.txt
Q: Changing how returned output is displayed in Django I recently started learning Python/Django as a whole and in an attempt to speed up my learning curve and at the same time do something constructive I've started my own personal project. I've got the latest Django/Python/Jinja2 installed together with the Python B...
Changing how returned output is displayed in Django
I recently started learning Python/Django as a whole and in an attempt to speed up my learning curve and at the same time do something constructive I've started my own personal project. I've got the latest Django/Python/Jinja2 installed together with the Python Battle.net API egg. Currently I'm querying for a "characte...
[ "If you really need to use a classname in template, try using this template filter, or just get it in the view and pass in a context :)\n", "Is there any reason you can't add another variable to the context like so:\nctx = { 'character': character, 'info': info, 'class': repr(info.class_), 'guildname': 'Guild Nam...
[ 0, 0 ]
[]
[]
[ "django", "jinja2", "python" ]
stackoverflow_0008043351_django_jinja2_python.txt
Q: Installing a my Django app on ec2 Im in the process of launching a Django app on ec2, but have hit a wall trying to install my code on my AMI instance. This is my situation: I have a bitnami AMI up and running that has Django, apache, Postgresql, and nearly all my dependancies pre installed, and I have my fully fu...
Installing a my Django app on ec2
Im in the process of launching a Django app on ec2, but have hit a wall trying to install my code on my AMI instance. This is my situation: I have a bitnami AMI up and running that has Django, apache, Postgresql, and nearly all my dependancies pre installed, and I have my fully functional Django app running on my local...
[ "tar -pczf yourfile.tar.gz MyProject\nscp -i /home/user/.cert/yourcert.pem yourfile.tar.gz user@serveripaddress:/home/user\ntar -xvf /home/user/yourfile.tar\n\n", "I usually simply scp -R my whole site directory into /home/bitnami of my AMI. I'm using Apache/NGINX/Django with mod_wsgi. So the directory (for examp...
[ 2, 0, 0 ]
[]
[]
[ "amazon_ec2", "amazon_web_services", "cloud_hosting", "django", "python" ]
stackoverflow_0006310624_amazon_ec2_amazon_web_services_cloud_hosting_django_python.txt
Q: Fix a UnicodeEncodeError caused by smart quotes I am working on a project that involves auto-generating documents (via latex). The person creating these documents is working on a windows machine (he was working with Microsoft word but now he is editing them in notepad). Anyways, I noticed that sometimes after he e...
Fix a UnicodeEncodeError caused by smart quotes
I am working on a project that involves auto-generating documents (via latex). The person creating these documents is working on a windows machine (he was working with Microsoft word but now he is editing them in notepad). Anyways, I noticed that sometimes after he edits the documents, the whole generation process fail...
[ "It's impossible to solve this problem without seeing some code. But in my experience, nine times out of ten unicode errors in Django are caused by a __unicode__ method that doesn't actually don't return Unicode.\nFor example:\ndef __unicode__(self):\n return 'foo %s' % self.bar\n\nBecause the string is a bytestr...
[ 3, 1 ]
[]
[]
[ "django", "latex", "python", "unicode" ]
stackoverflow_0008040643_django_latex_python_unicode.txt
Q: using python to compare lists I have three lists in python. The first two contain strings and the third one contains ids that match the first one. I would like to compare the strings from the second list with all the terms from the first list and when I find the same string I want to take the id from the third lis...
using python to compare lists
I have three lists in python. The first two contain strings and the third one contains ids that match the first one. I would like to compare the strings from the second list with all the terms from the first list and when I find the same string I want to take the id from the third list and replace the string from the s...
[ "First, construct a dictionary mapping the strings in list1 to the corresponding ids. Then, use a list comprehension to apply the mapping:\nlist1 = [\"hello\", \"bye\", \"third\"]\nlist2 = [\"bye\", \"second\", \"forth\"]\nlist3 = [100, 150, 60] \nd = dict(zip(list1, list3))\nprint([d.get(x, x) for x in list2])\n\...
[ 2 ]
[]
[]
[ "list", "python", "python_3.x" ]
stackoverflow_0008043706_list_python_python_3.x.txt
Q: Py.test - Session based setup I'm trying to build a nice base around py.test Some of our tests needs certain test data to work. Today we just specify a mock object as a function argument and do the setup in the generator, this is clearly not desirable. Here is an example of how it could look today: def test_someth...
Py.test - Session based setup
I'm trying to build a nice base around py.test Some of our tests needs certain test data to work. Today we just specify a mock object as a function argument and do the setup in the generator, this is clearly not desirable. Here is an example of how it could look today: def test_something(self, some_data): # some_da...
[ "Here is something that may work as-is, and if not will hopefully point you in the right direction.\nclass TestData(object):\n def __getattr__(self, name):\n if name not in ('data1', 'data2', 'data3'):\n raise AttributeError(\"TestData has no %s\" % name)\n if name == 'data1':\n ...
[ 1, 1 ]
[]
[]
[ "decorator", "pytest", "python" ]
stackoverflow_0008032210_decorator_pytest_python.txt
Q: How to organize code for a Flask application with multiple set of templates I'm writing an application with Flask and I'd like to generate different code for desktop and mobile browsers. IMHO it should be a good idea to keep the application code identical and push the problem of serving different content down the ...
How to organize code for a Flask application with multiple set of templates
I'm writing an application with Flask and I'd like to generate different code for desktop and mobile browsers. IMHO it should be a good idea to keep the application code identical and push the problem of serving different content down the stack at the template level - so it essentially becomes a matter of writing two s...
[ "Replying to myself :)\nI ended up using this solution:\nimport flask\n# patch flask.render_template()\n_render_template = flask.render_template\ndef _my_render_template(*args, **kwargs):\n if detect_mobile_browser(flask.request.user_agent.string):\n args = ('m/' + args[0],) + args[1:]\n return _render...
[ 5, 4 ]
[]
[]
[ "flask", "jinja2", "python" ]
stackoverflow_0007961290_flask_jinja2_python.txt
Q: What is the equivalent of passing functions as arguments using an object oriented approach I have a program in python that includes a class that takes a function as an argument to the __init__ method. This function is stored as an attribute and used in various places within the class. The functions passed in can b...
What is the equivalent of passing functions as arguments using an object oriented approach
I have a program in python that includes a class that takes a function as an argument to the __init__ method. This function is stored as an attribute and used in various places within the class. The functions passed in can be quite varied, and passing in a key and then selecting from a set of predefined functions would...
[ "I'm just going to answer some of your questions.\nAs they say in the Scheme community, \"objects are a poor man's closures\" (closures being first-class functions). Blocks are usually just syntactic sugar for closures. For languages that do not have closures, there exist various solutions.\nOne of the common solut...
[ 1, 1, 1, 0 ]
[]
[]
[ "first_class_functions", "oop", "python" ]
stackoverflow_0007994777_first_class_functions_oop_python.txt
Q: FFT filter vs lfilter in python I have some troubles when applying bandpass filter to signal in Python. Have tried the following to things: Do the box window "by hand", i.e. do the FFT on the signal, apply the filter with a box window and the do the IFFT to get back to the time domain. Use the scipy.signal module...
FFT filter vs lfilter in python
I have some troubles when applying bandpass filter to signal in Python. Have tried the following to things: Do the box window "by hand", i.e. do the FFT on the signal, apply the filter with a box window and the do the IFFT to get back to the time domain. Use the scipy.signal module where I use firwin2 to construct the...
[ "Small differences can be explained by the libraries using different algorithms that accumulate error slightly differently. \nFor example, if you compute the DFT using a radix-2 FFT, a split-radix FFT and an ordinary DFT, the results will all be slightly different. In fact the ordinary DFT has worse accuracy than a...
[ 0 ]
[]
[]
[ "fft", "filter", "python" ]
stackoverflow_0008037990_fft_filter_python.txt
Q: django - urlconf request mapping and views not reached i have a form in a template, but it can't reach the correspondant view. the method is GET. i've tried also to pass it an argument just to populate the query string, but the request doesnt reach the mapped view. here'sthe views.py, urls.py and the template: tem...
django - urlconf request mapping and views not reached
i have a form in a template, but it can't reach the correspondant view. the method is GET. i've tried also to pass it an argument just to populate the query string, but the request doesnt reach the mapped view. here'sthe views.py, urls.py and the template: template.html <div id="search-new-btn"> <form action="/anag...
[ "As Willian suggested don't put the view in a tuple. Another thing you are missing is the $ at the end of regular expression i.e.:\nurls.py\n...\nurl(r'^anagrafica/$','gpf1.views.anagrafica'),\n...\nurl(r'^anagrafica/new/$','gpf1.views.anagrafica_new'),\n...\n\nMake sure that the folder containing gpf1 package is w...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_views", "get", "python" ]
stackoverflow_0008042138_django_django_forms_django_views_get_python.txt
Q: Measuring efficiency of Huffman coding with Python bitstring I have the following string that I would like to Huffman-encode and store efficiently into a bit array: >>> print sequence GTCAGGACAAGAAAGACAANTCCAATTNACATTATG| The frequencies of the symbols in sequence are: >>> print freqTuples [(0.40540540540540543, ...
Measuring efficiency of Huffman coding with Python bitstring
I have the following string that I would like to Huffman-encode and store efficiently into a bit array: >>> print sequence GTCAGGACAAGAAAGACAANTCCAATTNACATTATG| The frequencies of the symbols in sequence are: >>> print freqTuples [(0.40540540540540543, 'A'), (0.1891891891891892, 'T'), (0.16216216216216217, 'C'), (0.16...
[ "I'm not really sure about the bitarray stuff, but shouldn't you just be able to do:\n>>> len(bitArray.tobytes()) / float(len(sequence))\n\nI'm not saying that will solve your problem, but it could be that the \"getsizeof\" thing (again, something I'm not really all that familiar with) is throwing you off.\nFrom wh...
[ 2, 2, 1 ]
[]
[]
[ "bitarray", "bitstring", "compression", "huffman_code", "python" ]
stackoverflow_0008044121_bitarray_bitstring_compression_huffman_code_python.txt
Q: Creating a python game, dealing with lists So I'm creating a very basic python game and I need some help with this step I'm stuck at. The concept of the game is for the program to roll two die and add the sums. With that number they can choose a number available from the number list (1-10) to "peg". They keep g...
Creating a python game, dealing with lists
So I'm creating a very basic python game and I need some help with this step I'm stuck at. The concept of the game is for the program to roll two die and add the sums. With that number they can choose a number available from the number list (1-10) to "peg". They keep going until all numbers are pegged or are out of ...
[ "I am really not sure how your game is supposed to work, but this may help you out:\n#!/usr/bin/env python\n\nimport random\nimport sys\n\npegs = range(2, 11)\n\ndef roll_dice():\n return random.randint(1, 5) + random.randint(1, 5)\n\nwhile True:\n roll = roll_dice()\n print \"You rolled %s\" %roll\n av...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008043913_python.txt
Q: How do I properly serve json data with Python? I've searched high and low for an answer and can't figure out what i'm doing wrong. I'm creating an api that returns json data. I would prefer the response to be printed to the browser as well, if possible. What am I doing wrong? #!/usr/bin/python import simplejson a...
How do I properly serve json data with Python?
I've searched high and low for an answer and can't figure out what i'm doing wrong. I'm creating an api that returns json data. I would prefer the response to be printed to the browser as well, if possible. What am I doing wrong? #!/usr/bin/python import simplejson as json class serve_json: def __init__(self): ...
[ "I'd recommend bottle, it's really easy to build simple little JSON services with it:\nfrom bottle import *\n\n@get('/')\ndef serve_json():\n return {\"msg\": \"Some message\", \"error\": \"Some error\"}\n\nrun(host='localhost', port=8080)\n\nOne neat feature of bottle is that it'll automatically serve JSON from...
[ 3 ]
[]
[]
[ "json", "python" ]
stackoverflow_0008044754_json_python.txt
Q: Histogram in PyQt4 I would like to plot a 1D histogram (bar chart) on my Python application using PyQt4. Anyone have a code example on how to do this or can refer me to an example? Many thanks!! A: Two possible solutions would be: Embedding a matplotlib plot in PyQt (example) Using PyQwt extensions (examples) ...
Histogram in PyQt4
I would like to plot a 1D histogram (bar chart) on my Python application using PyQt4. Anyone have a code example on how to do this or can refer me to an example? Many thanks!!
[ "Two possible solutions would be:\n\nEmbedding a matplotlib plot in PyQt (example)\nUsing PyQwt extensions (examples)\n\n" ]
[ 2 ]
[]
[]
[ "histogram", "pyqt4", "python" ]
stackoverflow_0008044737_histogram_pyqt4_python.txt
Q: Multithreading attempt using Python 3.2.2: "AttributeError: 'str' object has no attribute '_initialized'" I'm running into a problem with the following Python 3.2.2 code. The code is an attempt to do some timing tests of another application I'm testing. The idea is to have another script (of any variety) get passe...
Multithreading attempt using Python 3.2.2: "AttributeError: 'str' object has no attribute '_initialized'"
I'm running into a problem with the following Python 3.2.2 code. The code is an attempt to do some timing tests of another application I'm testing. The idea is to have another script (of any variety) get passed into the timer program and make some changes to the environment. That script should run in a separate thread,...
[ "\nThis is called elsewhere in the script by AsyncScript.start(options.script)\n\nThat invokation is wrong. You're calling threading.Thread's nullary (no arguments - not counting self) start method with your script string as self, instead of instanciating your AsyncScript class (passing the string to __init__) and ...
[ 1, 0, 0 ]
[]
[]
[ "multithreading", "python", "python_3.x" ]
stackoverflow_0008041625_multithreading_python_python_3.x.txt
Q: How simple list functions could be implemented in Python I know that Python has built-in list functions but I'm curious as to how one would write a function to sum a list and a function to reverse a list. I was able to figure out how to write some other list functions (sort, count, index, etc.) but not these, and ...
How simple list functions could be implemented in Python
I know that Python has built-in list functions but I'm curious as to how one would write a function to sum a list and a function to reverse a list. I was able to figure out how to write some other list functions (sort, count, index, etc.) but not these, and I imagine some other languages don't have these built-in funct...
[ "Sum a list\nStraight from the Python manual:\n>>> def sum(seq):\n... def add(x,y): return x+y\n... return reduce(add, seq, 0)\n>>> sum(range(1, 11))\n55\n>>> sum([])\n0\n\nThis could be done as a one-liner (...ish) using lambda (Python's anonymous function syntax):\ndef sum(seq):\n return reduce(lambda ...
[ 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0008044933_list_python.txt
Q: python: how to override SimpleHTTPServer to show timestamp in directory listing? I am using python -m SimpleHTTPServer as a very simple web server for internal users to access data files on a test server. The default listing of SimpleHTTPServer is very simple. It only shows file links. How can I make it to sh...
python: how to override SimpleHTTPServer to show timestamp in directory listing?
I am using python -m SimpleHTTPServer as a very simple web server for internal users to access data files on a test server. The default listing of SimpleHTTPServer is very simple. It only shows file links. How can I make it to show the file timestamp as well? I am happy to write a custom class to extend SimpleHTTP...
[ "You could subclass SimpleHTTPRequestHandler:\nimport cgi, os, SocketServer, sys, time, urllib\nfrom SimpleHTTPServer import SimpleHTTPRequestHandler\nfrom StringIO import StringIO\n\nclass DirectoryHandler(SimpleHTTPRequestHandler):\n def list_directory(self, path):\n try:\n list = os.listdir(...
[ 8 ]
[]
[]
[ "python" ]
stackoverflow_0008044873_python.txt
Q: How do I get Python and ColdFusion to work together using CORBA on Windows? This just seems like something that is easy but I can't find any data on it. A: Read http://www.forta.com/books/0321292693/0321292693_chapter28.pdf
How do I get Python and ColdFusion to work together using CORBA on Windows?
This just seems like something that is easy but I can't find any data on it.
[ "Read http://www.forta.com/books/0321292693/0321292693_chapter28.pdf\n" ]
[ 2 ]
[]
[]
[ "coldfusion", "corba", "python" ]
stackoverflow_0008045157_coldfusion_corba_python.txt
Q: python django analyze a file for a list of keywords I have a list of keywords that I need to ensure are not present in a string. This string could be either plain text or plain text with svn or git repository syntax in it such as a patch. How exactly would you implement this search in the python/django environmen...
python django analyze a file for a list of keywords
I have a list of keywords that I need to ensure are not present in a string. This string could be either plain text or plain text with svn or git repository syntax in it such as a patch. How exactly would you implement this search in the python/django environment; regex, loop, grep? I'd ideally also like to get the li...
[ "txt = open('the_file.txt', 'r').read()\nfor keyword in ['foo', 'bar']:\n if keyword in txt:\n # Do something for when the keyword is found\n print 'Matched keyword %s' % keyword\n\n", "Here you are:\nimport re\n\nBAD_WORDS = [\"spam\", \"ham\"]\nBAD_WORDS_RE = re.compile(r\"\\b(%s)\\b\" % \"|\"....
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008042046_django_python.txt
Q: How can I access attributes of a lazy variable class? I've made myself a lazy variable class, and used it in another class. How can I then access the attributes of the lazy variable class? I have tried __getattr__ without luck. Here's an example: class lazyobject(object): def __init__(self,varname,something...
How can I access attributes of a lazy variable class?
I've made myself a lazy variable class, and used it in another class. How can I then access the attributes of the lazy variable class? I have tried __getattr__ without luck. Here's an example: class lazyobject(object): def __init__(self,varname,something='This is the something I want to access'): self.va...
[ "The way to bypass __get__ when accessing a class attribute is to look it up via the class dictionary rather than using dotted access.\nThis is easy to demonstrate using function objects. For example:\n>>> class A(object):\n def f(self):\n pass\n\n>>> A.f # dotted access c...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0008045069_python.txt
Q: Object Oriented Programming removing repeated items (Python) I'm trying to remove an item from a sorted list. If the item is not in the list, then the list remains unchanged. If the item occurs multiple times, only one occurrence of the item is removed. Again, I'm not allowed to use build-in list functions, but fo...
Object Oriented Programming removing repeated items (Python)
I'm trying to remove an item from a sorted list. If the item is not in the list, then the list remains unchanged. If the item occurs multiple times, only one occurrence of the item is removed. Again, I'm not allowed to use build-in list functions, but for the time being, I'm just trying to get the code to just work! c...
[ "Your remove function seems very confused.\ndef remove(self, item):\n finalSet=[]\n for item in self.s_list:\n if item not in finalSet:\n finalSet.append(item)\n return finalSet\n\n\nWhy are you creating a new list, shouldn't you be modifying the existing list?\nThere are two diff...
[ 2, 1 ]
[]
[]
[ "duplicates", "list", "python" ]
stackoverflow_0008045654_duplicates_list_python.txt
Q: HTTPS Python client I have a tornado server that provide an https connection with a self signed certificate that I generated this way: openssl genrsa -out privatekey.pem 1024 openssl req -new -key privatekey.pem -out certrequest.csr openssl x509 -req -in certrequest.csr -s...
HTTPS Python client
I have a tornado server that provide an https connection with a self signed certificate that I generated this way: openssl genrsa -out privatekey.pem 1024 openssl req -new -key privatekey.pem -out certrequest.csr openssl x509 -req -in certrequest.csr -signkey privatekey.pem -ou...
[ "If you control the client side too (like in an android or iphone app) you can add your self-signed certificate to your trusted certificate store.\nIt is well explained here for an Android app\n", "There is no way for the client to make sure that the server tells the truth. You can create a self-signed certificat...
[ 3, 1 ]
[]
[]
[ "certificate", "https", "mobile", "python", "tornado" ]
stackoverflow_0008045698_certificate_https_mobile_python_tornado.txt
Q: TypeError: 'float' object is not subscriptable When trying to make a histogram in matplotlib When I try and run the following code import matplotlib.pyplot as plt import math import numpy as np from numpy.random import normal masses = [] f = open( 'myfile.txt','r') f.readline() for line in f: if line != ' ':...
TypeError: 'float' object is not subscriptable When trying to make a histogram in matplotlib
When I try and run the following code import matplotlib.pyplot as plt import math import numpy as np from numpy.random import normal masses = [] f = open( 'myfile.txt','r') f.readline() for line in f: if line != ' ': line = line.strip() # Strips end of line character columns = line.split() # Spli...
[ "Based on the docs, I'm pretty sure mass doesn't belong there in the hist() call...\n", "@Ignacio diagnosed it right: you were providing the wrong variable to the hist() call. You had confused the singleton float variable mass for the list variable containing several floats masses. hist() requires a list or any i...
[ 2, 0 ]
[]
[]
[ "histogram", "matplotlib", "python" ]
stackoverflow_0008045956_histogram_matplotlib_python.txt
Q: Python optparse, default values, and explicit options Take the following rather standard code: from optparse import OptionParser opts = OptionParser() opts.add_option('-f', action="store_true") opts.add_option("-x", dest="x", type="int", default=1) options, args = opts.parse_args() Assume...
Python optparse, default values, and explicit options
Take the following rather standard code: from optparse import OptionParser opts = OptionParser() opts.add_option('-f', action="store_true") opts.add_option("-x", dest="x", type="int", default=1) options, args = opts.parse_args() Assume that -x and -f are mutually exclusive: when -x and -f are ...
[ "You can accomplish this with optparse using a callback. Building from your code:\nfrom optparse import OptionParser\n\ndef set_x(option, opt, value, parser):\n parser.values.x = value\n parser.values.x_set_explicitly = True\n\nopts = OptionParser()\nopts.add_option('-f', action=\"store_true\")\nopts.add_opti...
[ 9, 8 ]
[]
[]
[ "optparse", "python" ]
stackoverflow_0008046064_optparse_python.txt
Q: VPython Error on Ubuntu 11.10 I get an error when trying to use VPython on Ubuntu 11.10. I installed the program using the Ubuntu Software Center. All the additional instructions that I've found are either for much older versions or confuse me. What do I need to do in order to use VPython? I am running Python 2.7....
VPython Error on Ubuntu 11.10
I get an error when trying to use VPython on Ubuntu 11.10. I installed the program using the Ubuntu Software Center. All the additional instructions that I've found are either for much older versions or confuse me. What do I need to do in order to use VPython? I am running Python 2.7.2. neil@neilcomp:~$ python Python 2...
[ "It seems like the problem is openGL related.\nTry updating your graphics driver (make sure you have 3D acceleration enabled)\nAlso try installing the dev package for libgtkglextmm-x11, someone on the ubuntu forums seem to have solved their problem this way.\n" ]
[ 5 ]
[]
[]
[ "graphics", "installation", "python", "ubuntu", "vpython" ]
stackoverflow_0008046667_graphics_installation_python_ubuntu_vpython.txt
Q: Project Euler: problem 8 n = # some ridiculously large number, omitted N = [int(i) for i in str(n)] maxProduct = 0 for i in range(0,len(N)-4): newProduct = 1 is_cons = 0 for j in range(i,i+4): if N[j] == N[j+1] - 1: is_cons += 1 if is_cons == 5: for j in range(i,i+5): ...
Project Euler: problem 8
n = # some ridiculously large number, omitted N = [int(i) for i in str(n)] maxProduct = 0 for i in range(0,len(N)-4): newProduct = 1 is_cons = 0 for j in range(i,i+4): if N[j] == N[j+1] - 1: is_cons += 1 if is_cons == 5: for j in range(i,i+5): newProduct *= N[j] ...
[ "I think you've misunderstood the problem. Where it says \"5 consecutive digits\", that only means 5 digits that come one right after another - you're not supposed to check that the values of the digits are consecutive (i.e. each one greater than the last). So throw away all the is_cons logic and just check the pro...
[ 3, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004431252_python.txt
Q: Replace keys with values and write in a new file Python I've got a problem trying to replace keys (dictionary) that I have in a file, with its corresponding values. More details: an input file called event_from_picks looks like: EVENT2593 EVENT2594 EVENT2595 EVENT41025 EVENT2646 EVENT2649 Also, my dictionary, cr...
Replace keys with values and write in a new file Python
I've got a problem trying to replace keys (dictionary) that I have in a file, with its corresponding values. More details: an input file called event_from_picks looks like: EVENT2593 EVENT2594 EVENT2595 EVENT41025 EVENT2646 EVENT2649 Also, my dictionary, created by reloc_event_coords_dic() looks like: {'EVENT23595': ...
[ "just do the following:\nwith open('receiver.in', 'w') as f:\n f.writelines([v[0] for v in reloc_event_coords_dic().itervalues()])\n\n", "Your first loop just leaves the last pair in the coord_line variable.\nBetter do\nevent_dict = reloc_event_coords_dic()\nwith open ('event_from_picks', 'r') as file_in:\n ...
[ 0, 0 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0008047067_dictionary_python.txt
Q: Creating a new Freebsd port I am trying to create a new freeBsd port for cogapp 2.2 . I use the following makefile which actually fetches the tar.gz as expected but does not use easy install to install the package. # New ports collection makefile for: cogapp # Whom: Karthick # # $FreeBSD: po...
Creating a new Freebsd port
I am trying to create a new freeBsd port for cogapp 2.2 . I use the following makefile which actually fetches the tar.gz as expected but does not use easy install to install the package. # New ports collection makefile for: cogapp # Whom: Karthick # # $FreeBSD: ports/devel/py-virtualenv/Makefile,...
[ "It's worked for me with these changes:\nUSE_PYTHON=yes\nUSE_PYDISTUTILS=yes\n\nAnd while i'm there:\n\nUSE_PYTHON defines which python versions are working with this port.\nIf it's \"yes\", then all python version are supported.\nRun 'make makesum' to create distinfo file for your port.\nYou also would need to cre...
[ 2 ]
[]
[]
[ "freebsd", "package", "ports", "python" ]
stackoverflow_0008044173_freebsd_package_ports_python.txt
Q: multiple group matches for single regex I'm parsing a log with python and need quick fetch some values from it this is the simple equivalent regex and usage example pat = re.compile("(1(2[3456]+2)+1)*") It doesn't work as expected, only the last match group is returned by pat.match().groups() What is the simplest...
multiple group matches for single regex
I'm parsing a log with python and need quick fetch some values from it this is the simple equivalent regex and usage example pat = re.compile("(1(2[3456]+2)+1)*") It doesn't work as expected, only the last match group is returned by pat.match().groups() What is the simplest solution for such problems? updated (as wiki...
[ "You are repeating a captured group instead of capturing a repeated group and that is the reason why you are getting only the last capture. \nYou should be using \npat = re.compile(\"((1(2[3456]+2)+1)*)\")\n\nSee here for more on repeating a captured group vs capturing a repeated group http://www.regular-expression...
[ 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0008045885_python_regex.txt
Q: django form with select fields I have the following models class Group(models.Model): name = models.CharField(max_length=32, unique=True) class Subgroup(models.Model): name = models.CharField(max_length=32, unique=True) group = models.ForeignKey(Group) class Keywords(models.Model): name = models....
django form with select fields
I have the following models class Group(models.Model): name = models.CharField(max_length=32, unique=True) class Subgroup(models.Model): name = models.CharField(max_length=32, unique=True) group = models.ForeignKey(Group) class Keywords(models.Model): name = models.CharField(max_length=32, unique=True...
[ "I think you can create form with MultipleChoiceField:\nclass MyForm(forms.Form):\n to_select = forms.MultipleChoiceField(widget=forms.CheckboxInput, choices=[])\n\nIn this case you have to override form`s save method.\nDid you try to create model form for subgroup class?\nclass MyForm(forms.ModelForm):\n cla...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008043766_django_python.txt
Q: Equivalent for loop expression for complex list comprehension The following Python List Comprehension statement could be rephrased as the for loop below. >>> [(x,y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1] >>> result = [] >>> for x in range(5): if x % 2 == 0: for y in range(5):...
Equivalent for loop expression for complex list comprehension
The following Python List Comprehension statement could be rephrased as the for loop below. >>> [(x,y) for x in range(5) if x % 2 == 0 for y in range(5) if y % 2 == 1] >>> result = [] >>> for x in range(5): if x % 2 == 0: for y in range(5): if y % 2 == 1: result.append((x,y)) I...
[ "To use your style:\nI believe the first one does this:\nresult = []\nfor col in range(len(rows[0])):\n a = rows[0][col]\n b = rows[0][col]\n for row in rows:\n a = min(a, row[col])\n b = max(b, row[col])\n\n result.append((a, b))\n\n", "Here is an example to expand the first loop , see ...
[ 3, 1 ]
[]
[]
[ "for_loop", "list_comprehension", "python" ]
stackoverflow_0008047965_for_loop_list_comprehension_python.txt
Q: Call ajax on dropdown button I've created a form and populating its value from Category model in drop down box. Its working. I displayed this form in template like this {{ language_form }}.It worked. Now I want to implement onchange event on this drop down with ajax. Function will call on change of drop down value...
Call ajax on dropdown button
I've created a form and populating its value from Category model in drop down box. Its working. I displayed this form in template like this {{ language_form }}.It worked. Now I want to implement onchange event on this drop down with ajax. Function will call on change of drop down value. Edit:it can be done like this wi...
[ "If you want to just add onchange attr, then:\nclass Language(forms.Form):\n language = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.Select(attrs={'onchange':'ajaxfunction()'}))\n\nOr you can render form manually.\n", "Add this code in the end of your form.\n...\n</form>\n\n <script ...
[ 2, 0 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0008047947_ajax_django_python.txt
Q: manipulate text file line by line or as a whole string? for line in open('file.txt'): print(re.sub('windows', 'linux', line)) or print(re.sub('windows', 'linux', open('file.txt').read())) Which one is better? Is there any differences? BTW. Is is a good idea to manipulate a huge string with a regex? A: As P...
manipulate text file line by line or as a whole string?
for line in open('file.txt'): print(re.sub('windows', 'linux', line)) or print(re.sub('windows', 'linux', open('file.txt').read())) Which one is better? Is there any differences? BTW. Is is a good idea to manipulate a huge string with a regex?
[ "As Polynomial said, the second one reads the whole file into RAM, which may or may not be better.\nBut there is another solution:\nwith open('file.txt') as file:\n for line in file:\n print(re.sub('windows', 'linux', line))\n\nThis ensures that the file will be closed immediately after not needing it any...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008048133_python.txt
Q: SWIG interfacing C library to Python (SWIG generated classes are cumbersome to use) I am using SWIG to generate Python language bindings to my C library. I have managed to build the bindings and exported data structures, but I'm having to jump through some hoops when using the library. For example the C header has...
SWIG interfacing C library to Python (SWIG generated classes are cumbersome to use)
I am using SWIG to generate Python language bindings to my C library. I have managed to build the bindings and exported data structures, but I'm having to jump through some hoops when using the library. For example the C header has data types and function prototypes as follows: struct MyStruct { /* fields */ } st...
[ "Writing a wrapper on the Python side seems like a good idea to me, not sure why you think that is not going to work.\nclass MyStructWrapper:\n def __init__(self):\n self.ms = fb.MYSTRUCT_Alloc()\n\n def __del__(self):\n fb.MYSTRUCT_Free(self.ms)\n\n def func1(self, arg):\n return fb.M...
[ 2, 2, 0 ]
[]
[]
[ "c", "python", "python_extensions", "swig" ]
stackoverflow_0008044870_c_python_python_extensions_swig.txt
Q: Can I store a dict with bitstring values in memory without padding? I have a dict from some hash key to a bitstring. The bitstring can be variable length, but are generally < 160 bits and usually <80. I have about 80M key value pairs. How can I store this data structure in as little memory as possible? I don't wan...
Can I store a dict with bitstring values in memory without padding?
I have a dict from some hash key to a bitstring. The bitstring can be variable length, but are generally < 160 bits and usually <80. I have about 80M key value pairs. How can I store this data structure in as little memory as possible? I don't want to pad the bitstrings, or I will lose quite a bit of space (no pun inte...
[ "If you're referring to padding the bitstrings to an integral number of bytes, then you could store the concatenation of all the initial bitstrings in a single bitstring, and keep a dictionary whose values are tuples of the form (bit position, length).\nProblem is, if I did the math right, then the length of this l...
[ 0 ]
[]
[]
[ "bitstring", "memory", "padding", "python" ]
stackoverflow_0008048047_bitstring_memory_padding_python.txt
Q: How come I can't download this webpage in python? Please try this yourself :) ! curl http://www.windowsphone.com/en-US/apps?list=free the result is: <html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="https://login.live.com/login.srf?wa=wsignin1.0&amp;rpsnv=11&amp;checkda=1&amp;c...
How come I can't download this webpage in python?
Please try this yourself :) ! curl http://www.windowsphone.com/en-US/apps?list=free the result is: <html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="https://login.live.com/login.srf?wa=wsignin1.0&amp;rpsnv=11&amp;checkda=1&amp;ct=1320735308&amp;rver=6.1.6195.0&amp;wp=MBI&amp;wreply=...
[ "The reason it fails is because http://www.windowsphone.com attempts to set a cookie, which is checked on https://login.live.com which creates another cookie and redirects back to windowsphone.com if successful.\nYou should look into http://docs.python.org/library/cookielib.html\nIf you want to use curl, allow it t...
[ 3, 2 ]
[]
[]
[ "curl", "download", "http", "python", "url" ]
stackoverflow_0008046907_curl_download_http_python_url.txt
Q: zope template namespaces gone? Where can I find the zope namespaces for my templates? I setup a pyramid project using SQLAlchemy + URL dispatch + Chameleon templates. These URLs don't exist anymore... http://xml.zope.org/namespaces/tal http://xml.zope.org/namespaces/metal Thanks. A: The TAL specification says:...
zope template namespaces gone?
Where can I find the zope namespaces for my templates? I setup a pyramid project using SQLAlchemy + URL dispatch + Chameleon templates. These URLs don't exist anymore... http://xml.zope.org/namespaces/tal http://xml.zope.org/namespaces/metal Thanks.
[ "The TAL specification says:\n\nThis is not a URL, but merely a unique identifier. Do not expect a browser to resolve it successfully.\n\nhttp://wiki.zope.org/ZPT/TALSpecification14\n" ]
[ 1 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0008045606_python_zope.txt
Q: Quick checkup on python list comprehension I currently generate lists using following expression (T and no_jobs are integers): for i in xrange(no_jobs): row = row + T * [i] The first thing I came up with for converting it into a list comprehension statement was: [T*[i] for i in xrange(no_jobs)] But this obvi...
Quick checkup on python list comprehension
I currently generate lists using following expression (T and no_jobs are integers): for i in xrange(no_jobs): row = row + T * [i] The first thing I came up with for converting it into a list comprehension statement was: [T*[i] for i in xrange(no_jobs)] But this obviously creates a nested list which is not what I'...
[ "Nested loops.\n[i for i in xrange(no_jobs) for x in xrange(T)]\n\n", "\nBut this obviously creates a nested list which is not what I'm looking for.\n\nSo just flatten the result. List addition is concatenation, so we can put all the lists together by 'summing' them (with an empty list as an \"accumulator\").\nsu...
[ 6, 0 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0008047788_list_comprehension_python.txt
Q: Specify repeating tokens in Recursive Descent Parser with NLTK I am trying to parse a grammar similar to this. PER -> 'noun' | 'noun1' | 'noun2' PERS -> PER+ This is not a valid grammar for NLTK's recursive descent parser. How do specifiy one of more repeating tokens in this grammar A: try a rule like: PERS ->...
Specify repeating tokens in Recursive Descent Parser with NLTK
I am trying to parse a grammar similar to this. PER -> 'noun' | 'noun1' | 'noun2' PERS -> PER+ This is not a valid grammar for NLTK's recursive descent parser. How do specifiy one of more repeating tokens in this grammar
[ "try a rule like:\nPERS -> PER PERS | PER\n\n" ]
[ 1 ]
[]
[]
[ "nlp", "nltk", "python", "recursive_descent" ]
stackoverflow_0008047099_nlp_nltk_python_recursive_descent.txt
Q: SOAP server in python that also generates WSDL I'm looking to implement a SOAP web service in python on top of IIS. Is there a recommended library that would take a given Python class and expose its functions as web methods? It would be great if said library would also auto-generate a WSDL file based on the interf...
SOAP server in python that also generates WSDL
I'm looking to implement a SOAP web service in python on top of IIS. Is there a recommended library that would take a given Python class and expose its functions as web methods? It would be great if said library would also auto-generate a WSDL file based on the interface.
[ "There is an article by Doug Hellmann that evaluates various SOAP Tools\n\nhttp://doughellmann.com/2009/09/01/evaluating-tools-for-developing-with-soap-in-python.html\n\nOther ref:\n\nhttp://wiki.python.org/moin/WebServices\nhttp://pywebsvcs.sourceforge.net/\n\n", "You might want to take a look at https://github....
[ 2, 2, 0 ]
[]
[]
[ "iis", "python", "soap", "web_services", "wsdl" ]
stackoverflow_0004089843_iis_python_soap_web_services_wsdl.txt
Q: How can I inform sqlalchemy to raise an error whenever MySQL throws a warning? I want to modify sqlalchemy settings to raise an exception on warnings. For example, when I insert a larger amount of data in a field than the defined column length, mysql will truncate the data, insert the truncated data into the field...
How can I inform sqlalchemy to raise an error whenever MySQL throws a warning?
I want to modify sqlalchemy settings to raise an exception on warnings. For example, when I insert a larger amount of data in a field than the defined column length, mysql will truncate the data, insert the truncated data into the field and issue a warning. Instead of the warning, I would like sqlalchemy to raise an ap...
[ "To turn the “oh by the way I mangled your data” warnings into errors, \nset an appropriate server mode for MySQL.\nWith SQLAlchemy, you should choose ANSI, as you probably don't have to worry about your old queries being compatible with some brokenMySQL-specific behavior.\nSee the SQLAlchemy docs on how to do it.\...
[ 6 ]
[]
[]
[ "mysql", "mysql_python", "python", "sqlalchemy", "warnings" ]
stackoverflow_0008048384_mysql_mysql_python_python_sqlalchemy_warnings.txt
Q: cx_oracle: can callfunc return list? I'm trying to write a PL/SQL function that returns an array of integers and then be able to call it with cx_Oracles callfunc. I think I got the PL/SQL function right, but I don't know how to call it with cx_Oracle. create or replace type test_type is table of NUMBER(10); create...
cx_oracle: can callfunc return list?
I'm trying to write a PL/SQL function that returns an array of integers and then be able to call it with cx_Oracles callfunc. I think I got the PL/SQL function right, but I don't know how to call it with cx_Oracle. create or replace type test_type is table of NUMBER(10); create or replace function test_function (n in I...
[ "Something in the lines of,\nimport cx_Oracle\n\ndb_sid = 'db_sid'\ndb_usr = 'schema'\ndb_pwd = 'passwd'\n\nconn_data = str('%s/%s@%s') % (db_usr, db_pwd, db_sid)\n\ntry:\n db = ora.connect(conn_data)\n except ora.DatabaseError, e:\n error, = e\n ORAmessage = error.message.rstrip(\"\\n\")\n print \"D...
[ 1 ]
[]
[]
[ "cx_oracle", "oracle", "plsql", "python" ]
stackoverflow_0008048124_cx_oracle_oracle_plsql_python.txt
Q: Sometimes PyDev doesn't recognise .py files as python source files Sometimes when I open a python file (.py extension) in the PyDev Package Explorer, that file is opened as a plain text file - without syntax highlighting, breakpoint setting and all the other great PyDev features. I cannot see any differences to ot...
Sometimes PyDev doesn't recognise .py files as python source files
Sometimes when I open a python file (.py extension) in the PyDev Package Explorer, that file is opened as a plain text file - without syntax highlighting, breakpoint setting and all the other great PyDev features. I cannot see any differences to other files in the same folder. When I create another .py file (this time ...
[ "If this happens (and the association for file marks \"Python editor\" as the default in the preferences), you can right-click the file and do \"open with > other\" and choose \"Python editor\" from the list. \nThat setting should be persisted for that file later on (what could've happened is that you opened the fi...
[ 9, 4 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0008045991_eclipse_pydev_python.txt
Q: using object_set in django template I have these models: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") class Image(models.Model): Image = models.ImageField(upload_to="gallery") Gallery = models.ForeignKey(Gallery, related_name='images') in template i have a gallery obje...
using object_set in django template
I have these models: class Gallery(models.Model): HeadImage = models.ImageField(upload_to="gallery") class Image(models.Model): Image = models.ImageField(upload_to="gallery") Gallery = models.ForeignKey(Gallery, related_name='images') in template i have a gallery object,now I wanna iterate it's image objects...
[ "Why do you use gallery.image_set.all? Related name for images in your Gallery model is \"images\".\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0008049240_django_python.txt
Q: How can I use python to read windows eventlog from a remote machine? I'm working on retrieving the Windows eventlog from a remote machine using Python. I tried the following code: import win32evtlog server = 'aRemoteMachineHostName' logtype = 'System' hand = win32evtlog.OpenEventLog(server,logtype) total = win...
How can I use python to read windows eventlog from a remote machine?
I'm working on retrieving the Windows eventlog from a remote machine using Python. I tried the following code: import win32evtlog server = 'aRemoteMachineHostName' logtype = 'System' hand = win32evtlog.OpenEventLog(server,logtype) total = win32evtlog.GetNumberOfEventLogRecords(hand) and I get an access denied erro...
[ "might be easier to use snmp\n", "As long as the user who is executing the script has the credentials to connect and read the event log, this ActiveState Recipe works for me. I've used it in a few different situations.\nActiveState WinEvtLogViewer\n" ]
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004457569_python.txt
Q: Python + getopt - Problems with parsing I have some problems with writing some Gerrit http://code.google.com/p/gerrit/ hooks. http://gerrit.googlecode.com/svn/documentation/2.2.0/config-hooks.html If I parse the command line for patchset-created --change --change-url --project --branch --uploader --commit --...
Python + getopt - Problems with parsing
I have some problems with writing some Gerrit http://code.google.com/p/gerrit/ hooks. http://gerrit.googlecode.com/svn/documentation/2.2.0/config-hooks.html If I parse the command line for patchset-created --change --change-url --project --branch --uploader --commit --patchset def main(): if (len(sys.argv) < 2)...
[ "As the options names and values are space-separated, you have to put the values in quotes if they contain spaces themselves.\nIf you write --uploader xxxxxxx-xxxxx xxxxxxx (xxxxxxxxxxxxx.xxxxxxx@xxx-xxxx.xx), the last two strings will actually end up in args from the line\noptlist, args = getopt.getopt(sys.argv[1:...
[ 2, 1, 0 ]
[]
[]
[ "gerrit", "parsing", "python" ]
stackoverflow_0008049093_gerrit_parsing_python.txt
Q: mp3info giving an error with variable filename I have been using mp3info to calculate my file length using the following syntax: mp3info -p "%S" /path/to/file whenever I use the code with the filename I get the correct output: mp3info -p "%S" far_from_love.mp3 However, on storing the filename in a string varia...
mp3info giving an error with variable filename
I have been using mp3info to calculate my file length using the following syntax: mp3info -p "%S" /path/to/file whenever I use the code with the filename I get the correct output: mp3info -p "%S" far_from_love.mp3 However, on storing the filename in a string variable and then using the variable I get an error: Syn...
[ "x=os.popen('mp3info -p \"%S\" f).read()\n\nis missing a closing quote:\nx=os.popen('mp3info -p \"%S\" ' + f).read()\n\nYou may also want to use the safer subprocess module:\nimport subprocess\nx = subprocess.check_output(['mp3info', '-p', '%S', f])\n\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0008049971_python.txt
Q: PyQt get date from the user I built simple widget in Qt Designer with a button and a QDateEdit. The user will enter the date into the QDateEdit and then when he presses the button, the date will be saved to a variable. How can I do it? A: You can make it simply: var_name = self.dateEdit.date() This will get you...
PyQt get date from the user
I built simple widget in Qt Designer with a button and a QDateEdit. The user will enter the date into the QDateEdit and then when he presses the button, the date will be saved to a variable. How can I do it?
[ "You can make it simply:\nvar_name = self.dateEdit.date()\n\nThis will get you a variable in QDate format.\nIf you need it in a format which would be easier to work with then you should use this:\ntemp_var = self.dateEdit.date() \nvar_name = temp_var.toPyDate()\n\nThe first one gives you: \"PyQt4.QtCore.QDate(2011,...
[ 21 ]
[]
[]
[ "pyqt", "python", "qt_designer", "user_interface" ]
stackoverflow_0008049055_pyqt_python_qt_designer_user_interface.txt
Q: single key with multiple values in a dict can I have a global dict in my code which is something like the following: group = { 'vowel' : ['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'], 'consonant' : ['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng...
single key with multiple values in a dict
can I have a global dict in my code which is something like the following: group = { 'vowel' : ['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'], 'consonant' : ['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y...
[ "It's more effective to use sets (you can group them in dict if you want):\nvowels = set(['aa', 'ae', 'ah', 'ao', 'eh', 'er', 'ey', 'ih', 'iy', 'uh', 'uw', 'o'])\nconsonants = set(['b', 'ch', 'd', 'dh', 'dx', 'f', 'g', 'hh', 'jh', 'k', 'l', 'm', 'n', 'ng', 'p', 'r', 's', 'sh', 't', 'th', 'v', 'w', 'y', 'z', 'zh'])\...
[ 11, 3, 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0008050264_python.txt
Q: Understanding nested list comprehension I want to understand nested list comprehension. Below, I listed a list comprehension expression and their for loop equivalent. I wonder if my understanding is correct on those. For example, [(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len...
Understanding nested list comprehension
I want to understand nested list comprehension. Below, I listed a list comprehension expression and their for loop equivalent. I wonder if my understanding is correct on those. For example, [(min([row[i] for row in rows]),max([row[i] for row in rows])) for i in range(len(rows[0]))] is equivalent to result=[] for ...
[ "Indeed, you are correct. This is described in detail in the Expressions section in the Python Language Reference.\nNote especially the order of nesting of several fors in a single list comprehension, which is always left-to-right:\n>>> matrix = [[1, 2], [3, 4]]\n>>> [item for item in row for row in matrix] # oops!...
[ 78, 75 ]
[]
[]
[ "list_comprehension", "nested", "python" ]
stackoverflow_0008049798_list_comprehension_nested_python.txt
Q: Wikipedia philosophy game diagram in python and R So I am relatively new to python, and in order to learn, I have started writing a program that goes online to wikipedia, finds the first link in the overview section of a random article, follows that link and keeps going until it either enters a loop or finds the p...
Wikipedia philosophy game diagram in python and R
So I am relatively new to python, and in order to learn, I have started writing a program that goes online to wikipedia, finds the first link in the overview section of a random article, follows that link and keeps going until it either enters a loop or finds the philosophy page (as detailed here) and then repeats thi...
[ "I'll just answer the second question:\nFor a start, just keep a dict mapping one Wikipedia article title to the next. This will make it easy and fast to check I've you've hit an article you've already found before. Essentially this is just storing a directed graph's vertices, indexed by their origins.\nIf you get ...
[ 4, 1 ]
[]
[]
[ "parsing", "python", "wikipedia" ]
stackoverflow_0008050110_parsing_python_wikipedia.txt
Q: python: copy selected csv columns to other csv file when one header is empty I have some large csv file, with about 200 header names (the first one of which is empty). I want to get some chosen columns and copy them to a new output.csv file. My problem comes grabbing the header which has no name! (empty first ele...
python: copy selected csv columns to other csv file when one header is empty
I have some large csv file, with about 200 header names (the first one of which is empty). I want to get some chosen columns and copy them to a new output.csv file. My problem comes grabbing the header which has no name! (empty first element in the header) So the input.csv looks something like, ,header1,he...
[ "In the CSV format, the first header should be a zero-length string (''), not a space (' '), which is what you use in SelectedSignals.\nYou could also add a fake column name to your name2index dict, for example name2index['header0'] = 0 just after name2index = ... and then use 'header0' in SelectedSignals.\nAlterna...
[ 1 ]
[]
[]
[ "csv", "parsing", "python", "string" ]
stackoverflow_0008050543_csv_parsing_python_string.txt
Q: Multiple use of exit() in Python Is it a bad coding practice to call the exit() function in Python repeatedly? I'm working on a command-line tool, so there are multiple function definitions... Basically: def usage() def error(arg1) def find(arg1, arg2) In the end of usage() I call exit(), which I assume it's OK, ...
Multiple use of exit() in Python
Is it a bad coding practice to call the exit() function in Python repeatedly? I'm working on a command-line tool, so there are multiple function definitions... Basically: def usage() def error(arg1) def find(arg1, arg2) In the end of usage() I call exit(), which I assume it's OK, but it's also called in the success of...
[ "It does work to call exit() on multiple locations and if it's simple program with only you using it it's no problem. But in my opinion it always makes inspecting/debugging code more complex if there are multiple exit points. Especially if you think other developers will at some point be modifying your code or you ...
[ 4, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008050455_python.txt
Q: Encoding data of mixed type? I've got an array as follows: row = [u'Arun DC', 4.0, 34.0, 76.0, 223.52941176470588, u'yes', 0.0, '', '', '', '', u'yes', '', u'yes', u'yes', u'yes', u'no', u'\xa37.50 - \xa310 not clear what this is for', u'\xa37.50 - \xa310 not clear what this is for', '', u'\xa37.50 - \xa310 not cl...
Encoding data of mixed type?
I've got an array as follows: row = [u'Arun DC', 4.0, 34.0, 76.0, 223.52941176470588, u'yes', 0.0, '', '', '', '', u'yes', '', u'yes', u'yes', u'yes', u'no', u'\xa37.50 - \xa310 not clear what this is for', u'\xa37.50 - \xa310 not clear what this is for', '', u'\xa37.50 - \xa310 not clear what this is for', u'\xa37.50 ...
[ "[x.encode('latin-1') if isinstance(x, unicode) else x\n for x in row]\n\n", "[i.encode('latin-1') if isinstance(i, unicode) else i for i in row]\n\n", "[('%s'%a).encode('latin-1') for a in row]\n\nreturns a list of strings. You could use it to write out to CSV.\n" ]
[ 8, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008050631_python.txt
Q: Numpy: equivalent of numpy.roll but only for data visualisation Is there a way to perform a roll on an array, but instead of having a copy of the data having just a different visualisation of it? An example might clarify: given b a rolled version of a... >>> a = np.random.randint(0, 10, (3, 3)) >>> a array([[6, 7...
Numpy: equivalent of numpy.roll but only for data visualisation
Is there a way to perform a roll on an array, but instead of having a copy of the data having just a different visualisation of it? An example might clarify: given b a rolled version of a... >>> a = np.random.randint(0, 10, (3, 3)) >>> a array([[6, 7, 4], [5, 4, 8], [1, 3, 4]]) >>> b = np.roll(a, 1, axis...
[ "This is not possible, sorry. The rolled array cannot be described by a different set of strides, which would be necessary for a NumPy view to work.\n" ]
[ 9 ]
[]
[]
[ "numpy", "python", "python_2.7" ]
stackoverflow_0008050789_numpy_python_python_2.7.txt
Q: How to navigate to and enter input in nested frame/form with mechanize I want to enter some text (login, password) inside a page with frames. The structure is something like: <html xmlns="http://www.w3.org/1999/xhtml"> <head>Whatever</head> <body id="Body"> <form id="frmM" onsubmit="javascr...
How to navigate to and enter input in nested frame/form with mechanize
I want to enter some text (login, password) inside a page with frames. The structure is something like: <html xmlns="http://www.w3.org/1999/xhtml"> <head>Whatever</head> <body id="Body"> <form id="frmM" onsubmit="javascript:return whatever();" action="Login.aspx" method="post"> ...
[ "2 options:\n\nAccess the URL within the iframe directly and then do your form login\nLogin to the site from your browser and use an extension like Firebug\nto track the posted data. Then replicate this request to login\nautomatically.\n\n" ]
[ 4 ]
[]
[]
[ "iframe", "mechanize", "python", "screen_scraping" ]
stackoverflow_0006445284_iframe_mechanize_python_screen_scraping.txt
Q: class and private variables class Test1: def __init__( self ): self.__test = 1 def getvalue( self ): return self.__test class Test2( Test1 ): def __init__( self ): Test1.__init__( self ) self.__test = 2 test = Test2() Why print test.getvalue() return 1 ? A: In Pytho...
class and private variables
class Test1: def __init__( self ): self.__test = 1 def getvalue( self ): return self.__test class Test2( Test1 ): def __init__( self ): Test1.__init__( self ) self.__test = 2 test = Test2() Why print test.getvalue() return 1 ?
[ "In Python, private member __bar of class Foo will be automatically renamed to _Foo__bar, so the __test in Test1 is _Test1__test and that in Test2 is _Test2__test. The two members are actually different. This is by design, to \"avoid name clashes of names with names defined by subclasses\".\nUse a single underscore...
[ 9, 6, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006187190_python.txt
Q: BooleanField vs. CharField in Django Models In my app model, I have a BooleanField: campaign = models.BooleanField(default=False, db_index=True, verbose_name=_('processed'), help_text=_('Campaign or not ?')) I use this to distinguish between two things. So, I thought of sending this value as hidden from an ht...
BooleanField vs. CharField in Django Models
In my app model, I have a BooleanField: campaign = models.BooleanField(default=False, db_index=True, verbose_name=_('processed'), help_text=_('Campaign or not ?')) I use this to distinguish between two things. So, I thought of sending this value as hidden from an html form: <input type="hidden" name="campaign" val...
[ "\nforms send strings and I want to convert that string into a boolean.\n\nAll data in request.POST comes as strings or lists of strings. You need to convert it yourself or use django forms (preferred) which do the the work for you.\nWith django forms you can replace the widget when you initiate forms.BooleanField ...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "html", "python" ]
stackoverflow_0008051316_django_django_forms_django_models_html_python.txt
Q: Raise exception if sqlite query is empty I have a method that do a sql-query and return a value. If empty it raise an exception. The code works as expected but it seems like there's a more clean way to do it? Or is it? def get_song(self, number): db_cursor.execute("select * from songs where Id = ?", number) ...
Raise exception if sqlite query is empty
I have a method that do a sql-query and return a value. If empty it raise an exception. The code works as expected but it seems like there's a more clean way to do it? Or is it? def get_song(self, number): db_cursor.execute("select * from songs where Id = ?", number) song = db_cursor.fetchone() if song: ...
[ "As the True statement doesn't improve your code (you just want to be assured it is not False) you could preserve some lines doing so:\nif song != True:\n raise ValueError\n\nor\nif song == Null:\n raise ValueError\n\n" ]
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0008051128_python_sqlite.txt
Q: urllib2 redirect empty page (though code is 200 and geturl() points to new page) I am trying to access a web page using urllib2 and the automatic redirect in urllib2 does not seem to retrieve the entire page. Here is my code: request = urllib2.Request(link) request.add_header('User-Agent','...') opener = urllib2....
urllib2 redirect empty page (though code is 200 and geturl() points to new page)
I am trying to access a web page using urllib2 and the automatic redirect in urllib2 does not seem to retrieve the entire page. Here is my code: request = urllib2.Request(link) request.add_header('User-Agent','...') opener = urllib2.build_opener() page = opener.open(request) print(page.code) print(page.geturl()) prin...
[ "View the source of the Google page - it really does end with a script tag. They leave off some of the closing tags because browsers can still interpret it correctly and it saves bandwidth. \nHere are some test redirect pages. Which of those do not work for you?\n" ]
[ 0 ]
[]
[]
[ "python", "screen_scraping", "urllib2" ]
stackoverflow_0004190461_python_screen_scraping_urllib2.txt
Q: Python GqlQuery not displaying content I have code which suppose to put 2 Objects(classes) to database and return all values. In my design: Table "Person" which contain records in following format: ("name", num, num, "group"). Following code displays: "None". What is wrong here? How to get all records for this "Ta...
Python GqlQuery not displaying content
I have code which suppose to put 2 Objects(classes) to database and return all values. In my design: Table "Person" which contain records in following format: ("name", num, num, "group"). Following code displays: "None". What is wrong here? How to get all records for this "Table"? class Person(db.Model): name = db....
[ "Well the code is right . \nquery = db.GqlQuery('SELECT * FROM Person' )\n\nresult = query.fetchAll() \nOR \nresult = query.fetch(5)\n\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0008051221_python.txt
Q: Select divs between html comments in lxml This is my html file <div> <div></div> <div></div> <!--Comment1--> <div>1</div> <div>2</div> <div>3</div> <!--Comment2--> <div></div> <div></div> <div></div> </div> and I want to select divs between Comment 1 and Comment 2 With this xPath = "...
Select divs between html comments in lxml
This is my html file <div> <div></div> <div></div> <!--Comment1--> <div>1</div> <div>2</div> <div>3</div> <!--Comment2--> <div></div> <div></div> <div></div> </div> and I want to select divs between Comment 1 and Comment 2 With this xPath = "/div/comment()" I can select <!--Comment1--><!-...
[ "//*[preceding-sibling::comment() and following-sibling::comment()]\n\nOr stricter version:\n//*[preceding-sibling::comment()[. = 'Comment1'] \n and following-sibling::comment()[. = 'Comment2']]\n\n", "In XPath 1.0 one can use the general (Kayessian) method for intersection of two node-sets $ns1 and $ns2:\n$ns...
[ 7, 1 ]
[]
[]
[ "html", "parsing", "python", "xml", "xpath" ]
stackoverflow_0008050929_html_parsing_python_xml_xpath.txt
Q: How can I rename files with a python script? On my plone site I have hundreds of files (pdf, doc, ...) in filefield of archetypes objects. Something went wrong during importation and all the filenames are missing. The problem is that when somebody wants to open the file, since the extension is missing, the browse...
How can I rename files with a python script?
On my plone site I have hundreds of files (pdf, doc, ...) in filefield of archetypes objects. Something went wrong during importation and all the filenames are missing. The problem is that when somebody wants to open the file, since the extension is missing, the browser doesn't always propose to open it with a viewer....
[ "http://plone.org/documentation/manual/plone-community-developer-documentation/content/rename\nyou've all you need here :)\nThe important part is this: parent.manage_renameObject(id, id + \"-old\")\nyou can loop over the subobjects doing:\nfor i in context.objectIds():\n obj = context[i]\n context.manage_renameObje...
[ 3, 2 ]
[]
[]
[ "archetypes", "filefield", "filenames", "plone", "python" ]
stackoverflow_0008051032_archetypes_filefield_filenames_plone_python.txt
Q: Inserting tuple's elements to database I have a tuple that i wanna store its elements, I'm trying to insert it as following and it gives the following error, what am i doing wrong ? records_to_be_inserted is the tuple that has 8 elements. with self.connection: cur = self.connection.cursor() cur.exe...
Inserting tuple's elements to database
I have a tuple that i wanna store its elements, I'm trying to insert it as following and it gives the following error, what am i doing wrong ? records_to_be_inserted is the tuple that has 8 elements. with self.connection: cur = self.connection.cursor() cur.executemany("INSERT INTO rehberim(names, phone,...
[ "Note that the executemany is for inserting multiple rows, e.g.,\nimport sqlite3\n\n\"\"\" the table structure is:\ncreate table tab\n a char(1),\n b char(2),\n c char(3)\n)\n\"\"\"\n\nconn = sqlite3.connect('C:\\\\test.db')\nstmt = \"insert into tab (a, b, c) values (?, ?, ?)\"\n\ncur = conn.cursor()\n## ...
[ 3, 2 ]
[]
[]
[ "lastinsertid", "python", "sqlite" ]
stackoverflow_0008051439_lastinsertid_python_sqlite.txt
Q: why the use of an ORM with NoSql (like MongoDB) sorry, but does this make sense? the ORM means: Object Relational Mapper, and here, there is Relational, and NoSql is not RDBMS! so why the use of an ORM in a NoSql solution? because i see updates of ORMs for Python! A: Firstly, they are not ORM (since they don't h...
why the use of an ORM with NoSql (like MongoDB)
sorry, but does this make sense? the ORM means: Object Relational Mapper, and here, there is Relational, and NoSql is not RDBMS! so why the use of an ORM in a NoSql solution? because i see updates of ORMs for Python!
[ "Firstly, they are not ORM (since they don't have any relations among them), they are ODM (Object Document Mapper)\nMain usage of these ODM frameworks here same as the some common feature of ORM, thus \n\nproviding the abstraction over your data model. you can have your data modelled in your application irrespectiv...
[ 13, 3, 2 ]
[]
[]
[ "mongodb", "orm", "python" ]
stackoverflow_0008051614_mongodb_orm_python.txt
Q: Google app engine send mail raises ApplicationError: 1 Internal Error Years back I built a simple mail form that has been working like a champ, but in the last couple months the logs show I'm getting an error when EmailMessage's send() method gets called. I wrote a quick test to see if a stripped down version of a...
Google app engine send mail raises ApplicationError: 1 Internal Error
Years back I built a simple mail form that has been working like a champ, but in the last couple months the logs show I'm getting an error when EmailMessage's send() method gets called. I wrote a quick test to see if a stripped down version of an EmailMessage would work without error: class TestEmail(webapp.RequestHand...
[ "What is your appid?\nThere is currently an issue that sending mail from an application whose appid is the same as the owner's gmail name will fail. eg, I have a gmail address \"moishel at gmail dot com\"; if I created an app whose appid is 'moishel' (before version 1.6.0) it will fail when trying to send mail. Not...
[ 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0008045444_google_app_engine_python.txt
Q: Language best for a Photo-sharing site: PHP, Python, Ruby or something else? I plan to build a photo-sharing site like Flickr/Picasa for photographers, with features most suited for them. As you know, if that venture proves successful, many GB to TB of data transfers take place every day. This question is not just...
Language best for a Photo-sharing site: PHP, Python, Ruby or something else?
I plan to build a photo-sharing site like Flickr/Picasa for photographers, with features most suited for them. As you know, if that venture proves successful, many GB to TB of data transfers take place every day. This question is not just about scalability of my application as it grows, but also performance. I would li...
[ "Any. The language doesn't matter. Ruby-fanatics (especially the RubyOnRails sort) will try and tell you that their language will do everything in only 10 lines and it'll make you dinner and pick the kids up from school. Others will tell you that their language is the most secure, fastest, quickest to develop in, e...
[ 7, 2, 0 ]
[]
[]
[ "php", "python", "ruby", "scalability" ]
stackoverflow_0008051087_php_python_ruby_scalability.txt
Q: Loop until steady-state of a complex data structure in Python I have a more-or-less complex data structure (list of dictionaries of sets) on which I perform a bunch of operations in a loop until the data structure reaches a steady-state, ie. doesn't change anymore. The number of iterations it takes to perform the ...
Loop until steady-state of a complex data structure in Python
I have a more-or-less complex data structure (list of dictionaries of sets) on which I perform a bunch of operations in a loop until the data structure reaches a steady-state, ie. doesn't change anymore. The number of iterations it takes to perform the calculation varies wildly depending on the input. I'd like to know ...
[ "Take a look at python-deep. It should do what you want, and if it's not fast enough you can modify it yourself.\nIt also very much depends on how expensive the compare operation and how expensive one calculation iteration is. Say, one calculation iteration takes c time and one test takes t time and the chance of t...
[ 4, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0008051630_python.txt
Q: Remove data points below a curve with python I need to compare some theoretical data with real data in python. The theoretical data comes from resolving an equation. To improve the comparative I would like to remove data points that fall far from the theoretical curve. I mean, I want to remove the points below and...
Remove data points below a curve with python
I need to compare some theoretical data with real data in python. The theoretical data comes from resolving an equation. To improve the comparative I would like to remove data points that fall far from the theoretical curve. I mean, I want to remove the points below and above red dashed lines in the figure (made with m...
[ "This might be overkill and is based on your comment\n\nBoth the theoretical curves and the data points are arrays of\n different length.\n\nI would do the following:\n\nTruncate the data set so that its x values lie within the max and min values of the theoretical set.\nInterpolate the theoretical curve using sci...
[ 4, 4, 1, 0 ]
[]
[]
[ "matplotlib", "python", "scientific_computing", "scipy" ]
stackoverflow_0007958956_matplotlib_python_scientific_computing_scipy.txt
Q: Manual installation SciPy, NumPy, MatPlotlib (Windows) I want to install SciPy, NumPy and MatplotLib globally so that the libraries can be accessed from network computers. Basically it should be in some network drive without full installation of the libraries on each remote computer. Now I copied the site-package ...
Manual installation SciPy, NumPy, MatPlotlib (Windows)
I want to install SciPy, NumPy and MatplotLib globally so that the libraries can be accessed from network computers. Basically it should be in some network drive without full installation of the libraries on each remote computer. Now I copied the site-package directory from one working installation into the network dri...
[ "In the docs, see : http://docs.python.org/install/index.html\n\"Alternate installation: Windows (the prefix scheme)\"\n\"Modifying Python’s Search Path\"\n\"Custom Installation\"\n\nmay help you. \nThere is also the PYTHONHOME var used during install. \nBut frankly, I'm afraid you will not succeed doing this becau...
[ 1 ]
[]
[]
[ "matplotlib", "numpy", "python", "scipy", "windows" ]
stackoverflow_0008052002_matplotlib_numpy_python_scipy_windows.txt
Q: How can I create a Word document using Python? I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I programatically convert to a PDF file. However, my client is now reques...
How can I create a Word document using Python?
I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I programatically convert to a PDF file. However, my client is now requesting that the same document be made available in Wor...
[ "A couple ways you can create Word documents using Python:\n\nUse COM automation to create a document using the MS Word object model (using pywin32). http://python.net/crew/pirx/spam7/\nAutomate OpenOffice using Python: http://wiki.services.openoffice.org/wiki/Python\nIf rtf format is OK, use the PyRTF library: htt...
[ 39, 33, 2, 2, 0 ]
[]
[]
[ "ms_word", "python", "xml", "xslt" ]
stackoverflow_0001035183_ms_word_python_xml_xslt.txt