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: Least painful way to run a Python delay loop I've got an event-driven chatbot and I'm trying to implement spam protection. I want to silence a user who is behaving badly for a period of time, without blocking the rest of the application. Here's what doesn't work: if user_behaving_badly(): ban( user ) time.sle...
Least painful way to run a Python delay loop
I've got an event-driven chatbot and I'm trying to implement spam protection. I want to silence a user who is behaving badly for a period of time, without blocking the rest of the application. Here's what doesn't work: if user_behaving_badly(): ban( user ) time.sleep( penalty_duration ) # Bad! Blocks the entire a...
[ "instead of starting a thread for each ban, put the bans in a priority queue and have a single thread do the sleeping and unbanning\nthis code keeps two structures a heapq that allows it to quickly find the soonest ban to expire and a dict to make it possible to quickly check if a user is banned by name\nimport tim...
[ 5, 3, 3, 0, 0 ]
[]
[]
[ "multithreading", "python", "python_multithreading" ]
stackoverflow_0007775251_multithreading_python_python_multithreading.txt
Q: Add radio button to Tkinter My friend and I are working on making a window that displays 4 radio buttons, text and we are struggling to add two buttons on the bottom. Here is our code: from Tkinter import * import time class App: def __init__(self, master): frame = Frame(master) frame.pack(...
Add radio button to Tkinter
My friend and I are working on making a window that displays 4 radio buttons, text and we are struggling to add two buttons on the bottom. Here is our code: from Tkinter import * import time class App: def __init__(self, master): frame = Frame(master) frame.pack() v = IntVar() ...
[ "You need to actually initialize the App class in order for it to do anything. The label should go inside the init method along with all the other widgets. Normally you'd put all of the widgets inside the frame (e.g., Radiobutton(frame, text= ...), but if you aren't going to use the frame there's no need to creat...
[ 3, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0007775001_python_tkinter.txt
Q: Image not showing in for loop I am trying to display the image and name in a for loop on my template. This is what I have on my template for loop, and I thought it should work, but it doesn't {% for op in tracked_objects %} {% if op.is_mine %} <div style="float:left;"> <div> ...
Image not showing in for loop
I am trying to display the image and name in a for loop on my template. This is what I have on my template for loop, and I thought it should work, but it doesn't {% for op in tracked_objects %} {% if op.is_mine %} <div style="float:left;"> <div> <img src="{{ op.t...
[ "Try:\n<img src=\"{{ op.tracked_object.image.url }}\" alt=\"\">\n\n", "See Using django.contrib.staticfiles.\n" ]
[ 5, 0 ]
[]
[]
[ "django", "django_models", "django_templates", "django_views", "python" ]
stackoverflow_0007770261_django_django_models_django_templates_django_views_python.txt
Q: Python26, Win32, ZBar - ImportError: DLL load failed I am using Python 2.6 (x86) and tried to install the ZBar module. I downloaded the current version of ZBar (Win32-Installer): http://zbar.sourceforge.net/download.html and the current version of the module on PyPi: http://pypi.python.org/pypi/zbar ZBar (prompt a...
Python26, Win32, ZBar - ImportError: DLL load failed
I am using Python 2.6 (x86) and tried to install the ZBar module. I downloaded the current version of ZBar (Win32-Installer): http://zbar.sourceforge.net/download.html and the current version of the module on PyPi: http://pypi.python.org/pypi/zbar ZBar (prompt and webcam) works fine but as soon as I try to import zbar ...
[ "Add the path to libzbar-0.dll to your system PATH so Windows can find it when zbar.pyd is loaded.\nEdit: I installed the application and Python library. Here's how to make it work without changing your PATH through the control panel system configuration:\n>>> zbar_path = os.path.join(os.environ['ProgramFiles'], 'z...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0007775339_python.txt
Q: Python/Anything - Alter lines from text file, Randomize, Then save on specific line This is a bit of a an odd question but I'll make it out the best I can. I'm in the works on writing a script with the use of proxies, but I ran in to a problem automating part of it, which sucks as it's the last part of everything ...
Python/Anything - Alter lines from text file, Randomize, Then save on specific line
This is a bit of a an odd question but I'll make it out the best I can. I'm in the works on writing a script with the use of proxies, but I ran in to a problem automating part of it, which sucks as it's the last part of everything that I need then I'm done. Example: Lets say I have a list of 200 or so proxies in this f...
[ "Creating the list is simple enough:\nfrom random import sample\n\nwith open(\"proxy_list.txt\") as proxy_file:\n proxies = [proxy.strip() for proxy in proxy_file.readlines()]\n\n proxies = sample(proxies, min(len(proxies), 99))\n\n proxy_str = \"|\".join(proxies)\n\nThen you must use a templating language...
[ 1 ]
[]
[]
[ "programming_languages", "proxies", "proxy", "python", "random" ]
stackoverflow_0007775625_programming_languages_proxies_proxy_python_random.txt
Q: Python3: option parser, check if a boolean option has been set I want to a true/false option (-w) to my program. If the option is set, I will be sorting the output. I have the following option added: parser.add_option("-w", "--without-replacement", action="store_true", dest="replacement", default...
Python3: option parser, check if a boolean option has been set
I want to a true/false option (-w) to my program. If the option is set, I will be sorting the output. I have the following option added: parser.add_option("-w", "--without-replacement", action="store_true", dest="replacement", default=False, help="outpt lines without replacement") r...
[ "The syntax error is because you forgot the colon after 'if replacement'.\nYou have to actually invoke the parser before the options will be available:\noptions = parser.parse_args()\n\nIf you are trying to remove duplicates in the for loop at the end, try this:\nif replacement and self.lines:\n self.lines = lis...
[ 4, 2 ]
[]
[]
[ "python", "python_2.x", "python_3.x" ]
stackoverflow_0007776048_python_python_2.x_python_3.x.txt
Q: Optional Parameters in Python with List Append Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument This is very odd, an optional list parameter in Python is persistent between function calls when using the .append() method. def wtf(some, thing, fields=[]): print fields if len...
Optional Parameters in Python with List Append
Possible Duplicate: “Least Astonishment” in Python: The Mutable Default Argument This is very odd, an optional list parameter in Python is persistent between function calls when using the .append() method. def wtf(some, thing, fields=[]): print fields if len(fields) == 0: fields.append('hey'); pr...
[ "Default values are only evaluated once, so using a mutable type as a default value will produce unexpected results. You'd do better to do something like this:\ndef wtf(some, thing, fields = None):\n if fields is None:\n fields = []\n\n" ]
[ 3 ]
[]
[]
[ "optional_parameters", "python" ]
stackoverflow_0007776142_optional_parameters_python.txt
Q: Bi-directional RPC options for cross-language client/server I'm trying to lay out an idea for a project, where a client-side GUI can be developed in python, and the GUI can be driven by a backend in potentially any other language, over RPC. More specifically, right now I am working with PyQt on the client side, an...
Bi-directional RPC options for cross-language client/server
I'm trying to lay out an idea for a project, where a client-side GUI can be developed in python, and the GUI can be driven by a backend in potentially any other language, over RPC. More specifically, right now I am working with PyQt on the client side, and Go as the initial backend. Here are my goals: PyQt client R...
[ "On the network when you connect to a server via TCP (or any other similar connection based protocol), when connecting your PC already chooses and listens on a (pseudo/relatively) random port in order to receive the servers answers. So for that matter, as long as the server keeps the connection and both sides keep ...
[ 2 ]
[]
[]
[ "client_server", "go", "language_agnostic", "python", "rpc" ]
stackoverflow_0007774959_client_server_go_language_agnostic_python_rpc.txt
Q: pygtk textview tab width? Is there a way to set the tab width of the pygtk TextView widget to be something other than 8spaces? Right now I tried textview.set_tabs(pango.TabArray(4, False)) However, it seems like I misunderstood the docs. What the actual way to do it? Thanks A: See the docs for pango.TabArray: yo...
pygtk textview tab width?
Is there a way to set the tab width of the pygtk TextView widget to be something other than 8spaces? Right now I tried textview.set_tabs(pango.TabArray(4, False)) However, it seems like I misunderstood the docs. What the actual way to do it? Thanks
[ "See the docs for pango.TabArray: your statement pango.Tabarray(4, False) creates a tab array with four tab stops, all at position 0 points. What you want is this:\ntabs = pango.TabArray(1, True)\ntabs.set_tab(0, pango.TAB_LEFT, desired_tab_width)\ntextview.set_tab(tabs)\n\nThe value of desired_tab_width is not in ...
[ 3 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0007774688_gtk_pygtk_python.txt
Q: How to eliminate html tags? I am getting the first paragraph from pages and trying to extract words suitable to be tags or keywords. In some paragraphs there are links and I want to remove the tags: For instance if the text is A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte" enter code heretitle="By...
How to eliminate html tags?
I am getting the first paragraph from pages and trying to extract words suitable to be tags or keywords. In some paragraphs there are links and I want to remove the tags: For instance if the text is A <b>hex triplet</b> is a six-digit, three-<a href="/wiki/Byte" enter code heretitle="Byte">byte</a> ... I want to remov...
[ "Beautiful Soup is the answer to your problem! Try it out, it's pretty awesome!\nHtml parsing would become so easy once you use it.\n>>> text = \"\"\"A <b>hex triplet</b> is a six-digit, three-<a href=\"/wiki/Byte\"\n... enter code heretitle=\"Byte\">byte</a> ...\"\"\"\n>>> soup = BeautifulSoup(text)\n>>> ''.join(s...
[ 3, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007775800_python_regex.txt
Q: getting python priority queue return item of largest priority I am using Queue.Priority class in python 2.7 as below q=Queue.PriorityQueue() q.put((2,"second")) q.put((1,"first")) q.put((3,"third")) print q.get(True) print q.get(True) print q.get(True) This would return the following result since get() returns th...
getting python priority queue return item of largest priority
I am using Queue.Priority class in python 2.7 as below q=Queue.PriorityQueue() q.put((2,"second")) q.put((1,"first")) q.put((3,"third")) print q.get(True) print q.get(True) print q.get(True) This would return the following result since get() returns the item of lowest priority (1, 'first') (2, 'second') (3, 'third') ...
[ "If it's just the first element of the tuple that matters, and it's an integer, you could simply negate it:\nq=Queue.PriorityQueue()\nq.put((-2,\"second\"))\nq.put((-1,\"first\"))\nq.put((-3,\"third\"))\nprint q.get(True)\nprint q.get(True)\nprint q.get(True)\n\nThis will print out:\n(-3, 'third') \n(-2, 'second')\...
[ 3 ]
[]
[]
[ "priority_queue", "python" ]
stackoverflow_0007776406_priority_queue_python.txt
Q: porting Python 2 syntax to Python 3 I'm trying to run the following code in python3, but it has been written for I'm pretty sure python2: f = open(filename, 'r') self.lines = f.readlines() f.close() if self.lines[-1] != "\n" : self.lines.append("\n") But I'm getting the following error: File "randline.py", ...
porting Python 2 syntax to Python 3
I'm trying to run the following code in python3, but it has been written for I'm pretty sure python2: f = open(filename, 'r') self.lines = f.readlines() f.close() if self.lines[-1] != "\n" : self.lines.append("\n") But I'm getting the following error: File "randline.py", line 32 if self.lines[-1] != "\n" : ...
[ "Python 2 allows you to mix spaces and tabs. so you can have indentation like:\ndef foo():\n[this is a tab it counts like eight spaces ]for each in range(5):\n[this is a tab it counts like eight spaces ][space][space]print(each)\n[space][space][space][space][space][space][space][space]print(...
[ 6 ]
[]
[]
[ "python", "python_2.x", "python_3.x" ]
stackoverflow_0007775478_python_python_2.x_python_3.x.txt
Q: python precautions to economize on size of text file of purely numerical characters I am tabulating a lot of output from some network analysis, listing an edge per line, which results in dozens of gigabytes, stretching the limits of my resources (understatement). As I only deal with numerical values, it occurred t...
python precautions to economize on size of text file of purely numerical characters
I am tabulating a lot of output from some network analysis, listing an edge per line, which results in dozens of gigabytes, stretching the limits of my resources (understatement). As I only deal with numerical values, it occurred to me that I might be smarter than using the Py3k defaults. I.e. some other character enco...
[ "You can use zlib or gzip to compress the data as you generate it. You won't need to change your format at all, the compression will adjust to the characters and sequences that you use the most to create an optimal file size. \n", "Avoid the character encodings entirely and save your data in a binary format. See...
[ 6, 3, 2, 0 ]
[]
[]
[ "character_encoding", "io", "performance", "python", "python_3.x" ]
stackoverflow_0007575329_character_encoding_io_performance_python_python_3.x.txt
Q: Python - Opening multiple SSH within (inside) eachother Here is what I want to do : SSH to server 1 inside server 1, SSH to server 2 inside server 2, SSH to server 3 inside server 3, run a single command ( like mysql ) inside mysql console, run another command. then exit all the way to server 1 Is it possible to...
Python - Opening multiple SSH within (inside) eachother
Here is what I want to do : SSH to server 1 inside server 1, SSH to server 2 inside server 2, SSH to server 3 inside server 3, run a single command ( like mysql ) inside mysql console, run another command. then exit all the way to server 1 Is it possible to do a procedure like this ? If yes, then how ?
[ "It is possible: Just execute ssh (or a corresponding Python program you upload first) on each new hop, and when you finally reach the target, execute mysql.\nHowever, it's not advisable: You should never enter passwords (or worse, store private keys) for one server on another server. That means that if server 1 is...
[ 0 ]
[]
[]
[ "python", "ssh" ]
stackoverflow_0007776755_python_ssh.txt
Q: Read txt file with multi-threaded in python I'm trying to read a file in python (scan it lines and look for terms) and write the results- let say, counters for each term. I need to do that for a big amount of files (more than 3000). Is it possible to do that multi threaded? If yes, how? So, the scenario is like th...
Read txt file with multi-threaded in python
I'm trying to read a file in python (scan it lines and look for terms) and write the results- let say, counters for each term. I need to do that for a big amount of files (more than 3000). Is it possible to do that multi threaded? If yes, how? So, the scenario is like this: Read each file and scan its lines Write coun...
[ "I agree with @aix, multiprocessing is definitely the way to go. Regardless you will be i/o bound -- you can only read so fast, no matter how many parallel processes you have running. But there can easily be some speedup. \nConsider the following (input/ is a directory that contains several .txt files from Project ...
[ 23, 1 ]
[]
[]
[ "multithreading", "python", "text_files" ]
stackoverflow_0007776293_multithreading_python_text_files.txt
Q: Python and Scipy programming I'm getting this error message: Traceback (most recent call last): File "C:/Python27/test", line 14, in <module> tck = interpolate.bisplrep(X,Y,Z) File "C:\Python27\lib\site-packages\scipy\interpolate\fitpack.py", line 850, in bisplrep raise TypeError('m >= (kx+1)(ky+1) mus...
Python and Scipy programming
I'm getting this error message: Traceback (most recent call last): File "C:/Python27/test", line 14, in <module> tck = interpolate.bisplrep(X,Y,Z) File "C:\Python27\lib\site-packages\scipy\interpolate\fitpack.py", line 850, in bisplrep raise TypeError('m >= (kx+1)(ky+1) must hold') TypeError: m >= (kx+1)(ky...
[ "Have you read the documentation?\nIf you don't specify kx and ky, default values will be 3:\nscipy.interpolate.bisplrep(x, y, z, w=None, xb=None, xe=None, yb=None, ye=None, \n kx=3, ky=3, task=0, s=None, eps=1e-16, tx=None, ty=None,\n full_output=0, nxest=None, n...
[ 5 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0007776396_python_scipy.txt
Q: Extracting values from text file I have one text file as follows with 2 columns 44333373 -5.829738285 3007762 -5.468521083 16756295 -5.247183569 46197456 -5.216096421 46884567 -5.195179321 44333390 -5.162411562 44420579 -5.133122186 6439190 -5.028260409 ... I want to extract values which...
Extracting values from text file
I have one text file as follows with 2 columns 44333373 -5.829738285 3007762 -5.468521083 16756295 -5.247183569 46197456 -5.216096421 46884567 -5.195179321 44333390 -5.162411562 44420579 -5.133122186 6439190 -5.028260409 ... I want to extract values which greater than -5.162411562 ideal outpu...
[ "Well, you need to actually set n to a value aside from zero. How about:\nwith open('file.txt') as f1:\n for line in f1: # readlines is not necessary here\n n = float(line.split()[1]) # line.split()[0] is the first number\n if n > -5.162411562:\n print (line.rstrip('\\r\\n')) # rstrip to remove the ex...
[ 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007777177_python.txt
Q: Bash redirection encoding error I'm redirecting the stdio of a server written in Python to a file: python server.py &> file The input is transmitted via a client.py which uses the XMLRPC library. If I transmit UTF-8 input, I get a UnicodeEncodeError before I can do anything. The curiosity here is: If I don't redi...
Bash redirection encoding error
I'm redirecting the stdio of a server written in Python to a file: python server.py &> file The input is transmitted via a client.py which uses the XMLRPC library. If I transmit UTF-8 input, I get a UnicodeEncodeError before I can do anything. The curiosity here is: If I don't redirect the stdoutput of the server.py, ...
[ "The Python code is irrelevant and I won't modify the SimpleXMLRPCServer module. It is Bash related:\nThe file created by redirection is us-ascii and only becomes utf-8 once a unicode character is inserted which won't work in this case since it is processed by the XMLRPC module first and hence the UnicodeDecodeErro...
[ 0 ]
[]
[]
[ "bash", "encoding", "python", "redirect" ]
stackoverflow_0007753119_bash_encoding_python_redirect.txt
Q: How to specify where to place buildout bootstrap generated folders? I have the following folder structure: bootstrap.py setup.py conf/ buildout.cfg Now how do I make it so that running python bootstrap.py puts the generated folders bin, eggs, parts, etc. on the root instead of under conf folder? A: The base...
How to specify where to place buildout bootstrap generated folders?
I have the following folder structure: bootstrap.py setup.py conf/ buildout.cfg Now how do I make it so that running python bootstrap.py puts the generated folders bin, eggs, parts, etc. on the root instead of under conf folder?
[ "The base directory for buildout is always the directory that the starting configuration file is found in, so in your case that's in conf/.\nThere are two work-arounds for this, one easy, one harder. The first is to just place a bare buildout.cfg file in the root, and have it include the file in conf/:\n[buildout]\...
[ 4, 1 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0007776498_buildout_python.txt
Q: How to post a file with telnet or a raw socket? I'm trying to post a file within a raw socket, I read the RFC, and I think I actually tested a lot of options but I'm now stuck. By the way, I know I could use pycurl, httplib, etc., but I really want to do it manualy. Here the request: POST /upload.php?foo=bar HTTP/...
How to post a file with telnet or a raw socket?
I'm trying to post a file within a raw socket, I read the RFC, and I think I actually tested a lot of options but I'm now stuck. By the way, I know I could use pycurl, httplib, etc., but I really want to do it manualy. Here the request: POST /upload.php?foo=bar HTTP/1.0 Host: localhost User-Agent: Mozilla/5.0 Content-T...
[ "Shouldnt there be a 'Content-Length' in the part-headers?\n", "Since you already figured out the header you will use, I recommend putting it into\na multiline string like this:\n# An infinitely clever way to make \\r\\n\\r\\n at end of header, although technically\n# inferior to just going rnrn = '\\r\\n\\r\\n' ...
[ 1, 1, 0 ]
[]
[]
[ "file_upload", "http_post", "python", "sockets" ]
stackoverflow_0005947367_file_upload_http_post_python_sockets.txt
Q: python how to parse "user:12345 location:ny search" I want python to parse string ""user:12345 location:ny search" Then I can use: if "user" in string: .... if "location" in string: ... Any existing way to do this? A: Although the original version of unutbu's answer was impressive, now re seems a bit overkill....
python how to parse "user:12345 location:ny search"
I want python to parse string ""user:12345 location:ny search" Then I can use: if "user" in string: .... if "location" in string: ... Any existing way to do this?
[ "Although the original version of unutbu's answer was impressive, now re seems a bit overkill. Here is a simpler one:\n>>> text = 'user:12345 location:ny search'\n>>> dict(pair.split(\":\") for pair in text.split() if \":\" in pair)\n{'user': '12345', 'location': 'ny'}\n\nEdit:\nTo insert \"search\" with key \"keyw...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007777733_python.txt
Q: Python on windows - conhost.exe CPU usage I'm running a Python script on Windows, and I've noticed that even though the Python process takes ~8% CPU, the associated conhost.exe process takes ~14%. Why is this so? How come such a large part of the CPU consumption is in the conhost and not in the Python process? Is ...
Python on windows - conhost.exe CPU usage
I'm running a Python script on Windows, and I've noticed that even though the Python process takes ~8% CPU, the associated conhost.exe process takes ~14%. Why is this so? How come such a large part of the CPU consumption is in the conhost and not in the Python process? Is there a way to reduce this CPU consumption? (be...
[ "Since we don't know what your program is doing we have to guess a little. So long as there is no I/O I'd expect conhost to consume 0% CPU. So I hypothesise that you are printing a lot of text to the console. For example, the following program has the same symptoms as you report:\nwhile True:\n print \"Hello wo...
[ 3 ]
[]
[]
[ "cpu_usage", "python", "windows", "windows_console" ]
stackoverflow_0007769870_cpu_usage_python_windows_windows_console.txt
Q: Parsing html with lxml on python I have following html code: <div class="test"> "Test" <br> <script type="text/javascript"></script> <a href="mailto:asdf@adsf.com">asdf@adsf.com</a> " " </div> How to get the email address from this code using lxml? A: import lxml.html as LH text='''\ <div c...
Parsing html with lxml on python
I have following html code: <div class="test"> "Test" <br> <script type="text/javascript"></script> <a href="mailto:asdf@adsf.com">asdf@adsf.com</a> " " </div> How to get the email address from this code using lxml?
[ "import lxml.html as LH\ntext='''\\\n<div class=\"test\">\n \"Test\"\n <br>\n <script type=\"text/javascript\"></script>\n <a href=\"mailto:asdf@adsf.com\">asdf@adsf.com</a> \n \" \"\n</div>\n'''\n\ndoc=LH.fromstring(text)\nprint(doc.xpath('//a[starts-with(@href,\"mailto:\")]/text()')[0])\n# asdf@ads...
[ 4 ]
[]
[]
[ "html_parsing", "lxml", "python" ]
stackoverflow_0007778128_html_parsing_lxml_python.txt
Q: Python open() raises an error if I try to create a file I'm having a problem with Python 2.6 on windows. Whether I try: fileobj=open("nonexistent.txt","w") or fil=os.open("nonexistent.txt", os.O_CREAT) fileobj=file(fil) I get an error: IOError: [Errno 2] No such file or directory: 'nonexistent.txt' What may be...
Python open() raises an error if I try to create a file
I'm having a problem with Python 2.6 on windows. Whether I try: fileobj=open("nonexistent.txt","w") or fil=os.open("nonexistent.txt", os.O_CREAT) fileobj=file(fil) I get an error: IOError: [Errno 2] No such file or directory: 'nonexistent.txt' What may be the problem?
[ "You will not be able to read the file if it does not exist, however, you should be able to write to it. Does the code below return the same error?\nf=open(\"nonexistent.txt\",\"w\")\nf.write('Test')\nf.close()\n\n" ]
[ -1 ]
[ "At seems like a permission problem.\nTry opening the file somewhere else or run the python as an Administrator.\n" ]
[ -1 ]
[ "file", "io", "python" ]
stackoverflow_0007778255_file_io_python.txt
Q: Is There '?' Control Flow in Python? Possible Duplicate: Python Ternary Operator Is there control flow operator similar to '?' of C/C++ in python? If there is a chunk of code similar to this: return n <= 1 ? n : fibo(n-1) + fibo(n-2) Will got an error like this: File "fibonacci.py", line 2 return n <= 1 ? n...
Is There '?' Control Flow in Python?
Possible Duplicate: Python Ternary Operator Is there control flow operator similar to '?' of C/C++ in python? If there is a chunk of code similar to this: return n <= 1 ? n : fibo(n-1) + fibo(n-2) Will got an error like this: File "fibonacci.py", line 2 return n <= 1 ? n : fibo(n-1) + fibo(n-2) ...
[ "Yes, the conditional expression is available in Python 2.5+:\nreturn n if n <= 1 else fibo(n-1) + fibo(n-2)\n\n", "You can try this short circuit expression return n > 1 and fibo(n-1) + fibo(n-2) or n. While this is not the ternary statement, it is concise and does the job in this scenario.\n" ]
[ 12, 5 ]
[]
[]
[ "python", "ternary_operator" ]
stackoverflow_0007778400_python_ternary_operator.txt
Q: Time and date on the basis of seconds elapsed since 1970 year Using python I have to retrieve value of time and date of an event knowing how many seconds elapsed since 01/01/1970 00:00:00. I started with: from datetime import timedelta a = timedelta(seconds=1317365200) print "%d days %02d:%02d:%02d" % (a.days, a....
Time and date on the basis of seconds elapsed since 1970 year
Using python I have to retrieve value of time and date of an event knowing how many seconds elapsed since 01/01/1970 00:00:00. I started with: from datetime import timedelta a = timedelta(seconds=1317365200) print "%d days %02d:%02d:%02d" % (a.days, a.seconds / 3600, (a.seconds / 60) % 60, a.seconds % 60)1317365200 R...
[ "from datetime import datetime\na = datetime.fromtimestamp(1317365200)\nprint a\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007778460_python.txt
Q: Converting flat Python Dictionary to List of Dictionaries I have a dictionary in the following format where I don't know the number of lines or items I'm going to receive: {'line(0).item1':'a', 'line(0).item2':'34', 'line(1).item1':'sd', 'line(1).item2':'2', 'line(1).item3':'fg', 'line(2).item1':'f' ... } Wha...
Converting flat Python Dictionary to List of Dictionaries
I have a dictionary in the following format where I don't know the number of lines or items I'm going to receive: {'line(0).item1':'a', 'line(0).item2':'34', 'line(1).item1':'sd', 'line(1).item2':'2', 'line(1).item3':'fg', 'line(2).item1':'f' ... } What is the most pythonic way to parse this into a list of diction...
[ "d = {'line(0).item1':'a' ...}\n\nout = collections.defaultdict(list)\nfor k,v in d.items():\n n,val = re.findall(r'^line\\((\\d+)\\)\\.(\\w+)$', k)[0]\n out[int(n)].append((val,v))\n\nmy_list = [dict(out[v]) for v in sorted(out)]\n\nand the output will be the expected:\n[{'item2': '34', 'item1': 'a'}, {'item...
[ 5, 0 ]
[]
[]
[ "dictionary", "loops", "python" ]
stackoverflow_0007778465_dictionary_loops_python.txt
Q: How to make my welcome text appear? After login, I want the text "Welcome, Niklas" to display but after logging in I have to reload the page and I didn't understand how to make the page display the text from the server variable current_user. If I login and press reload then the correct welcome message appears. Can...
How to make my welcome text appear?
After login, I want the text "Welcome, Niklas" to display but after logging in I have to reload the page and I didn't understand how to make the page display the text from the server variable current_user. If I login and press reload then the correct welcome message appears. Can you help me achieve what I want? Why is ...
[ "When using Oauth 2.0 \nFB.Init(...oauth=true) \n\nthe login button is setting a cookie into your domain named \nfbsr_(appid)=....\n\nwhich is encoded using the app secret key, and which do not contain the user token anymore.\nIf you really want to avoid the use of java script client side (which is the most simple ...
[ 2 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0007775320_facebook_python.txt
Q: How to capture first line from XML response in Python? I am receiving an XML response from an API in a variable r so that: print r.read() displays the entire XML response. I need to take the first line of this response and convert it to a string variable for use in a loop after some substringing. What is the bes...
How to capture first line from XML response in Python?
I am receiving an XML response from an API in a variable r so that: print r.read() displays the entire XML response. I need to take the first line of this response and convert it to a string variable for use in a loop after some substringing. What is the best way to capture just the first line?
[ "r.readline()\nBuilt-in Types - File Objects:\n\nfile.readline([size])\n Read one entire line from the file. A trailing\n newline character is kept in the string (but may be absent when a file\n ends with an incomplete line). If the size argument is present and\n non-negative, it is a maximum byte count (includ...
[ 4 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0007778809_python_xml.txt
Q: Updating models to reflect changes to other models I'm developing a system where users will need to match model fields from several models. To assist them, I've created an "is_orphan" Boolean field to indicate whether the required relationship (ForeignKey, in this case) should exist but doesn't yet. It is update...
Updating models to reflect changes to other models
I'm developing a system where users will need to match model fields from several models. To assist them, I've created an "is_orphan" Boolean field to indicate whether the required relationship (ForeignKey, in this case) should exist but doesn't yet. It is updated as part of the save routine - example below: class Cap...
[ "In the save method of Art model:\ndef save(self, *args, **kwargs):\n old_caption = None\n if self.id:\n old_caption = Art.objects.get(id=self.id).caption\n super(Art, self).save(*args, **kwargs)\n if old_caption and (self.caption != old_caption):\n if old_caption.art_set.all():\n ...
[ 0 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0007778602_django_django_admin_django_models_python.txt
Q: Python - getattr and concatenation So in playing around with getattr in my code I discovered the following: myVariable = foo.A.bar works...but something like this: B = "A" myVariable = getattr(foo, B + ".bar") returns an error that foo does not contain an attribute A.bar. Where am I going wrong? Thanks! A: B...
Python - getattr and concatenation
So in playing around with getattr in my code I discovered the following: myVariable = foo.A.bar works...but something like this: B = "A" myVariable = getattr(foo, B + ".bar") returns an error that foo does not contain an attribute A.bar. Where am I going wrong? Thanks!
[ "Because there is no attribute A.bar on foo. Attribute bar is a part of the object pointed to by A, which is an attribute of foo. You need either\ngetattr(foo.A, \"bar\")\n\nor\ngetattr(getattr(foo, 'A'), 'bar')\n\nThe generic code for accessing deep attributes is to split on the dot, and go until the last part is ...
[ 12, 2 ]
[]
[]
[ "getattr", "python" ]
stackoverflow_0007778867_getattr_python.txt
Q: Error With AlchemyAPI Python SDK I am trying to use AlchemyAPI Python 0.7 SDK. However when ever I run a method within it e.g. URLGetText(url); I get this error: nodes = etree.fromstring(result).xpath(xpathQuery) File "lxml.etree.pyx", line 2743, in lxml.etree.fromstring (src/lxml/lxml.etree.c:52665) File ...
Error With AlchemyAPI Python SDK
I am trying to use AlchemyAPI Python 0.7 SDK. However when ever I run a method within it e.g. URLGetText(url); I get this error: nodes = etree.fromstring(result).xpath(xpathQuery) File "lxml.etree.pyx", line 2743, in lxml.etree.fromstring (src/lxml/lxml.etree.c:52665) File "parser.pxi", line 1573, in lxml.etree...
[ "I looked at the Python urllib docs, and found this page:\nhttp://docs.python.org/library/urllib.html#high-level-interface\nwhich contains this warning about the filehandle object returned by urllib.urlopen():\n\nOne caveat: the read() method, if the size argument is omitted or negative, may not read until the end ...
[ 0 ]
[]
[]
[ "alchemyapi", "lxml", "python" ]
stackoverflow_0007778733_alchemyapi_lxml_python.txt
Q: python: changing object class in multi-level inheritance I have looked at many questions posted here to find an answer to my problem, but I wasn't successful. The problem might be, that I just don't know for what keywords I should look. So my problem is the following: I've got a program, that has a multi-level inh...
python: changing object class in multi-level inheritance
I have looked at many questions posted here to find an answer to my problem, but I wasn't successful. The problem might be, that I just don't know for what keywords I should look. So my problem is the following: I've got a program, that has a multi-level inheritance and I am trying to figure out how the best way would ...
[ "What you want is a factory: a function that opens the file, reads the stuff it needs to read to figure out what kind of file it is, and then initializes and returns an object of the appropriate class.\nIf you want to keep it a class, you'd want to override __new__() and then return an object of the desired class i...
[ 3, 1 ]
[]
[]
[ "class", "multiple_inheritance", "python" ]
stackoverflow_0007778764_class_multiple_inheritance_python.txt
Q: How can i determine the exact size of a type used by python >>> sys.getsizeof(int) 436 #? does this mean int occupies 436 bytes . >>> sys.getsizeof(1) 12 #12 bytes for int object, is this the memory requirement. I thought int in python is represented by 4 bytes, why is it reporting 12 bytes Please someone expla...
How can i determine the exact size of a type used by python
>>> sys.getsizeof(int) 436 #? does this mean int occupies 436 bytes . >>> sys.getsizeof(1) 12 #12 bytes for int object, is this the memory requirement. I thought int in python is represented by 4 bytes, why is it reporting 12 bytes Please someone explain why is it reporting 12 bytes when int uses just 4 bytes
[ "Yes, an int instance takes up 12 bytes on your system. Integers (like any object) have attributes, i.e. pointers to other objects, which take up additional memory space beyond that used by the object's own value. So 4 bytes for the integer's value, 4 bytes for a pointer to __class__ (otherwise, Python wouldn't kno...
[ 10, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007779207_python.txt
Q: Generator which leaves a placeholder at the beginning and at the end of the input iterator intact Let's take a list as an example: a = [255, 255, 1, 255, 255, 255, 1, 2, 255, 255, 2, 255, 255, 3, 255, 3, 255, 255, 255] 255 is a special value in it. It's a placeholder. I've made a generator which replaces some of ...
Generator which leaves a placeholder at the beginning and at the end of the input iterator intact
Let's take a list as an example: a = [255, 255, 1, 255, 255, 255, 1, 2, 255, 255, 2, 255, 255, 3, 255, 3, 255, 255, 255] 255 is a special value in it. It's a placeholder. I've made a generator which replaces some of the placeholder inside the list. It works as expected. But I need not to process the beginning placehol...
[ "def replace(it, process, placeholder):\n it = iter(it)\n while True:\n item = it.next()\n if item == placeholder:\n yield item\n else:\n yield process(item)\n pcount = 0\n try:\n while True:\n item = it.next()\n if item == placehol...
[ 2, 0, 0 ]
[]
[]
[ "functional_programming", "python", "python_itertools" ]
stackoverflow_0007755227_functional_programming_python_python_itertools.txt
Q: how to fill the start and the end of a unique entry with the same value in numpy array? i have a 1D numpy array. Lets look at the following example a = [255,1,255,255,1,255,255,255,2,2,255,255,255,2,2,3,255,255,255,3] In the above array the unique entries are considered except the value which is 255. We want to f...
how to fill the start and the end of a unique entry with the same value in numpy array?
i have a 1D numpy array. Lets look at the following example a = [255,1,255,255,1,255,255,255,2,2,255,255,255,2,2,3,255,255,255,3] In the above array the unique entries are considered except the value which is 255. We want to fill values between each unique entry. the resultant will look like [255,1,1,1,1,255,255,255,...
[ "I used groupby function from itertools module.\nAlso I used window function from here.\nfrom __future__ import print_function\nfrom itertools import tee, izip, groupby\n\na = [255,1,255,255,1,255,255,255,2,2,255,255,255,2,2,3,255,255,255,3]\n\ndef groupby2(iterable):\n '''Used to convert to the second iterable...
[ 1, 1, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007745367_numpy_python.txt
Q: NLP project, python or C++ We are working on Arabic Natural Language Processing project, we have limited our choices to either write the code in Python or C++ (and Boost library). We are thinking of these points: Python Slower than C++ (There is ongoing work to make Python faster) Better UTF8 support Faster in w...
NLP project, python or C++
We are working on Arabic Natural Language Processing project, we have limited our choices to either write the code in Python or C++ (and Boost library). We are thinking of these points: Python Slower than C++ (There is ongoing work to make Python faster) Better UTF8 support Faster in writing tests and trying differen...
[ "Although this is subjective and argumentative, there is evidence that you can write a successful NLP project in python like NLTK. They also have a comparison of NLP functionality in different languages: \n\n(Quoting from the comparison)\nMany programming languages have been used for NLP. As explained in the Prefac...
[ 9, 8, 3, 2, 0 ]
[]
[]
[ "boost", "c++", "nlp", "python" ]
stackoverflow_0002344081_boost_c++_nlp_python.txt
Q: Stop running tests if setUp raises an exception in Python unittest I have this test class: class mytest(unittest.TestCase): def setUp(self): os.mkdir(...) ... def tearDown(self): shutil.rmtree(...) def test_one(self): ... def test_two(self): ... If someth...
Stop running tests if setUp raises an exception in Python unittest
I have this test class: class mytest(unittest.TestCase): def setUp(self): os.mkdir(...) ... def tearDown(self): shutil.rmtree(...) def test_one(self): ... def test_two(self): ... If something fails after mkdir has ran when running setUp of test_one, it will st...
[ "Add a failure call in the setUp method.\ndef setUp(self):\n try:\n somethingThatMightFail()\n except:\n self.fail()\n\n" ]
[ 13 ]
[]
[]
[ "python", "testing" ]
stackoverflow_0007779434_python_testing.txt
Q: BeautifulSoup error in Python's Mechanize I installed BeautifulSoup on my Mac using easy_install with no errors, And I can run the test.py file perfectly with no errors also. But when I try to use BeautifulSoup in another file, I get the error: Traceback (most recent call last): File "/Users/Conor/Desktop/test.p...
BeautifulSoup error in Python's Mechanize
I installed BeautifulSoup on my Mac using easy_install with no errors, And I can run the test.py file perfectly with no errors also. But when I try to use BeautifulSoup in another file, I get the error: Traceback (most recent call last): File "/Users/Conor/Desktop/test.py", line 54, in <module> from BeautifulSoup...
[ "Did you install using sudo? It's odd that any easy_install module would end up in /Documents. (And it's odd that you have a Documents directory below the /Users level.)\nOn OS X (10.7.1) and I installed and used BeautifulSoup with no errors.\n$ sudo pip install BeautifulSoup\n$ python\n>>>import BeautifulSoup\n>...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "macos", "mechanize", "python" ]
stackoverflow_0007777219_beautifulsoup_macos_mechanize_python.txt
Q: Python Celery Save Results in Database Asynchronously I'm using Python with Celery and RabbitMQ to make a web spider to count the number of links on a page. Can a database, such as MySQL, be written into asynchronously? Is it OK to commit the changes after every row added, or is it required to batch them (multi-a...
Python Celery Save Results in Database Asynchronously
I'm using Python with Celery and RabbitMQ to make a web spider to count the number of links on a page. Can a database, such as MySQL, be written into asynchronously? Is it OK to commit the changes after every row added, or is it required to batch them (multi-add) and then commit after a certain number of rows/duration...
[ "For write intensive operation like Counters and Logs NoSQL solution are always the best choice. Personally I use a mongoDB for this kind of tasks.\n" ]
[ 1 ]
[]
[]
[ "asynchronous", "celery", "database", "python", "rabbitmq" ]
stackoverflow_0007659246_asynchronous_celery_database_python_rabbitmq.txt
Q: How to structure my application for several tasks using redis with gevent or threading in Python I have a process which sends financial tick data through redis pubsub in realtime. Now I want my Python Application to handle the input data (json) for instance calculations like moving average and so on. the results I...
How to structure my application for several tasks using redis with gevent or threading in Python
I have a process which sends financial tick data through redis pubsub in realtime. Now I want my Python Application to handle the input data (json) for instance calculations like moving average and so on. the results I want to be send back via redis to other tasks (doing further calculations based on the results of the...
[ "If any of those calculations are computationally expensive and you do them in python and you want scalability then celery makes perfect sense.\ngevent would just make your code more efficient in specific cases, but won't help you in terms of scalability. That also holds true if you use threads.\nBear in mind that ...
[ 2 ]
[]
[]
[ "celery", "gevent", "multithreading", "python", "redis" ]
stackoverflow_0007752536_celery_gevent_multithreading_python_redis.txt
Q: pass list of iterables to itertools function i am using the itertools.product function. i have a 2-deep nested list, which is a list of iterables. i want to pass this to product function dont know how to format it correctly. to be clear, i want In [37]: [k for k in product([1,2],['a','b'])] Out[37]: [(1, 'a'), ...
pass list of iterables to itertools function
i am using the itertools.product function. i have a 2-deep nested list, which is a list of iterables. i want to pass this to product function dont know how to format it correctly. to be clear, i want In [37]: [k for k in product([1,2],['a','b'])] Out[37]: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')] but generated from ...
[ "product takes variable number of arguments, so you need to unpack your list.\nlist(product(*nested_list)) # without list() normally, of course\n\n" ]
[ 7 ]
[]
[]
[ "python", "python_itertools" ]
stackoverflow_0007780188_python_python_itertools.txt
Q: what is the difference between iterative and recursive binary search algorithms in case of asymptotic analysis I need to show the differences between the iterative and the recursive binary search algorithms' asymptotic runtime analysis'. as far as i know, they have the same worst case complexity (O(log(n)) but in ...
what is the difference between iterative and recursive binary search algorithms in case of asymptotic analysis
I need to show the differences between the iterative and the recursive binary search algorithms' asymptotic runtime analysis'. as far as i know, they have the same worst case complexity (O(log(n)) but in some resources it says that recursive has O(log(n)+1). I am a bit confused, can somebody help me about this situatio...
[ "O(log(n) + 1) is the same as O(log(n)) -- asymptotically, they produce the same set of functions. The constant addition is ignored, just like constant multiples.\nThey are different in terms of usage of space -- recursive binary search will use log(n) space (because of the stack) unless the tail-calls are removed ...
[ 2 ]
[]
[]
[ "algorithm", "binary_search", "iteration", "python", "recursion" ]
stackoverflow_0007780206_algorithm_binary_search_iteration_python_recursion.txt
Q: Python - Replace Value in Text at Random I have two open source files I've been messing around with, one file is a small macro script I'm working with, second is a txt file filled with commands I'd like to insert in to the first script in a random order within their respective lines. I've managed to come up with t...
Python - Replace Value in Text at Random
I have two open source files I've been messing around with, one file is a small macro script I'm working with, second is a txt file filled with commands I'd like to insert in to the first script in a random order within their respective lines. I've managed to come up with this script for searching and replacing the val...
[ "import random\nimport itertools as it\n\ndef replaceAll(file,searchExp,replaceExps):\n for line in fileinput.input(file, inplace=1):\n if searchExp in line:\n line = line.replace(searchExp,next(replaceExps))\n sys.stdout.write(line)\n\nwith open('SecondFile','r') as f:\n replaceExp=f...
[ 1 ]
[]
[]
[ "python", "random", "replace", "search" ]
stackoverflow_0007780331_python_random_replace_search.txt
Q: Interpolating a 3d array in Python. How to avoid for loops? I have an array which I want to interpolate over the 1st axes. At the moment I am doing it like this example: import numpy as np from scipy.interpolate import interp1d array = np.random.randint(0, 9, size=(100, 100, 100)) new_array = np.zeros((1000, 100,...
Interpolating a 3d array in Python. How to avoid for loops?
I have an array which I want to interpolate over the 1st axes. At the moment I am doing it like this example: import numpy as np from scipy.interpolate import interp1d array = np.random.randint(0, 9, size=(100, 100, 100)) new_array = np.zeros((1000, 100, 100)) x = np.arange(0, 100, 1) x_new = np.arange(0, 100, 0.1) f...
[ "You can specify an axis argument to interp1d:\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\narray = np.random.randint(0, 9, size=(100, 100, 100))\nx = np.linspace(0, 100, 100)\nx_new = np.linspace(0, 100, 1000)\nnew_array = interp1d(x, array, axis=0)(x_new)\nnew_array.shape # -> (1000, 100, 100)\n...
[ 7, 6 ]
[]
[]
[ "arrays", "interpolation", "numpy", "python", "scipy" ]
stackoverflow_0007755871_arrays_interpolation_numpy_python_scipy.txt
Q: C++, Python, Incompatible Types of Numbers I am having difficulty using the vector_indexing_suite in Boost. In C++ I have defined: class_<std::vector<double> >("PyVecDouble") .def(vector_indexing_suite<std::vector<double> >()); and class_<std::vector<long> >("PyVecLong") ...
C++, Python, Incompatible Types of Numbers
I am having difficulty using the vector_indexing_suite in Boost. In C++ I have defined: class_<std::vector<double> >("PyVecDouble") .def(vector_indexing_suite<std::vector<double> >()); and class_<std::vector<long> >("PyVecLong") .def(vector_indexing_suite<std::vect...
[ "The relationships between Numpy and C types is listed here (check the \"compatible: C ...\" sections):\nhttp://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#built-in-scalar-types\nThe size-specified types (int16 etc.) map to C int, long, long long etc. in a platform-specific way. numpy/ndarrayobject.h how...
[ 1 ]
[]
[]
[ "c++", "python", "typeerror", "types", "vector" ]
stackoverflow_0007737479_c++_python_typeerror_types_vector.txt
Q: Python mysqldb on Mac 10.6 I have tried all options, suggested here and also on many other places but still cant get it working. Just out of curiosity, why is it so insanely difficult to get this thing working on mac. I am new to the platform and getting mysql and python bindings running have been a huge pain and ...
Python mysqldb on Mac 10.6
I have tried all options, suggested here and also on many other places but still cant get it working. Just out of curiosity, why is it so insanely difficult to get this thing working on mac. I am new to the platform and getting mysql and python bindings running have been a huge pain and makes me wonder why nothing more...
[ "It's pretty straightforward:\n\nInstall MySQL client libraries (using MacPorts, downloading them from MySQL, compiling them yourself)\nUse easy_install to install MySQL-python: easy_install MySQL-python\n\nDone. You could check if it was correctly installed with a plain python interpreter:\n>>> import _mysql\n>>> ...
[ 0 ]
[]
[]
[ "django", "mysql", "python" ]
stackoverflow_0007780542_django_mysql_python.txt
Q: read 140 or less characters from python stdin I was wondering how I might read 140 or less characters from a line in python. Either the user would enter exactly 140 characters, then a newline, or less than 140 and a newline. It appears that raw_input() doesn't have a limit, and that sys.stdin.read(140) will read u...
read 140 or less characters from python stdin
I was wondering how I might read 140 or less characters from a line in python. Either the user would enter exactly 140 characters, then a newline, or less than 140 and a newline. It appears that raw_input() doesn't have a limit, and that sys.stdin.read(140) will read until it hits 140 characters, regardless of a newlin...
[ "Like \nip = sys.stdin.readline()\nif len(ip) > 140:\n print \"error: over 140 chars\"\n sys.exit()\n\n", "Normally, stdin is line-buffered, which means the program running is not informed about what the user is typing until the user presses Enter (this allows the user to use line-editing commands such as b...
[ 3, 1 ]
[]
[]
[ "input", "python", "stdin", "tweepy", "twitter" ]
stackoverflow_0007780578_input_python_stdin_tweepy_twitter.txt
Q: Using the multiprocessing module I'm trying to use the multiprocessing module in python 2.6, but apparently there is something I do not understand. I would expect the class below to add up the numbers sent to it by add() and return the sum in the get_result() method. The code below prints "0", I'd like it to print...
Using the multiprocessing module
I'm trying to use the multiprocessing module in python 2.6, but apparently there is something I do not understand. I would expect the class below to add up the numbers sent to it by add() and return the sum in the get_result() method. The code below prints "0", I'd like it to print "2". What have I missed? import multi...
[ "Change self.sum = 0 to self.sum = multiprocessing.Value('d', 0.0), and use self.sum.value to access or change the value.\nclass AdderProcess(multiprocessing.Process): \n def __init__(self):\n ...\n self.sum = multiprocessing.Value('d', 0.0) \n ...\n def run(self):\n while True:...
[ 6, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0007780478_multiprocessing_python.txt
Q: Getting decimals from python math function? I'm a bit new to python and can't seem to figure out what I'm doing wrong. a = 9 b = 13 print ((a-b)/a) -1 But on my calculator, the correct answer is -0.444444444 (meaning 'a' is about 45% lower than 'b'). How can I get a few decimals to show up? I tried print Decimal...
Getting decimals from python math function?
I'm a bit new to python and can't seem to figure out what I'm doing wrong. a = 9 b = 13 print ((a-b)/a) -1 But on my calculator, the correct answer is -0.444444444 (meaning 'a' is about 45% lower than 'b'). How can I get a few decimals to show up? I tried print Decimal((a-b)/a) print float((a-b)/a) both with the sam...
[ "Try converting one (or both) of the arguments to a float, rather than the result:\nprint ((a-b)/float(a))\n\nOr just upgrade to Python 3 where this behaviour has been fixed:\n>>> a = 9\n>>> b = 13\n>>> print ((a-b)/a)\n-0.4444444444444444\n\nBy the way, if you want integer division in Python 3.x you can use // ins...
[ 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0007780683_python.txt
Q: Python - Screen Scraping Yahoo! Gamechannel for fantasy football So I am trying to scrape Yahoo gamechannel/startracker so i can grab the updates for the fantasy teams when players get points, so i can make graphs in excel. The website url is basically http://sports.yahoo.com/nfl/gamechannel?app=st&lid=60604 <-- ...
Python - Screen Scraping Yahoo! Gamechannel for fantasy football
So I am trying to scrape Yahoo gamechannel/startracker so i can grab the updates for the fantasy teams when players get points, so i can make graphs in excel. The website url is basically http://sports.yahoo.com/nfl/gamechannel?app=st&lid=60604 <-- the number at the end is the league id i am kinda new to python. I tri...
[ "You might want to look into the Yahoo Fantasy Sports API: http://developer.yahoo.com/fantasysports/guide/index.html\nThis is the kind of data you can get.\nWould that be of any use or are you trying to get information that isn't available through the API?\nPS. You'll need to get an API key here: http://developer.y...
[ 5 ]
[]
[]
[ "javascript", "python", "screen_scraping" ]
stackoverflow_0007779686_javascript_python_screen_scraping.txt
Q: SegFault when trying to write to a Numpy array created within a C Extension I have an if clause within a for loop in which I have defined state_out beforehand with: state_out = (PyArrayObject *) PyArray_FromDims(1,dims_new,NPY_BOOL); And the if conditions are like this: if (conn_ctr<sum*2){ *(...
SegFault when trying to write to a Numpy array created within a C Extension
I have an if clause within a for loop in which I have defined state_out beforehand with: state_out = (PyArrayObject *) PyArray_FromDims(1,dims_new,NPY_BOOL); And the if conditions are like this: if (conn_ctr<sum*2){ *(state_out->data + i*state_out->strides[0]) = true; } else { ...
[ " if (conn_ctr<sum*2){\n *(state_out->data + i*state_out->strides[0]) = true;\n }\n else {\n *(state_out->data + i*state_out->strides[0]) = false;\n }\n\nHere, I naively make a pointer arithmetic, state_out->data is a pointer to the beginning of data, it is defined to be a pointer of cha...
[ 0 ]
[]
[]
[ "c", "python", "python_c_api" ]
stackoverflow_0007774524_c_python_python_c_api.txt
Q: Max recursion in "pip install" & "setup.py install" I'm trying to install a package (splinter) on a Macbook (OS X 10.6.8), but I keep getting maximum recursion errors. They occur whether I use "setup.py install" or "pip install", and whether I try to do a global install or use virtualenv. They occurred both unde...
Max recursion in "pip install" & "setup.py install"
I'm trying to install a package (splinter) on a Macbook (OS X 10.6.8), but I keep getting maximum recursion errors. They occur whether I use "setup.py install" or "pip install", and whether I try to do a global install or use virtualenv. They occurred both under Python 2.7.1 and 2.7.2. They occur when I do it a boat...
[ "You need to install a separate version of either Distribute or setuptools (the two sources for the easy_install command) for your Python 2.7 installation. Each Python instance must have its own. The Apple-supplied system Pythons in 10.6 come with their own easy_install in /usr/bin and setuptools in their Apple-s...
[ 2 ]
[]
[]
[ "python", "python_install" ]
stackoverflow_0007779503_python_python_install.txt
Q: Access parents variables in Python I have something like this: class SomeObject: #code to access parents MyVar class MyClass: MyVar = 3 MyObject = SomeObject() I need to access MyVar from inside MyObject. Is there any way I can do that? Thank you! A: You can store a reference to the MyClass objec...
Access parents variables in Python
I have something like this: class SomeObject: #code to access parents MyVar class MyClass: MyVar = 3 MyObject = SomeObject() I need to access MyVar from inside MyObject. Is there any way I can do that? Thank you!
[ "You can store a reference to the MyClass object in the SomeObject. You can initialise the reference when you make an constructor with a MyClass Object as parameter.\nclass SomeObject:\n def __init__(self, reference):\n self.reference_=reference\n #code to access parents MyVar\n self.reference_.MyV...
[ 5, 0 ]
[]
[]
[ "class", "parent", "python" ]
stackoverflow_0007780366_class_parent_python.txt
Q: Python OptsParse Attribute Checking.. i think I have an opts parse. ex.: from optparse import OptionParser parser = OptionParser() parser.add_option("ablah, dest = 'a',\ action = 'store', nargs=2) parser.add_option("bblah, dest = 'b',\ action = 'store', nargs=2) parser.add_option("cblah, dest = 'c',\ a...
Python OptsParse Attribute Checking.. i think
I have an opts parse. ex.: from optparse import OptionParser parser = OptionParser() parser.add_option("ablah, dest = 'a',\ action = 'store', nargs=2) parser.add_option("bblah, dest = 'b',\ action = 'store', nargs=2) parser.add_option("cblah, dest = 'c',\ action = 'store', nargs=2) now I would get a dictio...
[ "I'm not sure I understand your problem correctly but maybe this could give you a hint:\n# map option name to function\nfunc_map = {'ablah': ablah,\n 'bblah': bblah,\n 'cblah': cblah}\n\n# filter out the options without argument\n# this may be redundant, optparse can make proper validations\nselected ...
[ 0 ]
[]
[]
[ "arguments", "dictionary", "parsing", "python" ]
stackoverflow_0007780957_arguments_dictionary_parsing_python.txt
Q: Grappelli Tinymce missing theme I an setting up tinymce, filebrowser, zinnia, and Grappelli for the first time. I think I have everything setup properly, but it seems that I am missing some files and I am not sure where I can find them. I am getting 400 errors on the following. "GET /static/tiny_mce/themes/advance...
Grappelli Tinymce missing theme
I an setting up tinymce, filebrowser, zinnia, and Grappelli for the first time. I think I have everything setup properly, but it seems that I am missing some files and I am not sure where I can find them. I am getting 400 errors on the following. "GET /static/tiny_mce/themes/advanced/skins/grappelli/content.css HTTP/1....
[ "The grappelli skings for tinymce come with grappelli. You also should load the js files for tinymce coming with grappelli, so tinymce will find the theme files relatively to the tinymce js.\nYou can achieve this by pointing TINYMCE_JS_URL in your settings.py file to the right url, eg. TINYMCE_JS_URL = STATIC_URL +...
[ 1 ]
[]
[]
[ "django", "python", "tinymce" ]
stackoverflow_0007781076_django_python_tinymce.txt
Q: Python - Why is installing oauth2 so hard? So im trying to get oauth2 to work with python. So i downloaded it from github, and ran the setup.py file but that didn't exactly work. I googled some more and found a question here and the answer said to put the folder in python27/Lib/site-packages with a .pth file in th...
Python - Why is installing oauth2 so hard?
So im trying to get oauth2 to work with python. So i downloaded it from github, and ran the setup.py file but that didn't exactly work. I googled some more and found a question here and the answer said to put the folder in python27/Lib/site-packages with a .pth file in the /site-packages folder. The .pth folder has the...
[ "I think that you need to go back to square one. \nDid you try easy_install oauth2?\nDid you try pip install oauth2?\nIf neither of those work, then you need to install it manually. Having read through the readme on github you know that oauth2 depends on httplib2 so start by installing and testing httplib2. Don't g...
[ 33 ]
[]
[]
[ "python" ]
stackoverflow_0007781233_python.txt
Q: text aligning, python How could I align the text so that it cuts the first 140 characters of a string, and fills the rest with whitespace? e.g. "%140s"%some_text but the space on the other side. Thoughts? A: Simple: "%-140.140s" % some_text A: You can also use rjust and ljust for strings. In combination with s...
text aligning, python
How could I align the text so that it cuts the first 140 characters of a string, and fills the rest with whitespace? e.g. "%140s"%some_text but the space on the other side. Thoughts?
[ "Simple: \"%-140.140s\" % some_text\n", "You can also use rjust and ljust for strings. In combination with slicing you get this:\n>>> \"blabla\"[:10].ljust(10)\n'blabla '\n>>> \"blabla12345678901234567890\"[:10].ljust(10)\n'blabla1234'\n>>> \n>>> \"blabla\"[:10].rjust(10)\n' blabla'\n>>> \"blabla12345678901...
[ 6, 3 ]
[]
[]
[ "alignment", "character", "python", "string", "text" ]
stackoverflow_0007781242_alignment_character_python_string_text.txt
Q: How to remove standart menuitem from QTextEdit context menu So, i'm pretty new in PySide and QT, and want to know how to remove menuitem (it does not matter what kind of (undo, redo, copy, paste and etc)) from QTextEdit standart context menu. Or tell me a way to get QMenu object of this context menu. Then i can ap...
How to remove standart menuitem from QTextEdit context menu
So, i'm pretty new in PySide and QT, and want to know how to remove menuitem (it does not matter what kind of (undo, redo, copy, paste and etc)) from QTextEdit standart context menu. Or tell me a way to get QMenu object of this context menu. Then i can apply removeAction method to menuitem. TIA.
[ "To get full control over the context menu, first use QWidget.setContextMenuPolicy to change the context meu policy to Qt.CustomContextMenu. Then connect a handler to the QWidget.customContextMenuRequested signal. In the handler, you can then get a standard context menu object using the QTextEdit.createStandardCont...
[ 3, 2 ]
[]
[]
[ "pyqt", "pyside", "python", "qt" ]
stackoverflow_0007779988_pyqt_pyside_python_qt.txt
Q: Loading table in sqlite db using python: table not found I'm using python 2.7 and am trying to load a pipe delimited file into a sqlite table. Originally I tried to bloc transactions, but ran into an "Operational Error: no such table: ff. I added the global statement in the function, didn't help either (didn't exp...
Loading table in sqlite db using python: table not found
I'm using python 2.7 and am trying to load a pipe delimited file into a sqlite table. Originally I tried to bloc transactions, but ran into an "Operational Error: no such table: ff. I added the global statement in the function, didn't help either (didn't expect it to, but tried to be sure). So removing the function cal...
[ "There is nothing obviously wrong with your code. After trimming off all the unused code, making the remaining code a bit more terse and making cnt count something, it runs OK as shown below, with only one commit (just before terminating). I suggest that you try this code on a non-cloud system first, to ensure that...
[ 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007778669_python_sqlite.txt
Q: Python/Tkinter: Getting the full Event name? How do I get the full name of an event? For example, Event.keysym only shows "c" for an event triggered by "<Control-c>". How can I get the "Control" too? A: Event.state holds the OR'd together states of the modifier keys. So you could try something like: modifiers = ...
Python/Tkinter: Getting the full Event name?
How do I get the full name of an event? For example, Event.keysym only shows "c" for an event triggered by "<Control-c>". How can I get the "Control" too?
[ "Event.state holds the OR'd together states of the modifier keys. So you could try something like:\nmodifiers = []\nif event.state & 1:\n modifiers.append('Shift')\nif event.state & 4:\n modifiers.append('Control')\n# ... etc\nprint '-'.join(modifiers)\n\nSee here for more details.\n" ]
[ 3 ]
[]
[]
[ "events", "python", "tkinter" ]
stackoverflow_0007780814_events_python_tkinter.txt
Q: python regular expression replace I'm trying to change a string that contains substrings such as the</span></p> <p><span class=font7>currency to the currency At the line break is CRLF The words before and after the code change. I only want to replace if the second word starts with a lower case letter. The only ...
python regular expression replace
I'm trying to change a string that contains substrings such as the</span></p> <p><span class=font7>currency to the currency At the line break is CRLF The words before and after the code change. I only want to replace if the second word starts with a lower case letter. The only thing that changes in the code is the d...
[ "Use a lookahead assertion.\np = re.compile('</span></p>\\r\\n<p><span class=font\\d>(?=[a-z])')\nres = p.sub(' ', data)\n\n", "This : \nresult = re.sub(\"(?si)(.*?)</?[A-Z][A-Z0-9]*[^>]*>.*</?[A-Z][A-Z0-9]*[^>]*>(.*)\", r\"\\1 \\2\", subject)\n\nApplied to : \nthe</span></p>\n<p><span class=font7>currency\n\nPro...
[ 1, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007781414_python_regex.txt
Q: How can I find out why using PIL functions is resulting in a memory error? I am using PIL (python image library) to do some image manipulation, specifically I am stitching images together. My code seems to work fine for some images in small quantities, but sometime I and getting a MemoryError. The part that is p...
How can I find out why using PIL functions is resulting in a memory error?
I am using PIL (python image library) to do some image manipulation, specifically I am stitching images together. My code seems to work fine for some images in small quantities, but sometime I and getting a MemoryError. The part that is particularly strange to me is that I am not doing manipulations on bit images, it...
[ "To explain what actually happens:\n\nYou try to resize an image to a negative width\nPIL tries to allocate a negatively sized image to fit the resized image\nPIL calls malloc with a negative amount of memory to hold to negatively sized image\nmalloc takes a size_t which is unsigned. As a result, the negative memor...
[ 10, 8 ]
[]
[]
[ "memory", "python", "python_imaging_library" ]
stackoverflow_0007762226_memory_python_python_imaging_library.txt
Q: How to handle constructors or methods with a different set (or type) of arguments in Python? Is there a way in Python, to have more than one constructor or more than one method with the same name, who differ in the number of arguments they accept or the type(s) of one or more argument(s)? If not, what would be the...
How to handle constructors or methods with a different set (or type) of arguments in Python?
Is there a way in Python, to have more than one constructor or more than one method with the same name, who differ in the number of arguments they accept or the type(s) of one or more argument(s)? If not, what would be the best way to handle such situations? For an example I made up a color class. This class should onl...
[ "You can have the factory methods, it is fine. But why not just call it as it is?\nColor(r, g, b)\nColor(*[r, g, b])\nColor(**{'r': r, 'g': g, 'b': b})\n\nThis is the python way. As for the from object constructor, I would prefer something like:\nColor(*Color2.as_list())\n\nExplicit is better than implicit - Python...
[ 11, 10, 8, 2, 1, 0 ]
[ "You can check the type of the argument passed to your constructor inside:\ndef __init__(self, r = 0, g = 0, b = 0):\n # if r is a list\n if (type(r) == type([1,2,3])):\n r, g, b = r[0], r[1], r[2]\n # if r is a color\n if (type(r) == type(self)):\n r, g, b = r.r, r.g, r.b\n self.r = r\...
[ -1 ]
[ "python" ]
stackoverflow_0000356718_python.txt
Q: Can I find out the result of javascript in Python? I'm now making a web crawler. getting a link from HTML is easy part but acquiring a link from the result of javascript is not easy for me. Can I get the result of javascript so as to know where a link is referred to? for example. How can I retrieve the link to goo...
Can I find out the result of javascript in Python?
I'm now making a web crawler. getting a link from HTML is easy part but acquiring a link from the result of javascript is not easy for me. Can I get the result of javascript so as to know where a link is referred to? for example. How can I retrieve the link to google.com from javascript code in Python? <!DOCTYPE html> ...
[ "You would need to install node.js and run a separate piece of code that executes the Javascript code in context to emit the html. This is possible using jsdom but the key to it is extracting the Javascript code from the HTML page, and setting up the context correctly.\n", "Python doesn't offer a way to execute t...
[ 1, 0 ]
[]
[]
[ "django", "javascript", "pyjamas", "python", "urllib" ]
stackoverflow_0007781420_django_javascript_pyjamas_python_urllib.txt
Q: AppEngine Pipeline Yield - is this standard usage of the yield operator? From the following page (http://code.google.com/p/appengine-pipeline/wiki/GettingStarted) I have seen the following code in an example of how to use the AppEngine pipeline: class AddOne(pipeline.Pipeline): def run(self, number): return...
AppEngine Pipeline Yield - is this standard usage of the yield operator?
From the following page (http://code.google.com/p/appengine-pipeline/wiki/GettingStarted) I have seen the following code in an example of how to use the AppEngine pipeline: class AddOne(pipeline.Pipeline): def run(self, number): return number + 1 class AddTwoAndLog(pipeline.Pipeline): def run(self, number): ...
[ "Assigning from a yield is standard as of Python 2.5. It enables coroutines.\nSee http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features\n" ]
[ 2 ]
[]
[]
[ "google_app_engine", "pipeline", "python", "yield" ]
stackoverflow_0007779786_google_app_engine_pipeline_python_yield.txt
Q: xpath selecting elements and iterating over the tag Consider the tag in my html is like this <div class ="summary"> <p>Best <a class="abch" href="/canvas">canvas</a> abcdefgh <a class="zph" href="/canvas">canvas</a>, I cycle them to garden</p> </div> When I do site.select('.//*[contains(@class, "summary")]/...
xpath selecting elements and iterating over the tag
Consider the tag in my html is like this <div class ="summary"> <p>Best <a class="abch" href="/canvas">canvas</a> abcdefgh <a class="zph" href="/canvas">canvas</a>, I cycle them to garden</p> </div> When I do site.select('.//*[contains(@class, "summary")]/p/text()').extract() I get only the text of p and the hy...
[ "I think two slashes after p will work for you. One slash / selects children only, two slashes // will include deeper elements. Since text nodes under a are not direct children of p they are not selected.\nsite.select('.//*[contains(@class, \"summary\")]/p//text()').extract()\n\nUpdate:\nAnswering to your comment: ...
[ 0, 0 ]
[]
[]
[ "extract", "hyperlink", "python", "xpath" ]
stackoverflow_0007777060_extract_hyperlink_python_xpath.txt
Q: Using "class" as an option to a Mako Macro I am writing a Mako extension that assist in rendering forms. I was making excellent progress until I ran into one big stumbling block regarding css classes. I want to write code that looks like this: <%fp:form method="post" action="" class="css-class"%> ...content </%fp:...
Using "class" as an option to a Mako Macro
I am writing a Mako extension that assist in rendering forms. I was making excellent progress until I ran into one big stumbling block regarding css classes. I want to write code that looks like this: <%fp:form method="post" action="" class="css-class"%> ...content </%fp:form> The function that fp:form refers to looks...
[ "There is no way around this because class is a keyword and is always parsed as such. People usually use class_ instead.\n" ]
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0007781431_mako_python.txt
Q: approximate nearest neighbor library for python (WINDOWS) My main intention is just use some functions in the ann library in Pylab to calculate nearest neighbor. My system is Windows Vista 32 bit. I have a few questions about the ANN webpage. For ANN Version 1.1.2, I found two download options "ann_1.1.2.zip" and...
approximate nearest neighbor library for python (WINDOWS)
My main intention is just use some functions in the ann library in Pylab to calculate nearest neighbor. My system is Windows Vista 32 bit. I have a few questions about the ANN webpage. For ANN Version 1.1.2, I found two download options "ann_1.1.2.zip" and "ann_1.1.2_MS_Win32_bin.zip" for Windows. After reading the AN...
[ "Try scikits.ann (Windows binaries). \n", "I believe you've got some real difficulty in using ANN with Pylab.\nThe website contains C++ code and precompiled libraries. This is nice of them, as not all Windows users have C++ compilers available. However, calling into a library requires some sort of programming env...
[ 1, 0 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007781601_matplotlib_python.txt
Q: Order a queryset in django by an annotated field and append the rest of the objects that did not fit the criteria So this snippet practically explains what I want to do bloc_results = bloc_results.annotate(num_mates=Count(profilebloc__profile__in=probable_mates)).order_by("-num_mates") I know this is not possible...
Order a queryset in django by an annotated field and append the rest of the objects that did not fit the criteria
So this snippet practically explains what I want to do bloc_results = bloc_results.annotate(num_mates=Count(profilebloc__profile__in=probable_mates)).order_by("-num_mates") I know this is not possible but it was the easiest way I found to explain the situation. the variable probable_mates is a list filled with the pk'...
[ "Like akonsu said in his comment, I'm not exactly sure what you are trying to accomplish. That said, this sounds similar to this question I just answered. Adapted to your model names, does the following do what you want?\nmatches = bloc_results.objects.filter(profilebloc__profile__in=probable_mates)\nmatches = matc...
[ 0, 0, 0 ]
[]
[]
[ "django", "python", "web" ]
stackoverflow_0007747937_django_python_web.txt
Q: Which is faster to extract URLs in HTML? [html.parser.HTMLParser] OR [re.match] OR whatever Sometimes, I want to parse HTML to extract URLs. I find [html.parser.HTMLParser] and [re.match] both can do the job. I want to know which is faster. Is there a python-module like jquery to parse HTML? If you have better sol...
Which is faster to extract URLs in HTML? [html.parser.HTMLParser] OR [re.match] OR whatever
Sometimes, I want to parse HTML to extract URLs. I find [html.parser.HTMLParser] and [re.match] both can do the job. I want to know which is faster. Is there a python-module like jquery to parse HTML? If you have better solution, please leave a comment. Thanks lxml is very good. it make the job really simple. >>>for u...
[ "I would strongly suggest lxml. In my experience, it is the fastest. lxml will actually generate a tree in memory. So you can parse/serialize/...\nOn the other hand, if you have to pick among the mentioned two options, I'd suggest you use the timeit module and determine it. \n", "I would guess that re is faster, ...
[ 6, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007782054_python.txt
Q: Need custom model export script in blender I've been coding a simple android game with openGL ES 1.0 and require a simple exporter for Blender, but don't really understand python and how to add export scripts to blender 2.59. I tried the tutorial at: http://en.wikibooks.org/wiki/Blender_3D:_Noob_to_Pro/Advanced_Tu...
Need custom model export script in blender
I've been coding a simple android game with openGL ES 1.0 and require a simple exporter for Blender, but don't really understand python and how to add export scripts to blender 2.59. I tried the tutorial at: http://en.wikibooks.org/wiki/Blender_3D:_Noob_to_Pro/Advanced_Tutorials/Python_Scripting/Export_scripts , but I ...
[ "I would start with Jeff Lamarche's scripts on github.\nhttps://github.com/jlamarche/iOS-OpenGLES-Stuff/tree/master/Blender%20Export\nThe blog post is here:\nhttp://iphonedevelopment.blogspot.com/2010/10/blender-ios.html\nI recall having to fiddle with the blender or version tuples in the bl_info dictionary but it ...
[ 1 ]
[]
[]
[ "blender", "python" ]
stackoverflow_0007781731_blender_python.txt
Q: How to check Space between Two images Consider there are two images in a webpage. I want know if they have any space rendered between them. I'm using selenium tool and python language. Answer could be in any language. A: you can look up the position and size of each image quickly with javascript (I'm using jquer...
How to check Space between Two images
Consider there are two images in a webpage. I want know if they have any space rendered between them. I'm using selenium tool and python language. Answer could be in any language.
[ "you can look up the position and size of each image quickly with javascript (I'm using jquery)\n$('#image-one').width\n\n height\n\n x\n\n y\n\n$('#image-two')...same thing\nJust see if the x of one is right next to the x+width of the other. Repeat for Y. \nedit: ther...
[ 1 ]
[]
[]
[ "perl", "python", "selenium_rc" ]
stackoverflow_0007776461_perl_python_selenium_rc.txt
Q: Random memcache calls take extra-ordinarily long Please see this appstats log, randomly some memcache calls take extraordinarily longer than others. These are all get calls for memcached counters so there is absolutely nothing different about the calls that are taking longer than others. Any explanation? A: Me...
Random memcache calls take extra-ordinarily long
Please see this appstats log, randomly some memcache calls take extraordinarily longer than others. These are all get calls for memcached counters so there is absolutely nothing different about the calls that are taking longer than others. Any explanation?
[ "Memcache like all GAE service is done using a remote procedure call and the response time is not generated. If the machine/network is busy it might lag. \nThe real question here is way are you calling memcache 20 times in a single request?\nThere are two ways go work around it:\n\nUse the get_multi to retreive al...
[ 1 ]
[]
[]
[ "google_app_engine", "memcached", "python" ]
stackoverflow_0007552607_google_app_engine_memcached_python.txt
Q: function for loading both strings and files on disk? I have a design question. I have a function loadImage() for loading an image file. Now it accepts a string which is a file path. But I also want to be able to load files which are not on physical disk, eg. generated procedurally. I could have it accept a string,...
function for loading both strings and files on disk?
I have a design question. I have a function loadImage() for loading an image file. Now it accepts a string which is a file path. But I also want to be able to load files which are not on physical disk, eg. generated procedurally. I could have it accept a string, but then how could it know the string is not a file path ...
[ "You can change your loadImage function to expect an opened file-like object, such as:\ndef load_image(f):\n data = file.read()\n\n... and then have that called from two functions, one of which expects a path and the other a string that contains the data:\nfrom StringIO import StringIO\n\ndef load_image_from_pat...
[ 3, 0, 0 ]
[]
[]
[ "arguments", "file", "python", "string" ]
stackoverflow_0007782650_arguments_file_python_string.txt
Q: wget Vs urlretrieve of python I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size. The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high ...
wget Vs urlretrieve of python
I have a task to download Gbs of data from a website. The data is in form of .gz files, each file being 45mb in size. The easy way to get the files is use "wget -r -np -A files url". This will donwload data in a recursive format and mirrors the website. The donwload rate is very high 4mb/sec. But, just to play around I...
[ "Probably a unit math error on your part. \nJust noticing that 500KB/s (kilobytes) is equal to 4Mb/s (megabits).\n", "urllib works for me as fast as wget. try this code. it shows the progress in percentage just as wget.\nimport sys, urllib\ndef reporthook(a,b,c): \n # ',' at the end of the line is important!\n...
[ 40, 9, 3, 3, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "urllib2", "wget" ]
stackoverflow_0000974741_python_urllib2_wget.txt
Q: Interactive (annotated) charts in python What are the best libaries for creating interactive (zoom, pan, create online annotations) charts in python? I've checked Pretty graphs and charts in Python but this does not address zoom, pan, and annotation capabilities. A: I'm not sure what you mean by "annotation" in ...
Interactive (annotated) charts in python
What are the best libaries for creating interactive (zoom, pan, create online annotations) charts in python? I've checked Pretty graphs and charts in Python but this does not address zoom, pan, and annotation capabilities.
[ "I'm not sure what you mean by \"annotation\" in this context, but matplotlib graphs are well-suited for interactive work, and include very good zooming and panning capabilities built-in.\n" ]
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0007782967_python.txt
Q: Python unit-test running oddity with Eclipse and PyDev I have created a Pydev project following this layout: - project_root/ |- setup.py |- my_package/ |- __init__.py |- my_module.py |- tests/ |- __init__.py |- test_my_module.py The project_root directory was added to PYTHONPATH...
Python unit-test running oddity with Eclipse and PyDev
I have created a Pydev project following this layout: - project_root/ |- setup.py |- my_package/ |- __init__.py |- my_module.py |- tests/ |- __init__.py |- test_my_module.py The project_root directory was added to PYTHONPATH during project creation. The my_package/my_module.py file h...
[ "How strange. Nothing's changed in the environment or settings, but the problem disappeared.\nRunning the tests using nosetests or unittest.discover from PyDev or from command line works OK...\n" ]
[ 0 ]
[]
[]
[ "eclipse", "nose", "pydev", "python", "unit_testing" ]
stackoverflow_0007779019_eclipse_nose_pydev_python_unit_testing.txt
Q: select from three tables in one query gives multiplied result I try to select from three tables in one query. these three sql tables I select has 93 lines per table import sqlite3 database = sqlite3.connect('F.tsj') cursor = database.cursor() cursor.execute("select Name, C1, C2, C3, NumofEpochs, HDop, VDop, NumOf...
select from three tables in one query gives multiplied result
I try to select from three tables in one query. these three sql tables I select has 93 lines per table import sqlite3 database = sqlite3.connect('F.tsj') cursor = database.cursor() cursor.execute("select Name, C1, C2, C3, NumofEpochs, HDop, VDop, NumOfGpsSats, SecondsFrom1970 from tblSoPoints, tblCrdGnssRaw, tblCrdRaw...
[ "Instead of:\nWHERE keySoPoint AND keyCrdGnssRaw = keyCrdRawMeas\n\nI guess you meant this:\nWHERE keySoPoint = keyCrdRawMeas\nAND keyCrdGnssRaw = keyCrdRawMeas\n\nI'd also recommend that you start using the JOIN syntax as it makes errors in the join conditions less likely:\nSELECT Name, C1, C2, C3, NumofEpochs, HD...
[ 3 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0007783328_python_sqlite.txt
Q: Using instance attributes as parameters to a method I have this code I am trying out and I can't figure out how to modify the instance attributes when I use them as parameters when calling a method. class Portfolio(object): def __init__(self): self.qtyA = 50 self.qtyB = 0 self.qtyC = 0 ...
Using instance attributes as parameters to a method
I have this code I am trying out and I can't figure out how to modify the instance attributes when I use them as parameters when calling a method. class Portfolio(object): def __init__(self): self.qtyA = 50 self.qtyB = 0 self.qtyC = 0 self.cash = 0 def __str__(self): r...
[ "\nThis problem might be related to this question: Python: How do I pass a variable by reference?\n\nIt is.\n\nHow can I work around this issue?\n\nYou need to pass a value that can be modified, and modify it. Numbers cannot be modified: a can be changed from referring to 23 to referring to 42 instead, but you cann...
[ 2, 0, 0, 0 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0007782682_class_methods_python.txt
Q: How to rerun a series of statements in the same order in a shell? I bet you have came across the same problem like me. I use shell(s) a lot. For python, ruby(irb), mongo... I use some shortcurt like crt+a to go at the begining, crt+e at the end, crt+k to clean to the end. But I miss one thing. When you define a mu...
How to rerun a series of statements in the same order in a shell?
I bet you have came across the same problem like me. I use shell(s) a lot. For python, ruby(irb), mongo... I use some shortcurt like crt+a to go at the begining, crt+e at the end, crt+k to clean to the end. But I miss one thing. When you define a multiline block in a ruby shell or a python shell and you miswrite someth...
[ "Pry (A Ruby REPL) was designed to make this kind of thing less of a pain. There are a few options to deal with this situation:\n(1) Use amend-line to fix the line.\n\n(2) Dump the current input buffer into an editor using the edit command, the changes you make in the editor are then brought back into the Pry sessi...
[ 3, 1, 1, 0 ]
[]
[]
[ "bash", "python", "ruby", "shell" ]
stackoverflow_0007777484_bash_python_ruby_shell.txt
Q: Remote control or script Open Office to edit Word document from Python I want to (preferably on Windows) start Open Office on a particular document, search for a fixed string and replace it with another string selected by my program. How do I do that, from an external Python program? OLE-something? The native Py...
Remote control or script Open Office to edit Word document from Python
I want to (preferably on Windows) start Open Office on a particular document, search for a fixed string and replace it with another string selected by my program. How do I do that, from an external Python program? OLE-something? The native Python scripting solution? (The document is in the Word 97-2003 format, but th...
[ "I'd say using the Python-UNO bridge. Does this work for you?\nimport uno\n\nctx = uno.getComponentContext()\nservice_manager = ctx.getServiceManager() \ndesktop = service_manager.createInstanceWithContext(\"com.sun.star.frame.Desktop\", ctx)\ndocument = desktop.loadComponentFromURL(\"file:///file.doc\", \"_blank\"...
[ 3 ]
[]
[]
[ "libreoffice", "ms_word", "openoffice_writer", "python", "replace" ]
stackoverflow_0007783678_libreoffice_ms_word_openoffice_writer_python_replace.txt
Q: Advice on writing a solver for Vexed levels Vexed is a popular puzzle game, with many versions available (some of them GPL free software). It is very suitable for small screen devices; versions are available for Android, iOS, etc. I discovered it on the PalmOS platform. Just for fun, I'd like to write a solver t...
Advice on writing a solver for Vexed levels
Vexed is a popular puzzle game, with many versions available (some of them GPL free software). It is very suitable for small screen devices; versions are available for Android, iOS, etc. I discovered it on the PalmOS platform. Just for fun, I'd like to write a solver that will solve Vexed levels. Vexed is a block-sli...
[ "Studying Wikipedia may be better than studying the actual source code. A* is written out pretty clearly there. But that feels like cheating, doesn't it?\nAs all good ideas, A* is actually pretty obvious in retrospective. It's fun trying to work it through, and there are a few nice insights along the way. Here's ho...
[ 5, 1 ]
[]
[]
[ "artificial_intelligence", "c", "game_ai", "python", "solver" ]
stackoverflow_0007782909_artificial_intelligence_c_game_ai_python_solver.txt
Q: How to properly handle simplejson errors? I've loaded json data to api_result variable. Now I need to extract particular fields (name, surname, city etc.). How should I verify if they are there? api_result = json.loads(some_json_data) if api_result.get('name'): # do something with name if api_result.get('surna...
How to properly handle simplejson errors?
I've loaded json data to api_result variable. Now I need to extract particular fields (name, surname, city etc.). How should I verify if they are there? api_result = json.loads(some_json_data) if api_result.get('name'): # do something with name if api_result.get('surname'): # do something with surname if api_re...
[ "get() in Python has a default parameter, if the value is not found the default value will be retuned.\nprint dict.get(\"name\", \"<default name>\")\n\n" ]
[ 3 ]
[]
[]
[ "python", "simplejson" ]
stackoverflow_0007783876_python_simplejson.txt
Q: Interactive visualization of a graph in python I have a program written in python using the module networkx to create a dynamic graph. It is a planer graph where the vertices remain constant but the edges change. Now I'm looking for a library that allows me to do two things, in a fast and quick manner preferably: ...
Interactive visualization of a graph in python
I have a program written in python using the module networkx to create a dynamic graph. It is a planer graph where the vertices remain constant but the edges change. Now I'm looking for a library that allows me to do two things, in a fast and quick manner preferably: Drawing the vertices as the lattice points inside a...
[ "For modest graph sizes, any good python graphics library should provide sufficient primitives to address this issue. For example, either Pyglet or PyGame would be suitable.\n" ]
[ 1 ]
[]
[]
[ "graph", "graph_visualization", "graphics", "networkx", "python" ]
stackoverflow_0007632180_graph_graph_visualization_graphics_networkx_python.txt
Q: Parallel processing within a queue (using Pool within Celery) I'm using Celery to queue jobs from a CGI application I made. The way I've set it up, Celery makes each job run one- or two-at-a-time by setting CELERYD_CONCURRENCY = 1 or = 2 (so they don't crowd the processor or thrash from memory consumption). The qu...
Parallel processing within a queue (using Pool within Celery)
I'm using Celery to queue jobs from a CGI application I made. The way I've set it up, Celery makes each job run one- or two-at-a-time by setting CELERYD_CONCURRENCY = 1 or = 2 (so they don't crowd the processor or thrash from memory consumption). The queue works great, thanks to advice I got on StackOverflow. Each of t...
[ "What you need is a workflow management system (WFMS) that manages\n\ntask concurrency\ntask dependency\ntask nesting\n\namong other things. \nFrom a very high level view, a WFMS sits on top of a task pool like celery, and submits the tasks which are ready to execute to the pool. It is also responsible for openin...
[ 0, 0 ]
[]
[]
[ "django_celery", "multiprocessing", "parallel_processing", "python", "threadpool" ]
stackoverflow_0007693467_django_celery_multiprocessing_parallel_processing_python_threadpool.txt
Q: Is there an API for Wireshark, to develop programs/plugins that interact with it/enhance it? Googling didn't give me great results. Is there any sort of API for Wireshark that abstracts away from the main source code so we can develop programs that interact with it and deal with the data it provides? edit: I app...
Is there an API for Wireshark, to develop programs/plugins that interact with it/enhance it?
Googling didn't give me great results. Is there any sort of API for Wireshark that abstracts away from the main source code so we can develop programs that interact with it and deal with the data it provides? edit: I appreciate the suggestions for different ways to receive packets, but I want to implement packet inje...
[ "I use pypcap to read packets and dpkt to parse.\nFor example, to use dpkt to read packets from a saved pcap:\nimport socket\nimport dpkt\nimport sys\npcapReader = dpkt.pcap.Reader(file(sys.argv[1], \"rb\"))\nfor ts, data in pcapReader:\n ether = dpkt.ethernet.Ethernet(data)\n if ether.type != dpkt.ethernet.E...
[ 5, 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "api", "c++", "packet_sniffers", "python", "wireshark" ]
stackoverflow_0002198972_api_c++_packet_sniffers_python_wireshark.txt
Q: How to compile 64 bit Python library (SIP, for example) at the 32 bit old Mac with py2app? I need to compile 64 bit libraries for Python (SIP for example) instead 32-bit, compiled by my old 32bit Mac for using to .app bandle at new Macs. Looks like similar question placed here Is it possible to compile a 64 bit ...
How to compile 64 bit Python library (SIP, for example) at the 32 bit old Mac with py2app?
I need to compile 64 bit libraries for Python (SIP for example) instead 32-bit, compiled by my old 32bit Mac for using to .app bandle at new Macs. Looks like similar question placed here Is it possible to compile a 64 bit executable on a 32 bit system under Ubuntu? but is looks like a very slow-tuning way, but I need...
[ "You will need to rebuild your entire python distribution, including all the packages as 32 bit architecture. It might be easiest to do this on the old Mac you're developing for. It's not going to be fast, but it it is not complicated. \n" ]
[ 0 ]
[]
[]
[ "32bit_64bit", "macos", "py2app", "python", "python_sip" ]
stackoverflow_0007784153_32bit_64bit_macos_py2app_python_python_sip.txt
Q: Is IronPython + XNA a serious contender for game development? I do enjoy the other multimedia libraries for Python, however I am curious if IronPython and XNA could be a contender for game development. Is there any reason why you don't hear of this too often? Also, this was meant to be more or less a topic regardi...
Is IronPython + XNA a serious contender for game development?
I do enjoy the other multimedia libraries for Python, however I am curious if IronPython and XNA could be a contender for game development. Is there any reason why you don't hear of this too often? Also, this was meant to be more or less a topic regarding Python and IronPython. I know there are other languages that may...
[ "By using IronPython + XNA, instead of C# + XNA, you lose XNA's cross-platform capabilities.\nYou cannot run IronPython on the Xbox 360 or Windows Phone 7 (see this thread). I also suspect that you won't be able to use other cross-platform XNA implementations (eg: my own ExEn).\nAlso there is, of course, a performa...
[ 2 ]
[]
[]
[ "ironpython", "python", "xna" ]
stackoverflow_0007768276_ironpython_python_xna.txt
Q: Static variable simultaion: classes vs generators I was curious about using static variables in python, and ended up at: Why doesn't Python have static variables? In the accepted answer, which I found informative, it is said "If you want your function's behavior to change each time it's called, what you need is a ...
Static variable simultaion: classes vs generators
I was curious about using static variables in python, and ended up at: Why doesn't Python have static variables? In the accepted answer, which I found informative, it is said "If you want your function's behavior to change each time it's called, what you need is a generator". However I was a bit confused, since the exa...
[ "Generators (the simple ones, not getting into coroutines) have a single, very specific purpose: Writing iterators. To this end, you get implicit capture of local variable and a keyword to suspend (as opposed to \"terminate\" - you can resume) execution and give the caller the next value of the iterator. The advant...
[ 3, 2, 2, 1 ]
[]
[]
[ "class", "generator", "python", "static_variables" ]
stackoverflow_0007783970_class_generator_python_static_variables.txt
Q: Basic/Digest HTTP Authentication in a Pyramid app I have a very simple Pyramid app (my first one) and I'd like to 'lock' a couple of view callables with Basic/Digest HTTP Authentication (the generic login popup). This app will be administered by just one user. So I'd like a very basic security. I've read theory ab...
Basic/Digest HTTP Authentication in a Pyramid app
I have a very simple Pyramid app (my first one) and I'd like to 'lock' a couple of view callables with Basic/Digest HTTP Authentication (the generic login popup). This app will be administered by just one user. So I'd like a very basic security. I've read theory about Pyramid's Authentication Policy, AuthKit, repoze.wh...
[ "If you only have say one \"/admin\" section with one administrator you can configure nginx as a reverse proxy with authentication. \nI'm using this to \"protect\" public sections of demo sites before opening to the whole world.\nThe advantage is that you can use exactly the same method for serving Django or Pylons...
[ 1 ]
[]
[]
[ "authentication", "pyramid", "python" ]
stackoverflow_0007780785_authentication_pyramid_python.txt
Q: Maintaining sequence type in set or list comprehension in python If I have a function that can operate on both sets and lists and should return a modified form of the sequence, is there a way to preserve the sequence type but still use a comprehension? For example, in the following if I call stripcommonpathprefix ...
Maintaining sequence type in set or list comprehension in python
If I have a function that can operate on both sets and lists and should return a modified form of the sequence, is there a way to preserve the sequence type but still use a comprehension? For example, in the following if I call stripcommonpathprefix with a set, it works but has the undesired side effect of converting t...
[ "There is no good way to preserve the type of the sequence. As you have guessed, if you really want to do this, you will have to convert the answer at the end to the type you want. It's quite likely that you don't need to do this, so you should think hard about it.\nOne shortcut that might help you if you do deci...
[ 5, 0 ]
[]
[]
[ "list", "list_comprehension", "python", "python_3.x", "set" ]
stackoverflow_0007784549_list_list_comprehension_python_python_3.x_set.txt
Q: tkinter and GUI programming methods Hopefully this doesn't fall under "general discussion topic", since I'd like it to be more about resolving these issues in an efficient manner than a giant debate about which general approach to GUI programming is the absolute best. So I've started some GUI programming with tkin...
tkinter and GUI programming methods
Hopefully this doesn't fall under "general discussion topic", since I'd like it to be more about resolving these issues in an efficient manner than a giant debate about which general approach to GUI programming is the absolute best. So I've started some GUI programming with tkinter and long story short my code is getti...
[ "It sounds like you're trying to create a GUI that acts procedurally, which won't work. GUIs aren't procedural, their code doesn't run linearly where functions call callbacks which return values. What you're asking isn't unique to tkinter. This is the nature of event based GUI programming -- callbacks can't return ...
[ 8 ]
[]
[]
[ "paradigms", "python", "tkinter", "user_interface" ]
stackoverflow_0007782425_paradigms_python_tkinter_user_interface.txt
Q: Boost / Python unix timestamps don't match Python 2.6: import pytz import time import datetime time.mktime(datetime.datetime(1990, 1, 1, tzinfo=pytz.utc).timetuple()) Result: 631148400.0 Boost 1.46: auto a = boost::posix_time::ptime(boost::gregorian::date(1990, 1, 1)); auto b = boost::posix_time::ptime(boost::gr...
Boost / Python unix timestamps don't match
Python 2.6: import pytz import time import datetime time.mktime(datetime.datetime(1990, 1, 1, tzinfo=pytz.utc).timetuple()) Result: 631148400.0 Boost 1.46: auto a = boost::posix_time::ptime(boost::gregorian::date(1990, 1, 1)); auto b = boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)); // unix epoch boost:...
[ "For the example below I set my time zone to GMT-01:\n>>> import datetime, time, pytz\n\n>>> tz = pytz.FixedOffset(-60)\n>>> dt = datetime.datetime(1990, 1, 1, tzinfo=pytz.utc)\n\n>>> tm = dt.astimezone(tz).timetuple(); tm\ntime.struct_time(tm_year=1989, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=0, tm_s\nec=0, tm_w...
[ 2, 0 ]
[]
[]
[ "boost", "datetime", "epoch", "python" ]
stackoverflow_0007784340_boost_datetime_epoch_python.txt
Q: Python: ways of parsing get/post parameters I'm trying to analyse different ways of Python connection to webserver: cgi, fastcgi, mod_python, WSGI, and Django framework... So, how many ways exist to parse get/post parameters in python? Are they differ from one connection to another? I saw this question. CGI, Djan...
Python: ways of parsing get/post parameters
I'm trying to analyse different ways of Python connection to webserver: cgi, fastcgi, mod_python, WSGI, and Django framework... So, how many ways exist to parse get/post parameters in python? Are they differ from one connection to another? I saw this question. CGI, Django etc. are considered there. But what about fast...
[ "urlparse.parseqs[l]() is used to parse parameters. But you likely won't have to do it yourself since the framework (if you're using one) will handle them.\n" ]
[ 2 ]
[]
[]
[ "cgi", "get", "post", "python" ]
stackoverflow_0007785029_cgi_get_post_python.txt
Q: Better Python list Naming Other than "list" Is it better not to name list variables "list"? Since it's conflicted with the python reserved keyword. Then, what's the better naming? "input_list" sounds kinda awkward. I know it can be problem-specific, but, say I have a quick sort function, then quick_sort(unsorted_...
Better Python list Naming Other than "list"
Is it better not to name list variables "list"? Since it's conflicted with the python reserved keyword. Then, what's the better naming? "input_list" sounds kinda awkward. I know it can be problem-specific, but, say I have a quick sort function, then quick_sort(unsorted_list) is still kinda lengthy, since list passed t...
[ "I like to name it with the plural of whatever's in it. So, for example, if I have a list of names, I call it names, and then I can write:\nfor name in names:\n\nwhich I think looks pretty nice. But generally for your own sanity you should name your variables so that you can know what they are just from the name....
[ 26, 6, 6, 3, 3, 2, 1 ]
[]
[]
[ "naming_conventions", "python" ]
stackoverflow_0007785071_naming_conventions_python.txt
Q: lxml findall and reverse order How to print all findall elements in reverse order ? labels = tree.findall(label) for label in labels: print etree.tostring(label) A: There is a reversed function: for label in reversed(labels) A: or maybe something like this: labels = ET.findall(label) alist =[] for one_la...
lxml findall and reverse order
How to print all findall elements in reverse order ? labels = tree.findall(label) for label in labels: print etree.tostring(label)
[ "There is a reversed function:\nfor label in reversed(labels)\n", "or maybe something like this:\nlabels = ET.findall(label)\nalist =[]\nfor one_label in labels:\n alist.append(etree.tostring(one_label))\n\nprint sorted(alist, reverse=True) \n\n" ]
[ 4, 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0007784961_lxml_python.txt
Q: Python OO-pygame cannon game. Unable to get the cannonball to move I am attempting to work on a homework for my Software Engineering class currently. We are creating a object oriented cannon game. We just need to get the cannon created and fire a cannon ball. Currently I can get my code to create a cannonball at ...
Python OO-pygame cannon game. Unable to get the cannonball to move
I am attempting to work on a homework for my Software Engineering class currently. We are creating a object oriented cannon game. We just need to get the cannon created and fire a cannon ball. Currently I can get my code to create a cannonball at the muzzle point of the Cannon, but the move function unfortunatly does ...
[ "There are a couple of problems with the framework you have posted here:\n\nThe methods and variables are not indented into the CannonBall class and thus are part of the global scope, not the class itself.\nThe move method should not have a while loop, instead, try and structure your game similar to the following c...
[ 1, 0, 0 ]
[]
[]
[ "move", "pygame", "python" ]
stackoverflow_0007654699_move_pygame_python.txt
Q: How do I use a Radiobutton to input a set integer to a variable? I have used the line of code below to input a variable for "BAI_var1" in a multiple choice command line software. BAI_var1 = input ("Please enter 0 for not at all, 1 for somewhat, 2 for moderatly or 3 for a lot:") Here is my Graphic User Interface:...
How do I use a Radiobutton to input a set integer to a variable?
I have used the line of code below to input a variable for "BAI_var1" in a multiple choice command line software. BAI_var1 = input ("Please enter 0 for not at all, 1 for somewhat, 2 for moderatly or 3 for a lot:") Here is my Graphic User Interface: from Tkinter import * import time class App: def __init_...
[ "Use a dictionary to map the integer values to the strings they represent:\nchoices = {\n 1: \"not at all\",\n 2: \"somewhat\",\n 3: \"moderately\",\n 4: \"a lot\"\n}\n\nYou can then use this to create the UI:\nfor (i in sorted(choices.keys())):\n label = \"%s - %s\" % (i, choices[i])\n rb=Radiobu...
[ 0 ]
[]
[]
[ "input", "python", "radio_button", "string", "tkinter" ]
stackoverflow_0007781448_input_python_radio_button_string_tkinter.txt
Q: PyDev Auto-Complete Doesn't Work Today I reinstalled my OS (Ubuntu 11.10) and installed Django and PyDev. I ran one of my programs that import Django framework. It works, but PyDev doesn't detect my project, Django, Simple Django Captcha and most Python libraries. What can I do to fix this problem? Actually, I mus...
PyDev Auto-Complete Doesn't Work
Today I reinstalled my OS (Ubuntu 11.10) and installed Django and PyDev. I ran one of my programs that import Django framework. It works, but PyDev doesn't detect my project, Django, Simple Django Captcha and most Python libraries. What can I do to fix this problem? Actually, I must say I configured my PYTHONPATH in Py...
[ "New versions of PyDev should have Django integration. Try looking here.\nAlso, it might help defining those libraries as Forced Builtins. I had to use it to get PyQt auto-complete working.\n", "I had the some problem when I upgraded my Ubuntu, it was fixed when i installed the aptana studio package fully.\n" ]
[ 1, 0 ]
[]
[]
[ "django", "pydev", "python" ]
stackoverflow_0007784555_django_pydev_python.txt