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: Adjustment to a shortest path algorithm for a datastructures & algorithms class in college we have to implement an algorithm presented in a paper. The paper can be found here. So i fullly implemented the algorithm, with still some errors left (but that's not really why I'm asking this question, if you want to see ...
Adjustment to a shortest path algorithm
for a datastructures & algorithms class in college we have to implement an algorithm presented in a paper. The paper can be found here. So i fullly implemented the algorithm, with still some errors left (but that's not really why I'm asking this question, if you want to see how I implemented it thus far, you can find i...
[ "Your best bet in cases like this is to think like a researcher: Research in general and Computer Science research specifically is about incremental improvement, one person shows that they can compute something faster using Dijkstra's Algorithm and then later they, or someone else, show that they can compute the sa...
[ 2 ]
[]
[]
[ "dijkstra", "python", "shortest_path" ]
stackoverflow_0004420926_dijkstra_python_shortest_path.txt
Q: Python: Better way/module to manipulate image quality What can you advise me to use to manipulate images using python? So long for now I consider GD and Image libraries. Sultan A: Try Python Imaging Library. Easy to understand with good documentation. What they say about themselves: The Python Imaging Library a...
Python: Better way/module to manipulate image quality
What can you advise me to use to manipulate images using python? So long for now I consider GD and Image libraries. Sultan
[ "Try Python Imaging Library. Easy to understand with good documentation.\nWhat they say about themselves:\n\nThe Python Imaging Library adds image processing capabilities to your Python interpreter.\nThis library provides extensive file format support, an efficient internal representation, and fairly powerful image...
[ 1 ]
[]
[]
[ "graphics", "image", "python" ]
stackoverflow_0004421180_graphics_image_python.txt
Q: can not find the function on disk even though it is being imported django manage.py imports a function execute_manager using from django.core.management import execute_manager but when i browse to django->core->management directory there is no file present as execute_manager why is that so? A: Because it's defin...
can not find the function on disk even though it is being imported
django manage.py imports a function execute_manager using from django.core.management import execute_manager but when i browse to django->core->management directory there is no file present as execute_manager why is that so?
[ "Because it's defined in __init__.py.\nPython Tutorial, §6.4, \"Packages\"\n" ]
[ 5 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004421200_django_python.txt
Q: Model relationship to html template I've been struggling for this issue for a few hours - I know there's probably a simple solution that I'm overlooking. I have a one to many relationship with my models. I have need to return all rows of one object with the rows for the related object. In a sense I have this: obj...
Model relationship to html template
I've been struggling for this issue for a few hours - I know there's probably a simple solution that I'm overlooking. I have a one to many relationship with my models. I have need to return all rows of one object with the rows for the related object. In a sense I have this: object object object_relationship.prope...
[ "You might not need to worry too much about this, acutally... look at these models:\nclass Venue(base.NamedEntity, HasPerformances, HasUrl, HasLocation):\n city = db.ReferenceProperty(City, collection_name='venues')\n url = db.StringProperty(required=True, validator=validators.validate_url)\n location = db...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0004420381_google_app_engine_google_cloud_datastore_python.txt
Q: sort tuples in lists in python i was wondering if there was any simple way around sorting tuples in lists in python, for instance if i have a list: list01 = ([a,b,c],[b,a,d],[d,e,c],[a,f,d]) and i sorted it, i would get: ([a,b,c],[a,b,d],[c,d,e],[a,d,f])? or even: ([a,b,c],[a,b,d],[a,d,f],[c,d,e]) if that's ea...
sort tuples in lists in python
i was wondering if there was any simple way around sorting tuples in lists in python, for instance if i have a list: list01 = ([a,b,c],[b,a,d],[d,e,c],[a,f,d]) and i sorted it, i would get: ([a,b,c],[a,b,d],[c,d,e],[a,d,f])? or even: ([a,b,c],[a,b,d],[a,d,f],[c,d,e]) if that's easier Thanx in advance:)
[ ">>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])\n>>> map(sorted, list01)\n[['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f']]\n>>> sorted(map(sorted, list01))\n[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'd', 'f'], ['c', 'd', 'e']]\n\n", "Simple as that...\nlist01 = (['a','b'...
[ 6, 2, 2 ]
[]
[]
[ "list", "python", "sorting", "tuples" ]
stackoverflow_0004421410_list_python_sorting_tuples.txt
Q: interface web-browser bot helper I have the interface with many controls which I need to set, the problem is that there are too many controls I need to set data in and click (whey work via ajax on https page). I want to write some helper which is integrated in my browser and do route clicking on certain page for m...
interface web-browser bot helper
I have the interface with many controls which I need to set, the problem is that there are too many controls I need to set data in and click (whey work via ajax on https page). I want to write some helper which is integrated in my browser and do route clicking on certain page for me. It's Preferable to do this componen...
[ "I would first try doing this with mechanize. \nIf the web page needs to execute javascript, you could \n\nstudy the javascript to figure out\nwhat it does and mimick it with\nPython code (perhaps hard),\nuse TamperData or similar app\nto inspect headers and post\nparameters.\nuse Firebug or similar app to\ninspect...
[ 2 ]
[]
[]
[ "bots", "browser", "helper", "python" ]
stackoverflow_0004421537_bots_browser_helper_python.txt
Q: How to scrape the images from this javascript website? link text This is a link from a digital book library.There are forward and backward buttons to see next and previous page.I want to download these pictures automatically. I have once used urllib in python but the website baned it soon. I just want to download ...
How to scrape the images from this javascript website?
link text This is a link from a digital book library.There are forward and backward buttons to see next and previous page.I want to download these pictures automatically. I have once used urllib in python but the website baned it soon. I just want to download this book for study purpose so can anyone recommend me some ...
[ "wget is an excellent web spider \nhttp://linux.die.net/man/1/wget\n", "That site uses Javascript, so you can't easily scrape it with Python. Two suggestions:\n\nWork out what requests are being made when clicking the next button. You can do this with a tool like firebug. You might then find you can scrape it wit...
[ 0, 0, 0 ]
[]
[]
[ "python", "scripting", "web_crawler" ]
stackoverflow_0004405266_python_scripting_web_crawler.txt
Q: Which key-value store has decent twisted API (nonblocking)? I need a reliable K-V storage to be run in network. Main requirements: Network connectivity has nonblocking twisted API be reliable, production ready. No data loss write performance is more important than read performance support for distributed operatio...
Which key-value store has decent twisted API (nonblocking)?
I need a reliable K-V storage to be run in network. Main requirements: Network connectivity has nonblocking twisted API be reliable, production ready. No data loss write performance is more important than read performance support for distributed operation and failover would be great (So I just specify list of nodes) j...
[ "MongoDB sounds like a really good fit: http://api.mongodb.org/python/1.8.1%2B/index.html\nI haven't really played with Twisted yet but Mongo fulfils all of your listed requirements.\n", "You could also Redis, with https://github.com/deldotdr/txRedis. redis is super fast, the only inconveninet is that it is memor...
[ 1, 1 ]
[]
[]
[ "key_value_store", "nosql", "python", "twisted" ]
stackoverflow_0003526353_key_value_store_nosql_python_twisted.txt
Q: What are common strategies for updating python programs? I have a Windows program that I made with python and py2exe. I'd like to create an updating feature so that the software can be readily updated. What are common ways of going about this? A: If you think your code might benefit others, you could put it up...
What are common strategies for updating python programs?
I have a Windows program that I made with python and py2exe. I'd like to create an updating feature so that the software can be readily updated. What are common ways of going about this?
[ "If you think your code might benefit others, you could put it up on PyPI. Then having different versions is just updating your package, or telling your clients to use easy_install to get the latest version. This doesn't push updates, though.\nYou can try Esky, which is an auto-update framework for managing differe...
[ 3, 1 ]
[]
[]
[ "py2exe", "python", "windows_7" ]
stackoverflow_0004406078_py2exe_python_windows_7.txt
Q: Unicode with active_directory I'm using the active_directory module, and trying to print a list of the users. My code is: import active_directory as ad users = ad.AD_Object("LDAP://OU=Home, DC=dome, DC=net") for user in users.search(objectCategory="Person"): print str(user) It prints some of the users until i...
Unicode with active_directory
I'm using the active_directory module, and trying to print a list of the users. My code is: import active_directory as ad users = ad.AD_Object("LDAP://OU=Home, DC=dome, DC=net") for user in users.search(objectCategory="Person"): print str(user) It prints some of the users until it meets an unicode username. Then i...
[ "Try:\nprint user.decode('utf-8')\n\n" ]
[ 1 ]
[]
[]
[ "active_directory", "python" ]
stackoverflow_0004421836_active_directory_python.txt
Q: Python, probability My code is next: with open("test.txt") as f_in: for line in f_in: for char in line: frequencies[char] += 1 list= [(count, char) for char, count in frequencies.iteritems()] This code open test.txt, read every line and "list" sign into form for example: [(3, 'a'),..........
Python, probability
My code is next: with open("test.txt") as f_in: for line in f_in: for char in line: frequencies[char] += 1 list= [(count, char) for char, count in frequencies.iteritems()] This code open test.txt, read every line and "list" sign into form for example: [(3, 'a'),.........]. This means that in w...
[ "If frequencies = {\"a\": 3, \"b\": 4} then frequencies.values() gives us [3, 4] and we can calculate the sum:\ntotal = float(sum(frequencies.values()))\n\nand then the probabilities:\nprobs = [(count / total, char) for char, count in frequencies.iteritems()]\n\nNote that Python returns an integer when dividing two...
[ 1, 1, 0 ]
[]
[]
[ "char", "line", "list", "probability", "python" ]
stackoverflow_0004422174_char_line_list_probability_python.txt
Q: tuple checking in python i've written a small program: def check(xrr): """ goes through the list and returns True if the list does not contain common pairs, IE ([a,b,c],[c,d,e]) = true but ([a,b,c],[b,a,c]) = false, note the lists can be longer than 2 tuples""" x = xrr[:] #sorting the tuples ...
tuple checking in python
i've written a small program: def check(xrr): """ goes through the list and returns True if the list does not contain common pairs, IE ([a,b,c],[c,d,e]) = true but ([a,b,c],[b,a,c]) = false, note the lists can be longer than 2 tuples""" x = xrr[:] #sorting the tuples sorted(map(sorted,x)) f...
[ "I would recommend using a set for this:\ndef check(xrr):\n s = set()\n for t in xrr:\n u = tuple(sorted(t))\n if u in s:\n return False\n s.add(u)\n return True\n\nThis way, you don't need to sort the whole list and you stop when the first duplicate is found.\nThere are seve...
[ 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0004422092_python_tuples.txt
Q: Tips for making a fraction calculator code more optimized (faster and using less memory) Basicly, what I need for the program to do is to act a as simple fraction calculator (for addition, subtraction, multiplication and division) for the a single line of input, for example: -input: 1/7 + 3/5 -output: 26/35 My ini...
Tips for making a fraction calculator code more optimized (faster and using less memory)
Basicly, what I need for the program to do is to act a as simple fraction calculator (for addition, subtraction, multiplication and division) for the a single line of input, for example: -input: 1/7 + 3/5 -output: 26/35 My initial code: import sys def euclid(numA, numB): while numB != 0: numRem = numA % nu...
[ "Probably the biggest improvement you could make would be to use Python (2.6)'s fractions library:\n>>> import fractions\n>>> fractions.Fraction(1,7) + fractions.Fraction(\"3/5\")\nFraction(26, 35)\n\n", "I'd create a class containing numerator and denominator fields (both integers) and implementing __add__, __su...
[ 9, 5, 1, 1, 1, 0 ]
[]
[]
[ "optimization", "performance", "python" ]
stackoverflow_0002985797_optimization_performance_python.txt
Q: Eventdriven Webframework for Python Hy, is there any event-drive/event-based Webframework for Python? I mean something like NitroGen is for erlang. You simply get some components you add to a website (like a button) and accociate a python-function to the "onclick"-handler of the button and it gets executed. It sho...
Eventdriven Webframework for Python
Hy, is there any event-drive/event-based Webframework for Python? I mean something like NitroGen is for erlang. You simply get some components you add to a website (like a button) and accociate a python-function to the "onclick"-handler of the button and it gets executed. It should generate all needed html and js core ...
[ "KSS (Kinetic Style Sheets) provides something similar to NitroGen. Although KSS differs from NitroGen in that it defines a simple domain-specific language (DSL) for declaring how JavaScript events should be bound to an HTML page on the client side, and this DSL can also declare that events need to trigger a server...
[ 3, 1, 1, 1, 0 ]
[ "twisted matrix?\n" ]
[ -1 ]
[ "frameworks", "python" ]
stackoverflow_0001066413_frameworks_python.txt
Q: Use mechanize to log into megaupload I am attempting to use the following code to log into megaupload. My question is, how do i that it successfully logged in? I print out the current URL at the end of the code, but when i run the script it just returns www.megaupload.com. import mechanize import cookielib from Be...
Use mechanize to log into megaupload
I am attempting to use the following code to log into megaupload. My question is, how do i that it successfully logged in? I print out the current URL at the end of the code, but when i run the script it just returns www.megaupload.com. import mechanize import cookielib from BeautifulSoup import BeautifulSoup import ht...
[ "Search the error message in the response body:\n\"Username and password do not match\" in br.response().read()\n\nOr check if you got the expected cookie (simple example, tweak as needed):\nany(c.domain == \".megaupload.com\" and c.name == \"user\" for c in cj)\n\n" ]
[ 3 ]
[]
[]
[ "authentication", "mechanize", "python" ]
stackoverflow_0004422389_authentication_mechanize_python.txt
Q: Compiling Python to C using Cython I'm trying to compile python source code foo.py to C using cython. In foo.py: print "Hello World" The command I'm running is cython foo.py. The problem is that when compiling foo.c using gcc, I get the error: undefined reference to 'main'. A: when converting the code from py...
Compiling Python to C using Cython
I'm trying to compile python source code foo.py to C using cython. In foo.py: print "Hello World" The command I'm running is cython foo.py. The problem is that when compiling foo.c using gcc, I get the error: undefined reference to 'main'.
[ "when converting the code from python to c (using Cython) it converts it to c code which can be compiled into a shared object.\nin order to make it executable, you should add \"--embed\" to cython conversion command. this flag adds the 'main' function you need, so you could compile the c code into executable file.\...
[ 25, 10, 0 ]
[]
[]
[ "c", "cython", "gcc", "linux", "python" ]
stackoverflow_0004421832_c_cython_gcc_linux_python.txt
Q: Edit files with template I have a lot of files which consist of some string. I have to remove it from all of files. How can I do this faster? Any ideas, prefer python-script, for example. Thanks. A: sed -i "s/YOUR_STRING//g" * /* or */ for file in `grep YOUR_STRING -l *`; do sed -i "s/YOUR_STRING//g" $file; don...
Edit files with template
I have a lot of files which consist of some string. I have to remove it from all of files. How can I do this faster? Any ideas, prefer python-script, for example. Thanks.
[ "sed -i \"s/YOUR_STRING//g\" *\n\n/* or */\nfor file in `grep YOUR_STRING -l *`; do sed -i \"s/YOUR_STRING//g\" $file; done\n\nfirst method will blindly remove the YOUR_STRING for all files \nsecond method probably will break if too many files matched\nupdated : is not a python solution, ping me if you dislike and...
[ 1, 1 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0004422451_python_replace.txt
Q: using numpy in cython: defining ndarray datatype/ndims I'm trying to write some cython code to do computations with numpy arrays. Cython seems to not like the [] used in all the examples I've seen to define the datatype and number of dimensions. For example, I have a file test.pyx: cimport numpy as np import nu...
using numpy in cython: defining ndarray datatype/ndims
I'm trying to write some cython code to do computations with numpy arrays. Cython seems to not like the [] used in all the examples I've seen to define the datatype and number of dimensions. For example, I have a file test.pyx: cimport numpy as np import numpy as np ctypedef np.ndarray[np.float64_t, ndim=2] mymatri...
[ "Put the type information in the declaration of the function, as in:\ndef hat (ndarray[np.float64_t, ndim=2] x):\n a = np.zeros((3,3));\n a[0,1] = x[2,0];\n etc.\n\n", "I think you cannot do it directly: you have to check the shape and type in the function\nassert x.shape[0] == 2\nassert x.dtype == np.f...
[ 3, 0 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0003379297_cython_python.txt
Q: Problem with django's call_command inside a Thread I would to execute the django's call_method inside a Thread. This is the sample code: import sys sys.path.append("/my/django/project/path/") import threading import time # Import my django project configuration settings from django.core.management import setup_e...
Problem with django's call_command inside a Thread
I would to execute the django's call_method inside a Thread. This is the sample code: import sys sys.path.append("/my/django/project/path/") import threading import time # Import my django project configuration settings from django.core.management import setup_environ from mydjangoprojectname import settings setup_e...
[ "I found a solution (Chris Morgan was right). This code works as I want:\nimport sys\nsys.path.append(\"/my/django/project/path/\")\nimport threading\n\n# Import my django project configuration settings\nfrom django.core.management import setup_environ, ManagementUtility\n\nfrom mydjangoprojectname import settings\...
[ 5, 0 ]
[]
[]
[ "django", "multithreading", "pyqt", "pyside", "python" ]
stackoverflow_0004420099_django_multithreading_pyqt_pyside_python.txt
Q: Reducing complexity of following code What I wanted to do was to search in a list and remove a value . So I wrote the following code for x in range(10): if x in list1: list1.remove(x) Does this function of order ~ (n^2) since first it looks for the value and then it deletes and pushes the rest of the val...
Reducing complexity of following code
What I wanted to do was to search in a list and remove a value . So I wrote the following code for x in range(10): if x in list1: list1.remove(x) Does this function of order ~ (n^2) since first it looks for the value and then it deletes and pushes the rest of the values backwards ?? Also is there a way to tur...
[ "Use:\nL = [x for x in L if x not in removal_list]\n\nremoval_list can be any container, but if you use a set() or a frozenset() you will achieve O(n) (with n = len(L)).\n", "This sounds like a job for filter():\n>>> filter(lambda x: not x in (4, 5, 7), xrange(10))\n[0, 1, 2, 3, 6, 8, 9]\n\nUpdate: one more examp...
[ 5, 2, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004421500_python.txt
Q: Any libraries/modules for file management in python? Trying to find out if there any good modules which allow constant monitoring of a directory and as soon as a new file is in there, a number of functions are intiated? Also actions should not be done on partly transfered files which are coming in via FTP. A: I'...
Any libraries/modules for file management in python?
Trying to find out if there any good modules which allow constant monitoring of a directory and as soon as a new file is in there, a number of functions are intiated? Also actions should not be done on partly transfered files which are coming in via FTP.
[ "I'm implementing a cross-platform library called watchdog which\nmay be what you are looking for. It's available at \nhttp://github.com/gorakhargosh/watchdog\nHTH.\n=)\n", "You are looking for file system events modules.\nWhich OS are you running?\n(disclaimer: I'm maintaining those two modules)\n\nOn Linux, you...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001332978_python.txt
Q: How to find x in a string in Python I was wondering how to go about finding a string you don't know what is, in a string. I am writing an IRC bot and i need this function. I want to be able to write: !greet Greg and then my bot is supposed to say "Hi, Greg!". So what comes after greet is variable. And if i wrote !...
How to find x in a string in Python
I was wondering how to go about finding a string you don't know what is, in a string. I am writing an IRC bot and i need this function. I want to be able to write: !greet Greg and then my bot is supposed to say "Hi, Greg!". So what comes after greet is variable. And if i wrote !greet Matthew it would say "Hi, Matthew!"...
[ "if command.lower().startswith('!greet '):\n put('Hi, ' + command[7:].strip() + '!')\n\n'!greet Greg' -> [ put()s 'Greg' ]\n'!Greet Fred ' -> [ put()s 'Fred' ]\n'!hello John' -> [ nothing ]\n\n", "import re\n...\ninput = '!greet Greg'\nm = re.match(r'!greet\\s+(.*)', input)\nif m:\n print 'Hi, %s!' % m.gro...
[ 3, 3, 3, 1 ]
[ "if \"Greg\" in greet:\n doSomething(\"Hi Greg\")\nthe key is that strings take the in operator\n" ]
[ -1 ]
[ "irc", "python" ]
stackoverflow_0004422948_irc_python.txt
Q: Computing filter(b,a,x,zi) using FFTs I would like to try to compute y=filter(b,a,x,zi) and dy[i]/dx[j] using FFTs rather than in the time domain for possible speedup in a GPU implementation. I am not sure it's possible, particularly when zi is non-zero. I looked through how scipy.signal.lfilter in scipy and fil...
Computing filter(b,a,x,zi) using FFTs
I would like to try to compute y=filter(b,a,x,zi) and dy[i]/dx[j] using FFTs rather than in the time domain for possible speedup in a GPU implementation. I am not sure it's possible, particularly when zi is non-zero. I looked through how scipy.signal.lfilter in scipy and filter in octave are implemented. They are bot...
[ "You can reduce the error in your existing implementation by replacing P = T + MN - 1 with P = T + 2*MN - 1. This is purely intuitive, but it seems to me that the division of bf and af will require 2*MN terms, due to wraparound.\nC.S. Burrus has a pretty terse writeup of how to regard filtering, whether FIR or IIR...
[ 2, 1, 1 ]
[]
[]
[ "filter", "matlab", "octave", "python", "signal_processing" ]
stackoverflow_0004419993_filter_matlab_octave_python_signal_processing.txt
Q: good numerical solution for LDA transformation I'm computing an LDA (linear discriminant analysis) transform, for an application I'm working on, and I've been following these notes (starting at page 36, especially slide 47 in green). I'm doing this in Python (with numpy and scipy), and this is what I have come up ...
good numerical solution for LDA transformation
I'm computing an LDA (linear discriminant analysis) transform, for an application I'm working on, and I've been following these notes (starting at page 36, especially slide 47 in green). I'm doing this in Python (with numpy and scipy), and this is what I have come up with: import numpy as np from scipy.linalg import sq...
[ "Try eigh instead of eig. Since Sigma^{-1/2} B_0 Sigma^{1/2} is symmetric, use an adapted routine.\nAlso, beware of using the right algorithm when computing B_0. See http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Two-pass_algorithm for a simpler case (that you can adapt here).\n" ]
[ 2 ]
[]
[]
[ "math", "numerical_methods", "numpy", "python", "scipy" ]
stackoverflow_0004423069_math_numerical_methods_numpy_python_scipy.txt
Q: How can I run 2 loops simultaneously in python? I have an application (Gtk) that has an embedded server (using circuits). Both components (The GUI and Server) have infinite loops. How can I run both loops simultaneously ? I also need the server loop to end when the gtk loop ends. The code for the example server ...
How can I run 2 loops simultaneously in python?
I have an application (Gtk) that has an embedded server (using circuits). Both components (The GUI and Server) have infinite loops. How can I run both loops simultaneously ? I also need the server loop to end when the gtk loop ends. The code for the example server from circuits.web import Server, Controller import os...
[ "You could use the multiprocessing module to do this:\nfrom multiprocessing import Process\n\ndef run_app():\n ... run the app ...\n\ndef run_server():\n ... run the server ...\n\ndef main():\n app = Process(target=run_app)\n app.start()\n\n server = Process(target=run_server)\n server.start()\n\n...
[ 2, 1 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0004423469_gtk_python.txt
Q: matplotlib MemoryError on pcolorfast The Problem: I'm currently loading column data from text files into numpy arrays, and then plotting them and saving the resulting image. Because the values will always lie on an equally spaced grid, it seemed an appropriate time to use pcolorfast. Each array is necessarily sq...
matplotlib MemoryError on pcolorfast
The Problem: I'm currently loading column data from text files into numpy arrays, and then plotting them and saving the resulting image. Because the values will always lie on an equally spaced grid, it seemed an appropriate time to use pcolorfast. Each array is necessarily square, usually between 1024x1024 and 8192x8...
[ "Caveats:\n\nThere might be a better way to deal\nwith this memory problem that I don't\nknow about.\nI haven't been able to reproduce this\nerror. When I use\nmatplotlib.cbook.report_memory() my\nmemory usage seems to level out as\nexpected.\n\nDespite the caveats, I thought I'd mention a general, cheap method of ...
[ 2 ]
[]
[]
[ "arrays", "matplotlib", "memory_management", "numpy", "python" ]
stackoverflow_0004423515_arrays_matplotlib_memory_management_numpy_python.txt
Q: Python GUI(tkinter; pygtk+glade), py2exe I'm new with python programming and GUI. I search on internet about GUI programming and see that there are a lot of ways to do this. I see that easiest way for GUI in python might be tkinter(which is included in Python, and it's just GUI library not GUI builder)? I also rea...
Python GUI(tkinter; pygtk+glade), py2exe
I'm new with python programming and GUI. I search on internet about GUI programming and see that there are a lot of ways to do this. I see that easiest way for GUI in python might be tkinter(which is included in Python, and it's just GUI library not GUI builder)? I also read a lot about GLADE+PyGTK(and XML format), wha...
[ "I really like PyQt bindings for Qt library.\nWhat is PyQt?\nQt itself is a very nice framework - rich, powerfull, elegant (for my taste, at least). And PyQt does a very nice job of exposing that functionality to a scripting environment.\nPlus, there is a very nice book about PyQt development - Rapid GUI Programmin...
[ 0, 0 ]
[]
[]
[ "glade", "py2exe", "pygtk", "python", "tkinter" ]
stackoverflow_0004424004_glade_py2exe_pygtk_python_tkinter.txt
Q: Install h5py in Mac OS X 10.6.3 I'm trying to install h5py in Mac OS X 10.6.3. First I installed HDF5 1.8, which used the following commands: ./configure \ --prefix=/Library/Frameworks/Python.framework/Versions/Current \ --enable-shared \ --enable-production \ --enable-threadsafe \ CPPFLAGS=-I/Library/Frameworks/P...
Install h5py in Mac OS X 10.6.3
I'm trying to install h5py in Mac OS X 10.6.3. First I installed HDF5 1.8, which used the following commands: ./configure \ --prefix=/Library/Frameworks/Python.framework/Versions/Current \ --enable-shared \ --enable-production \ --enable-threadsafe \ CPPFLAGS=-I/Library/Frameworks/Python.framework/Versions/Current/incl...
[ "I just came across a similar error while trying to build a Python extension module on Mac OS X with the Intel C/C++ compiler. To fix the \"undefined symbols: _main\" error I had to add the following to the linker command: -bundle -undefined dynamic_lookup\nYou can do a 'man ld' to find out what the specific linker...
[ 1, 0 ]
[]
[]
[ "h5py", "hdf5", "macos", "python" ]
stackoverflow_0002869790_h5py_hdf5_macos_python.txt
Q: Using Beautiful Soup to strip html tags from a string Does anyone have some sample code that illustrates how to use Python's Beautiful Soup to strip all html tags, except some, from a string of text? I want to strip all javascript and html tags everything except: <a></a> <b></b> <i></i> And also things like: <a o...
Using Beautiful Soup to strip html tags from a string
Does anyone have some sample code that illustrates how to use Python's Beautiful Soup to strip all html tags, except some, from a string of text? I want to strip all javascript and html tags everything except: <a></a> <b></b> <i></i> And also things like: <a onclick=""></a> Thanks for helping -- I couldn't find much ...
[ "import BeautifulSoup\n\ndoc = '''<html><head><title>Page title</title></head><body><p id=\"firstpara\" align=\"center\">This is <i>paragraph</i> <a onclick=\"\">one</a>.<p id=\"secondpara\" align=\"blah\">This is <i>paragraph</i> <b>two</b>.</html>'''\nsoup = BeautifulSoup.BeautifulSoup(doc)\n\nfor tag in soup.rec...
[ 8 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0004423953_beautifulsoup_python.txt
Q: simple python list comprehension question i am trying to select the elements of a list without the very first element. the following code works but it kinda look ugly to me [s[i] for i in range(len(s)) if i>0] is there a better way to write it? thanks A: Use the slicing notation: s[1:] Alternatively, you can a...
simple python list comprehension question
i am trying to select the elements of a list without the very first element. the following code works but it kinda look ugly to me [s[i] for i in range(len(s)) if i>0] is there a better way to write it? thanks
[ "Use the slicing notation:\ns[1:]\n\nAlternatively, you can avoid copying the list thus:\nitertools.islice(s, 1, None)\n\nThe result isn't a list — it doesn't support random access, for instance — but you can pass it to anything that accepts an iterator.\n", "Wouldn't s[1:] be correct?\n" ]
[ 11, 2 ]
[]
[]
[ "list_comprehension", "python" ]
stackoverflow_0004424283_list_comprehension_python.txt
Q: Are there reserved kwargs for python's dict constructor? When using the kwarg-style dict initialization: In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} for some reason, defining the key 'from' raises a syntax error: In [4]: dict(to=0, from=1) ---------------------------------------------------------...
Are there reserved kwargs for python's dict constructor?
When using the kwarg-style dict initialization: In [3]: dict(a=1, b=2, c=3) Out[3]: {'a': 1, 'b': 2, 'c': 3} for some reason, defining the key 'from' raises a syntax error: In [4]: dict(to=0, from=1) ------------------------------------------------------------ File "<ipython console>", line 1 dict(to=0, from=1...
[ "from is used in imports.\nPython Language Reference, §2.3.1, \"Keywords\"\nNote that you can still use kwarg expansion to get them through though.\n", "from, like a handful of other tokens, are keywords/reserved words in Python (from specifically is used when importing a few hand-picked objects from a module int...
[ 5, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004424342_python.txt
Q: Running shell commands from bytes objects in python 3.1 (Or writing UTF-8 mp3 tags in python 3.1) I'm writing a script which uses .CUE files to split monolithic music files into individual tracks, then encodes them in MP3 along with correct tags from the CUE. It's all working, but unfortunately the tags (applied s...
Running shell commands from bytes objects in python 3.1 (Or writing UTF-8 mp3 tags in python 3.1)
I'm writing a script which uses .CUE files to split monolithic music files into individual tracks, then encodes them in MP3 along with correct tags from the CUE. It's all working, but unfortunately the tags (applied simply through including them with lame's command line arguments) reliably show up as gibberish in iTune...
[ "If you choose to use tagging library you may look at eyeD3; then you could set utf-8 encoded tags as follows:\nimport eyeD3\n\ntag = eyeD3.Tag ('file.mp3')\ntag.setVersion (eyeD3.ID3_V2_4)\ntag.setTextEncoding (eyeD3.UTF_8_ENCODING)\ntag.setArtist ('artist')\ntag.setAlbum ('album')\ntag.setTitle ('title')\ntag.upd...
[ 1 ]
[]
[]
[ "mp3", "python", "python_3.x", "unicode" ]
stackoverflow_0004424360_mp3_python_python_3.x_unicode.txt
Q: Error importing module _md5, and relevant RPM I have a python script that used to run, although since moving servers at work it now throws up a strange error: >>> import _md5 ImportError: No module named _md5 The general setup is all correct, as is my python path and seemingly everything else. I was told that...
Error importing module _md5, and relevant RPM
I have a python script that used to run, although since moving servers at work it now throws up a strange error: >>> import _md5 ImportError: No module named _md5 The general setup is all correct, as is my python path and seemingly everything else. I was told that I need to install the relevant RPM for this to wor...
[ "Based on extra bit of information from the OP, they use Python 2.5+ on the new server.\nSuggested remedy is to use standard hashlib module. Which provides MD5 hash implementation among other things.\n", "Install openssl-devel and rebuild.\nOr better yet, build your own Python package and deploy everywhere.\n" ]
[ 2, 1 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0004424540_linux_python.txt
Q: How to respond to tkinter events? I'm doing some work with GUI in python. I'm using the Tkinter library. I need a button, which will open a .txt file and do this bit of processing: frequencies = collections.defaultdict(int) # <----------------------- with open("test.txt") as f_in: for line...
How to respond to tkinter events?
I'm doing some work with GUI in python. I'm using the Tkinter library. I need a button, which will open a .txt file and do this bit of processing: frequencies = collections.defaultdict(int) # <----------------------- with open("test.txt") as f_in: for line in f_in: for char in line: ...
[ "The main problem was tkFileDialog.askopenfile() returns an open file rather than a file name. This following seemed to be more-or-less working for me:\nfrom Tkinter import *\nimport tkFileDialog, Tkconstants,collections\n\nroot = Tk()\nroot.title(\"TEST\")\nroot.geometry(\"800x600\")\n\ndef openFile():\n f_in =...
[ 2, 1, 0 ]
[]
[]
[ "button", "python", "tkinter" ]
stackoverflow_0004424469_button_python_tkinter.txt
Q: In plain English, what are the difference between Python, Perl, and Ruby when it comes to translating them to another language? UPDATE: Received a lot of great info, thanks -- went back to read my question again, based on some of the answers stating that it's possible to do XYZ, which is not the question. the core...
In plain English, what are the difference between Python, Perl, and Ruby when it comes to translating them to another language?
UPDATE: Received a lot of great info, thanks -- went back to read my question again, based on some of the answers stating that it's possible to do XYZ, which is not the question. the core of the question is this: "Main focus of this question is finding an answer in plain English of why Python, Perl, and Ruby are what t...
[ "It isn't that it's impossible to translate them, since any Turing-complete language can emulate any other Turing-complete language. The problem is generating an efficient translation, since some languages support features that are either very difficult or very complex to emulate in another.\n", "Your question ma...
[ 10, 7, 4, 2 ]
[]
[]
[ "perl", "python", "ruby", "translation" ]
stackoverflow_0004424668_perl_python_ruby_translation.txt
Q: Comparing two containers for identity of their contents I have a method that returns a set of objects, and I'm writing a unit test for this method. Is there a generic, tidy and idiomatic way of comparing these for identity (rather than equality)? Or do I need to write a suitable implementation myself? An example (...
Comparing two containers for identity of their contents
I have a method that returns a set of objects, and I'm writing a unit test for this method. Is there a generic, tidy and idiomatic way of comparing these for identity (rather than equality)? Or do I need to write a suitable implementation myself? An example (somewhat contrived to keep it simple): class Foo(object): ...
[ "The best I can come up with is:\n@staticmethod\ndef set_id(c):\n return set([id(e) for e in c])\n\ndef assertContentIdentity(self, a, b):\n self.assertEqual(set_id(a), set_id(b))\n\nHowever, this is specialised for sets and can't deal with nested containers.\n", "A simple, albeit not the most efficient, wa...
[ 0, 0, 0 ]
[]
[]
[ "containers", "identity", "python" ]
stackoverflow_0004424718_containers_identity_python.txt
Q: How can I get pip install's -I flag to work with a requirements file? I feel like there must be a way to do this, but for the life of me I can't figure out how: I want to run pip against a requirements file in a virtualenv so that no matter what packages are in the virtualenv before I run pip, the requirements fil...
How can I get pip install's -I flag to work with a requirements file?
I feel like there must be a way to do this, but for the life of me I can't figure out how: I want to run pip against a requirements file in a virtualenv so that no matter what packages are in the virtualenv before I run pip, the requirements file is totally fulfilled (including specific versions) after I run it. The pr...
[ "I figured out what the cause of my pip problems was. Long story short, source left over in the virtualenv's build directory was causing an error that made packages upgrades fail. What I actually should have been doing was clearing out that directory (which pip doesn't always do I guess) before running the pip inst...
[ 4 ]
[]
[]
[ "pip", "python", "requirements.txt", "virtualenv" ]
stackoverflow_0004420706_pip_python_requirements.txt_virtualenv.txt
Q: Unexpected behaviour with Python urllib I am tryint to consume a JSON response but I have one very weird behaviour. The end point is a Java app running on Tomcat. I want to load the following url http://opendata.diavgeia.gov.gr/api/decisions?count=50&output=json_full&from=1 Using Ruby open-uri I load the json. If...
Unexpected behaviour with Python urllib
I am tryint to consume a JSON response but I have one very weird behaviour. The end point is a Java app running on Tomcat. I want to load the following url http://opendata.diavgeia.gov.gr/api/decisions?count=50&output=json_full&from=1 Using Ruby open-uri I load the json. If I hit in in the browser I still get the resp...
[ "The server appears to need an 'Accept' header:\n>>> print urllib2.urlopen(\n... urllib2.Request(\n... \"http://opendata.diavgeia.gov.gr/api/decisions?count=50&output=json_full&from=1\",\n... headers={\"accept\": \"*/*\"})).read()[:200]\n{\"model\":{\"queryInfo\":{\"total\":117458,\"count\":50,\"order\":\...
[ 5, 0 ]
[]
[]
[ "api", "json", "python", "servlets" ]
stackoverflow_0004424839_api_json_python_servlets.txt
Q: Cipher text Letter Freq Substitution: Comparing 2 dictionaries' dict keys by value and altering a text I've had a look at similar topics, but no solution I can find exactly compares to what I'm trying to achieve. I have a cipher text that needs to undergo a simple letter substitution based on the frequency of each...
Cipher text Letter Freq Substitution: Comparing 2 dictionaries' dict keys by value and altering a text
I've had a look at similar topics, but no solution I can find exactly compares to what I'm trying to achieve. I have a cipher text that needs to undergo a simple letter substitution based on the frequency of each letter's occurrence in the text. I already have a function to normalise the text (lowercase, no none-letter...
[ "First off, note that it's very unlikely that the frequencies will give you an exact match, unless your message is very long. So you might need to do some manual tweaking to get the exact message. But if the frequencies are close enough...\nYou could get the keys of both dictionaries (letters), sorted by their valu...
[ 0, 0, 0 ]
[]
[]
[ "dictionary", "encryption", "letter", "python", "substitution" ]
stackoverflow_0004425131_dictionary_encryption_letter_python_substitution.txt
Q: AttributeError: Edge instance has no attribute 'vto' I'm trying to pickle a class instance containing two lists of another instances. The instances in the two lists have attributes that refer instances of each other. Here are the classes. class Graph: def __init__(self): self.vertices = {} self...
AttributeError: Edge instance has no attribute 'vto'
I'm trying to pickle a class instance containing two lists of another instances. The instances in the two lists have attributes that refer instances of each other. Here are the classes. class Graph: def __init__(self): self.vertices = {} self.edges = set() def __repr__(self): return "\n"...
[ "This Python issue may be the cause: http://bugs.python.org/issue1761028\n\"pickle - cannot unpickle circular deps with custom __hash__\"\n" ]
[ 3 ]
[]
[]
[ "pickle", "python" ]
stackoverflow_0004425472_pickle_python.txt
Q: Jinja2 returns "None" string for Google App Engine models Google App Engine models, likeso: from google.appengine.ext.db import Model class M(Model): name = db.StringProperty() Then in a Jinja2 template called from a Django view with an in instance of M passed in as m: The name of this M is {{ m.name }}. Wh...
Jinja2 returns "None" string for Google App Engine models
Google App Engine models, likeso: from google.appengine.ext.db import Model class M(Model): name = db.StringProperty() Then in a Jinja2 template called from a Django view with an in instance of M passed in as m: The name of this M is {{ m.name }}. When m is initialized without name being set, the following is pr...
[ "You might also want to consider using Jinja2's \"or\"...\nThe name of this M is {{ m.name or ''}}.\n\nIf bool(m.name) == False, this will show The name of this M is .\n\nIf m.name == False and you want to display it as the string \"False\", you can use Jinja2's \"default\" filter:\nThe name of this M is {{ m.name|...
[ 14, 1, 1 ]
[]
[]
[ "google_app_engine", "jinja2", "python" ]
stackoverflow_0002695180_google_app_engine_jinja2_python.txt
Q: How to add to AppEngine a WSGI middleware that modifies the body of the response Adding a middleware that only modifies the HTTP headers (like FirePython) is quite simple, but when you call webapp.WSGIApplication(environ, start_response) it returns [''] instead of an iterable with the body: def __call__(self, envi...
How to add to AppEngine a WSGI middleware that modifies the body of the response
Adding a middleware that only modifies the HTTP headers (like FirePython) is quite simple, but when you call webapp.WSGIApplication(environ, start_response) it returns [''] instead of an iterable with the body: def __call__(self, environ, start_response): ... response.wsgi_write(start_response) return [''] ...
[ "If you want to intercept writes to the body of the request, you need to define your own start_response and write functions, like so:\nclass Upperware(object):\n def __init__(self, app):\n self.wrapped_app = app\n\n def __call__(self, environ, start_response):\n def my_start_response(status, response_header...
[ 3 ]
[]
[]
[ "google_app_engine", "python", "wsgi" ]
stackoverflow_0004411061_google_app_engine_python_wsgi.txt
Q: Measuring a DiV's width, or grabbing JS variables in Python. I'm working on a website in Python. It's all going well so far, however: the template is made up of 300 pixel blocks. Picture it thus: OOOOO OOOOO OOOOO OOOOO Now, previously I had an enclosing div set to 1500px width. This meant that I could check whet...
Measuring a DiV's width, or grabbing JS variables in Python.
I'm working on a website in Python. It's all going well so far, however: the template is made up of 300 pixel blocks. Picture it thus: OOOOO OOOOO OOOOO OOOOO Now, previously I had an enclosing div set to 1500px width. This meant that I could check whether the object was divisible by 5 in order to generate more blocks...
[ "Doing it all in JavaScript is generally going to be the neatest way to do it. Make it so that it'll sort of work without JavaScript, and that JavaScript will fix it up (generate the empty blocks in JS). If they're the same size, you could also use a repeated background image to simulate the empty blocks, but that ...
[ 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0004425885_javascript_python.txt
Q: Python source file organization I'm starting a new Python project, and want to follow standard conventions as closely as possible. I've read that import statements should come first, for example. But I haven't found any conventions for things like putting all function definitions before or after all class definiti...
Python source file organization
I'm starting a new Python project, and want to follow standard conventions as closely as possible. I've read that import statements should come first, for example. But I haven't found any conventions for things like putting all function definitions before or after all class definitions. Are there any conventions for th...
[ "PEP8 is the Python style guide: http://www.python.org/dev/peps/pep-0008/\nImports come at the top of the file, though method-level imports are allowed.\nThere's no specific ordering to classes and functions. Use what makes sense.\n", "No, there's no convention for organization of functions and classes. However, ...
[ 7, 3 ]
[]
[]
[ "conventions", "python" ]
stackoverflow_0004426002_conventions_python.txt
Q: Pick a Random Word On a Single Line In Python? How would I pick a single line and pick all the words on that line and then print them to the screen using a set. This is what I have so far: import random test = [''' line 1 line 2 line 3 line 4 line 5 line 6 '''] print (random.choice(test)) A: I think this does e...
Pick a Random Word On a Single Line In Python?
How would I pick a single line and pick all the words on that line and then print them to the screen using a set. This is what I have so far: import random test = [''' line 1 line 2 line 3 line 4 line 5 line 6 '''] print (random.choice(test))
[ "I think this does exactly what you're asking:\nprint random.choice(test[0].split('\\n'))\nline 5\n\nI have a feeling you're looking to do a little more than that, though. \n", "I suspect you want to pick them randomly without replacement; if all you do is pick words randomly, with something like\ndo until set em...
[ 3, 1 ]
[]
[]
[ "printing", "python", "random" ]
stackoverflow_0004425971_printing_python_random.txt
Q: Python/C: Parse all values at once for return to Python? If you are outputting a lot of values from C to a dict in Python, is there a better (quicker and less error prone) way to do it than: return Py_BuildValue("{s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s...
Python/C: Parse all values at once for return to Python?
If you are outputting a lot of values from C to a dict in Python, is there a better (quicker and less error prone) way to do it than: return Py_BuildValue("{s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d,s:d...
[ "Given that most of the values seem to come from spa, it's probably a better idea to encapsulate it along with the other loose properties within an object and just return that. Also, datetime.time.\n", "You can use macros:\n#define ADD_FIELD(F) PyDict_SetItemString(d, #F, spa.F)\nADD_FIELD(jd);\nADD_FIELD(jc);\n....
[ 2, 2, 2, 1 ]
[]
[]
[ "c", "python", "python_c_extension" ]
stackoverflow_0004424206_c_python_python_c_extension.txt
Q: How can I call erlang from Python? Possible Duplicate: best way to integrate erlang and python To use some powerful features of erlang, I should call erlang program from Python, How can I do that? Thank you~ A: In Erlang , you can communicate with the external world using ports which provides a byte oriented i...
How can I call erlang from Python?
Possible Duplicate: best way to integrate erlang and python To use some powerful features of erlang, I should call erlang program from Python, How can I do that? Thank you~
[ "In Erlang , you can communicate with the external world using ports which provides a byte oriented interface to the external program.\nYou can also have a look at erlport which is a python library implementing the Erlang port protocol.\n", "Take a look at BERT-RPC. It allows you to perform remote procedure calls...
[ 8, 3, 1 ]
[]
[]
[ "erlang", "python" ]
stackoverflow_0004425623_erlang_python.txt
Q: Sorting strings with accented characters in python Possible Duplicate: Python not sorting unicode properly. Strcoll doesn't help. I'm trying to sort some words in alphabetical order. Here is how I do it: #!/opt/local/bin/python2.7 # -*- coding: utf-8 -*- import locale # Make sure the locale is in french locale...
Sorting strings with accented characters in python
Possible Duplicate: Python not sorting unicode properly. Strcoll doesn't help. I'm trying to sort some words in alphabetical order. Here is how I do it: #!/opt/local/bin/python2.7 # -*- coding: utf-8 -*- import locale # Make sure the locale is in french locale.setlocale(locale.LC_ALL, "fr_FR.UTF-8") print "locale:...
[ "I finally chose to strip diacritics and compare the stripped version of the strings so that I don't have to add the PyICU dependency.\n" ]
[ 2 ]
[]
[]
[ "collation", "diacritics", "python", "sorting" ]
stackoverflow_0004409009_collation_diacritics_python_sorting.txt
Q: better writing style for the following code I was wondering if someone could tell me the pythonic way to check out the following. I have a 6 bit binary number and want to check with its decimal values. Using mathematical function is one way but still it would require that I write around 2**6 if constructs. So I wa...
better writing style for the following code
I was wondering if someone could tell me the pythonic way to check out the following. I have a 6 bit binary number and want to check with its decimal values. Using mathematical function is one way but still it would require that I write around 2**6 if constructs. So I wanted to know if there's an easier statement to wr...
[ "Use a dictionary mapping values into outcomes (which can be functions in Python).\nFor example:\nd = {}\nd[0] = ....\nd[1] = ....\nd[2] = ....\n\noutcome = d[a]\n\nNaturally, how this works depends on your ...., but this construct can be very flexible. The most important feature of this approach is that this dicti...
[ 4, 2, 0, -3 ]
[ "Personally I prefer a if/elif if I am understanding your ...\nso your:\nif(a==1):\n ....\nelse:\n if(a==2)\n.....\n\nBecomes this if you use if elif ladder:\nif a==1:\n ....\nelif a==2:\n .....\nelse:\n default\n\nYou can also use Python's version of a conditional expression for simple ladders:\ndef...
[ -1 ]
[ "python" ]
stackoverflow_0004212435_python.txt
Q: Measuring Download speed when using Python's FTPLib I am downloading files using the Python FTP lib , is there a way to get the current download speed. If not is there another lib that I can use that will provide me with speed info ? A: What's to stop you from providing your own callback to retrbinary/retrlines...
Measuring Download speed when using Python's FTPLib
I am downloading files using the Python FTP lib , is there a way to get the current download speed. If not is there another lib that I can use that will provide me with speed info ?
[ "What's to stop you from providing your own callback to retrbinary/retrlines that would calculate the current download speed? You'll know how much data has been downloaded and can trivially take time measurements.\n" ]
[ 0 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0004427224_ftplib_python.txt
Q: Django parsing arguments I'm using an AJAX call to get data from the server: $.ajax({ type: 'POST', url: '/simple/gd/', dataType: 'json', data: {t : "PL"}, success: function(data) { var newd = data['t']; alert('Load was performed: ' + newd); } }); On the server, urls.py is: (r'^simple/gd/(?P<data>.*)$', ...
Django parsing arguments
I'm using an AJAX call to get data from the server: $.ajax({ type: 'POST', url: '/simple/gd/', dataType: 'json', data: {t : "PL"}, success: function(data) { var newd = data['t']; alert('Load was performed: ' + newd); } }); On the server, urls.py is: (r'^simple/gd/(?P<data>.*)$', 'simple.views.getData'), The ...
[ "If you use type: 'POST' then the data doesn't get appended to the URL as a query string. \nInstead, it is included in the request object's POST dictionary.\nSo in order to pass something back that fires your alert you need to render a string that can be interpreted as json data something along the lines of:\n(r'^s...
[ 1, 0 ]
[]
[]
[ "ajax", "django", "python" ]
stackoverflow_0004427216_ajax_django_python.txt
Q: Python zero-values Are there any values other than False, None, 0, and 0.0 that will return False with bool(x) (in Python 3.X)? A: http://docs.python.org/py3k/library/stdtypes.html#truth-value-testing A: Any empty sequence or mapping object will also evaluate to False: >>> bool({}) False >>> bool([]) False >>...
Python zero-values
Are there any values other than False, None, 0, and 0.0 that will return False with bool(x) (in Python 3.X)?
[ "http://docs.python.org/py3k/library/stdtypes.html#truth-value-testing\n", "Any empty sequence or mapping object will also evaluate to False:\n>>> bool({})\nFalse\n>>> bool([])\nFalse\n>>> bool(\"\")\nFalse\n>>> bool(())\nFalse\n\n" ]
[ 7, 3 ]
[]
[]
[ "boolean", "python", "python_3.x" ]
stackoverflow_0004427543_boolean_python_python_3.x.txt
Q: How can I get a text from a window? Here my function: def getEditText(hwnd): result = [] bufferlength = struct.pack('i', 255) linecount = win32gui.SendMessage(hwnd, win32con.EM_GETLINECOUNT, 0, 0) print"--- linecount :",linecount for line in range(linecount): linetext = bufferlength + ...
How can I get a text from a window?
Here my function: def getEditText(hwnd): result = [] bufferlength = struct.pack('i', 255) linecount = win32gui.SendMessage(hwnd, win32con.EM_GETLINECOUNT, 0, 0) print"--- linecount :",linecount for line in range(linecount): linetext = bufferlength + "".ljust(253) linelength ...
[ "Thanks for your answer. I've just tried def \nGetText(hwnd):\n buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0)\n buffer = win32gui.PyMakeBuffer(buf_size)\n win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buffer)\n return buffer[:buf_size] ...
[ 0 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0004424445_python_windows.txt
Q: NameError: name 'buffer' is not defined with Ant Based framework batch file I'm using a python script to execute an Ant based framework batch file(Helium.bat) subprocess.Popen('hlm '+commands, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) However the script will always stop and display the following ...
NameError: name 'buffer' is not defined with Ant Based framework batch file
I'm using a python script to execute an Ant based framework batch file(Helium.bat) subprocess.Popen('hlm '+commands, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) However the script will always stop and display the following error when it executes the .bat file: import codecs File "C:\Python25\lib\codec...
[ "I think at least part of the problem is how you're executing the batch file. Give this a try:\n# execute the batch file as a separate process and echo its output\nPopen_kwargs = { 'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT,\n 'universal_newlines': True }\nwith subprocess.Popen('hlm '+co...
[ 1 ]
[]
[]
[ "batch_file", "python", "python_2.5", "windows" ]
stackoverflow_0004427494_batch_file_python_python_2.5_windows.txt
Q: Prevent a file from being opened I am writing a Python logger script which writes to a CSV file in the following manner: Open the file Append data Close the file (I think this is necessary to save the changes, to be safe after every logging routine.) PROBLEM: The file is very much accessible through Windows Expl...
Prevent a file from being opened
I am writing a Python logger script which writes to a CSV file in the following manner: Open the file Append data Close the file (I think this is necessary to save the changes, to be safe after every logging routine.) PROBLEM: The file is very much accessible through Windows Explorer (I'm using XP). If the file is op...
[ "Rather than closing and reopening the file after each access, just flush its buffer:\ntheloggingfile.flush()\n\nThis way, you keep it open for writing in Python, which should lock the file from other programs opening it for writing. I think Excel will be able to open it as read-only while it's open in Python, but ...
[ 4, 0 ]
[]
[]
[ "file_locking", "logging", "python" ]
stackoverflow_0004427936_file_locking_logging_python.txt
Q: Handling exceptions in python What the best way of handling exceptions. class SRException(Exception): default_exception = True def somefun1(email): try: user = somefun2(email) except Exception, e: raise SRException, ("could not find the email", e) def somefun2(...
Handling exceptions in python
What the best way of handling exceptions. class SRException(Exception): default_exception = True def somefun1(email): try: user = somefun2(email) except Exception, e: raise SRException, ("could not find the email", e) def somefun2(email): try: us...
[ "Your exception handler is too broad, catch only the specific exceptions you know you can handle. There is no sense in catching an Exception only to wrap it in another exception and re-raising it; an exception object carries a Traceback that will show you what path the code is going. Just let the Exception bubble u...
[ 4, 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004428250_django_python.txt
Q: RDFLib: Namespace prefixes in XML serialization In a Python script using RDFLib 3.0, I get the following XML-Output when serializing my triples: <rdf:RDF xmlns:_3="http://www.my-example.intra/ontologies/ci.owl#" > How can I define specific namespace prefixes for those anonymous _x-prefixes automatically assigne...
RDFLib: Namespace prefixes in XML serialization
In a Python script using RDFLib 3.0, I get the following XML-Output when serializing my triples: <rdf:RDF xmlns:_3="http://www.my-example.intra/ontologies/ci.owl#" > How can I define specific namespace prefixes for those anonymous _x-prefixes automatically assigned by RDFLib (or it's XML-Serializer respectively)? <...
[ "I eventually found a solution to this by looking at some (quite messily distributed) rdflib doc files. For the (Conjunctive)Graph storing the triples, call\nmygraph.bind(prefix, URIRef(url))\n\ni.e. \nmygraph.bind('ex', URIRef('http://www.my-example.intra/ontologies/ci.owl#'))\n\nPassing 'False' as 3rd argument ov...
[ 13 ]
[]
[]
[ "namespaces", "python", "rdflib" ]
stackoverflow_0004427607_namespaces_python_rdflib.txt
Q: How a Ruby on Rails developer should start learning Python Django I want to learn Django for web development. And for Django I need to know Python. I have never coded in Python but after reading discussions and articles on the web I think it wont be a difficult task. I have been coding in Ruby and using Ruby on Ra...
How a Ruby on Rails developer should start learning Python Django
I want to learn Django for web development. And for Django I need to know Python. I have never coded in Python but after reading discussions and articles on the web I think it wont be a difficult task. I have been coding in Ruby and using Ruby on Rails from more than past two years. So I can say that I have fairly good...
[ "The official tutorials for Python and Django are both good. There are so many freely available books on Python. Django Book (free) by it's creators is great if you are not satisfied with the tutorial.\n", "Here is what I think will work:\n\nInstall Python on your machine.\nGo through any introductory tutorial. H...
[ 6, 4, 3 ]
[]
[]
[ "django", "python", "ruby", "ruby_on_rails" ]
stackoverflow_0004428555_django_python_ruby_ruby_on_rails.txt
Q: How can I now make a my GUI to output the results? I'm studying Tkinter, and I need a Button, and then when I click it, do something with some code, and then print the result. I started with this: from Tkinter import * import heapq root = Tk() root.title("TEST") root.geometry("800x600") #-------------------CODE-...
How can I now make a my GUI to output the results?
I'm studying Tkinter, and I need a Button, and then when I click it, do something with some code, and then print the result. I started with this: from Tkinter import * import heapq root = Tk() root.title("TEST") root.geometry("800x600") #-------------------CODE----------------------- def makeHuffTree(symbolTupleList...
[ "You want to add something like the following in your code:\ndef OnButton():\n exampleData = [(0.124167 , 'e'), (0.0969225 , 't'),(0.0820011 , 'a'),]\n huffTree = makeHuffTree(exampleData)\n printHuffTree(huffTree)\n\nbutton = Button(root, text=\"Press me!\", command=OnButton)\nbutton.pack()\n\nIf by '\...
[ 2 ]
[]
[]
[ "connection", "python", "tkinter", "user_interface" ]
stackoverflow_0004428425_connection_python_tkinter_user_interface.txt
Q: XSL short `value-of` with `disable-output-escaping`? I'm processing the following (example) XML: <?xml version="1.0"?> <root>&amp; &amp; &amp;</root> through the following (example) XSL: <?xml version="1.0"?> <xsl:stylesheet version="1.0"> <xsl:output method="html" version="4.0" encoding="UTF-8" ...
XSL short `value-of` with `disable-output-escaping`?
I'm processing the following (example) XML: <?xml version="1.0"?> <root>&amp; &amp; &amp;</root> through the following (example) XSL: <?xml version="1.0"?> <xsl:stylesheet version="1.0"> <xsl:output method="html" version="4.0" encoding="UTF-8" omit-xml-declaration="yes" /> <xsl:template match="...
[ "DOE in fact is designed for such cases. Sorry, if you know that, just to be consecutive.\nhttp://www.w3.org/TR/xslt#disable-output-escaping\n\nNormally, the xml output method escapes & and < (and possibly other characters) when outputting text nodes. This ensures that the output is well-formed XML. However, it is ...
[ 1 ]
[]
[]
[ "libxslt", "lxml", "python", "xslt" ]
stackoverflow_0004428295_libxslt_lxml_python_xslt.txt
Q: List/matrix is not saving the correct values I have a weird problem with an assignment I got. We are supposed to implement a matrix class. Well, it's not that hard, but Python just won't do as I tell it to. But I'm sure there is an explanation. The problem is that, in the following code, I try to save values (prov...
List/matrix is not saving the correct values
I have a weird problem with an assignment I got. We are supposed to implement a matrix class. Well, it's not that hard, but Python just won't do as I tell it to. But I'm sure there is an explanation. The problem is that, in the following code, I try to save values (provided in a list) into a matrix. class simplematrix:...
[ "The problem is in [[0]*ln]*lm. The result consists of lm references to the same list, so when you modify one row, all rows appear to change.\nTry:\nself.matrix = [[0]*ln for i in xrange(lm)]\n\n", "The answers by Tim and aix correct your mistake, but that step isn't even necessary, you can do the whole thing in ...
[ 2, 2, 1 ]
[]
[]
[ "list", "matrix", "python" ]
stackoverflow_0004428632_list_matrix_python.txt
Q: Intellij IDEA 10 + Python + Django does not run Apache Ant-scripts Greetings! Intellij IDEA 10 + Python plugin when creating a project using Django, does not run Apache Ant-scripts. When I try to add an Ant-script error occurs «Cannot Add Files». I can’t understand reason of problem. A: Which module type have yo...
Intellij IDEA 10 + Python + Django does not run Apache Ant-scripts
Greetings! Intellij IDEA 10 + Python plugin when creating a project using Django, does not run Apache Ant-scripts. When I try to add an Ant-script error occurs «Cannot Add Files». I can’t understand reason of problem.
[ "Which module type have you created? Please try to create a regular Java module with a Java SDK, and to add a Python facet to it.\n" ]
[ 0 ]
[]
[]
[ "ant", "django", "intellij_idea", "python" ]
stackoverflow_0004426808_ant_django_intellij_idea_python.txt
Q: Drupal showing data from a python script in background :Asynchronous Solution I m wrting a drupal module (of course i followed the tutorial and reading pro drupal development etc) .In the Back-End (in a server side manner) a python script, scheduled with crontab, fetchs xml-data from a device (each 1-5minute , ...
Drupal showing data from a python script in background :Asynchronous Solution
I m wrting a drupal module (of course i followed the tutorial and reading pro drupal development etc) .In the Back-End (in a server side manner) a python script, scheduled with crontab, fetchs xml-data from a device (each 1-5minute , not time critical at all) and then ,after parsing it , stores the data in a mysql d...
[ "Take a look at http://drupal.org/project/rrdtool. This module integrates RRDTool with Drupal.\nFor automation you can use hook_cron.\n" ]
[ 1 ]
[]
[]
[ "drupal_modules", "php", "python" ]
stackoverflow_0004428832_drupal_modules_php_python.txt
Q: Django - how to obtain all fields from model Is there an easy way to obtain all the fields from a certain django model, even those set via a foreignkey or many to many field on an other relation? Example: class A(models.Model): some_number = models.IntegerField() class B(models.Model): link_to_a = models....
Django - how to obtain all fields from model
Is there an easy way to obtain all the fields from a certain django model, even those set via a foreignkey or many to many field on an other relation? Example: class A(models.Model): some_number = models.IntegerField() class B(models.Model): link_to_a = models.ForeignKey(A, related_name="link_to_b") Invoking ...
[ "You can use the semi-documented, non-public API on the _meta property of a model class:\nfrom myapp.models import A\n\nfor f in A._meta._fields():\n print f.name\n\n(Note, there is an existing work-item in Django to document this API: http://code.djangoproject.com/ticket/12663 )\nYou'll need to manually follow ...
[ 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004429156_django_python.txt
Q: Disabling Django CSRF for views that do not always have a response I have a Django view that receives POSTs which do not need to have the CSRF token. Therefore I used the @csrf_exempt decorator on the view. The problem is that sometimes I do not issue a response from the view (it's a Twitter bot, it receives an HT...
Disabling Django CSRF for views that do not always have a response
I have a Django view that receives POSTs which do not need to have the CSRF token. Therefore I used the @csrf_exempt decorator on the view. The problem is that sometimes I do not issue a response from the view (it's a Twitter bot, it receives an HTTP POST for every tweet and I do not want to respond to every tweet). Wh...
[ "I know you already got your answer, and indeed Ned's right;\nbut in addition to that: not only Django really expects views to return a response, your client also! It's an HTTP error and likely a resource waste not to return something (and thus close the connection straight away)!\nI would think that a 204 No Conte...
[ 9, 7 ]
[]
[]
[ "csrf", "decorator", "django", "django_csrf", "python" ]
stackoverflow_0003269617_csrf_decorator_django_django_csrf_python.txt
Q: PyGTK and visual-python I'm developing an application with PyGTK that will make use of visual-python's 3d drawings and animations, but I can't get both libraries to work together: they either hung up when I close the Gtk window or they get stuck when I run the application. I've tried with threads and they run side...
PyGTK and visual-python
I'm developing an application with PyGTK that will make use of visual-python's 3d drawings and animations, but I can't get both libraries to work together: they either hung up when I close the Gtk window or they get stuck when I run the application. I've tried with threads and they run side-by-side, but when I close vi...
[ "This is a non-trivial problem given the way that VPython wants to work, but there is an example in the contributed programs section of the VPython web site that shows how to embed VPython into a wxPython application, so perhaps you can look over that code and determine what you would need to do to perform the same...
[ 3 ]
[]
[]
[ "pygtk", "python", "python_multithreading", "vpython" ]
stackoverflow_0004428599_pygtk_python_python_multithreading_vpython.txt
Q: how to redirect form after submit I've a form, where users select the years and gender, then they click on submit. With these values I'm calculating the numbers, drawing some pictures, etc. Everything fine so far. What I would like to do is open these pictures and data into a pdf file, with the help of documentati...
how to redirect form after submit
I've a form, where users select the years and gender, then they click on submit. With these values I'm calculating the numbers, drawing some pictures, etc. Everything fine so far. What I would like to do is open these pictures and data into a pdf file, with the help of documentation. The thing is that I'm not able to ...
[ "So what I had to do was something like this:\nIn the view that allow the user to select data:\nform_year = YearForm()\nform_gender = GenderForm()\nreturn render_to_response('report.html',\n {\n 'form_year': form_year,\n 'form_...
[ 1 ]
[]
[]
[ "django", "django_forms", "django_templates", "django_views", "python" ]
stackoverflow_0004428548_django_django_forms_django_templates_django_views_python.txt
Q: Reading back a datetime in sqlite3 I am using Python to create an in-memory sqlite3 database with a timestamp column. When I use min() or max() on this column in my query, the column is returned as a string rather than a Python datetime object. I read a previous question on Stackoverflow that provided a solution f...
Reading back a datetime in sqlite3
I am using Python to create an in-memory sqlite3 database with a timestamp column. When I use min() or max() on this column in my query, the column is returned as a string rather than a Python datetime object. I read a previous question on Stackoverflow that provided a solution for normal SELECT statements, but it does...
[ "You have to set detect_types to sqlite.PARSE_COLNAMES and use as \"foo [timestamp]\" like this:\nimport sqlite3\nimport datetime\n\ndb = sqlite3.connect(':memory:', detect_types = sqlite3.PARSE_COLNAMES)\nc = db.cursor()\nc.execute('create table foo (bar integer, baz timestamp)')\nc.execute('insert into foo values...
[ 15 ]
[]
[]
[ "datetime", "python", "sqlite", "timestamp" ]
stackoverflow_0004429788_datetime_python_sqlite_timestamp.txt
Q: How to make a python script "pipeable" in bash? I wrote a script and I want it to be pipeable in bash. Something like: echo "1stArg" | myscript.py Is it possible? How? A: See this simple echo.py: import sys if __name__ == "__main__": for line in sys.stdin: sys.stderr.write("DEBUG: got line: " + li...
How to make a python script "pipeable" in bash?
I wrote a script and I want it to be pipeable in bash. Something like: echo "1stArg" | myscript.py Is it possible? How?
[ "See this simple echo.py:\nimport sys\n\nif __name__ == \"__main__\":\n for line in sys.stdin:\n sys.stderr.write(\"DEBUG: got line: \" + line)\n sys.stdout.write(line)\n\nrunning:\nls | python echo.py 2>debug_output.txt | sort\n\noutput:\necho.py\ntest.py\ntest.sh\n\ndebug_output.txt content:\nDEB...
[ 81, 21, 11, 5 ]
[]
[]
[ "pipe", "python" ]
stackoverflow_0004429966_pipe_python.txt
Q: View Script Output Over SSH? I have a script, called test.py, that does the following: while (1): ....print "hello world" (this script simply prints 'hello world' continuously). Now, I am using two machines (machine A and machine B). Same user is used for both machines. I would like to do the following: (1) [wo...
View Script Output Over SSH?
I have a script, called test.py, that does the following: while (1): ....print "hello world" (this script simply prints 'hello world' continuously). Now, I am using two machines (machine A and machine B). Same user is used for both machines. I would like to do the following: (1) [working with machine A] run test.p...
[ "There are a few ways you could do this… But possibly the simplest would be a fifo buffer:\nA$ mkfifo /tmp/stuff\nA$ ./test.py &> /tmp/stuff\n\nThen on machine B:\nB$ ssh A \"cat /tmp/stuff\"\nhello world\nhello world\n...\n\nNormally I would suggest using screen, but it assumes that you're going to be running from...
[ 4, 1 ]
[]
[]
[ "linux", "python", "ssh", "ubuntu" ]
stackoverflow_0004430408_linux_python_ssh_ubuntu.txt
Q: Get only properties of an instance I was wondering if there's a way in Python(2.6) to get only the name of the properties an instance has. Let's say I have: #!/usr/bin/python2.6 class MyClass(object): def __init__(self): self._x = None @property def x(self): return self._x @x....
Get only properties of an instance
I was wondering if there's a way in Python(2.6) to get only the name of the properties an instance has. Let's say I have: #!/usr/bin/python2.6 class MyClass(object): def __init__(self): self._x = None @property def x(self): return self._x @x.setter def x(self, value): p...
[ "You can use the following code:\ndef iter_properties_of_class(cls):\n for varname in vars(cls):\n value = getattr(cls, varname)\n if isinstance(value, property):\n yield varname\n\ndef properties(inst):\n result = {}\n for cls in inst.__class__.mro():\n for varname in iter_...
[ 5, 1, 1 ]
[]
[]
[ "decorator", "properties", "python" ]
stackoverflow_0004430133_decorator_properties_python.txt
Q: python on win32: how to get absolute timing / CPU cycle-count I have a python script that calls a USB-based data-acquisition C# dotnet executable. The main python script does many other things, e.g. it controls a stepper motor. We would like to check the relative timing of various operations, for that purpose the...
python on win32: how to get absolute timing / CPU cycle-count
I have a python script that calls a USB-based data-acquisition C# dotnet executable. The main python script does many other things, e.g. it controls a stepper motor. We would like to check the relative timing of various operations, for that purpose the dotnet exe generates a log with timestamps from C# Stopwatch.GetTi...
[ "Have you tried using ctypes?\nfrom ctypes import *\nval = c_int64()\nwindll.Kernel32.QueryPerformanceCounter(byref(val))\nprint val.value\n\n", "You could just call the C# StopWatch class directly from Python couldn't you? Maybe a small wrapper is needed (don't know Python/C# interop details - sorry) - if you a...
[ 8, 0 ]
[]
[]
[ "api", "performancecounter", "python", "winapi" ]
stackoverflow_0004430227_api_performancecounter_python_winapi.txt
Q: Resizing a Scrolled Tkinter Text Box I'd like a to make a scrolled Tkinter textbox that fills the maximum alloted space. I have it working kind of... For some reason when I stretch the window the text widget is fine; However, the scroll bar gets a ton of padding on the x axis. The second problem is when I shrink ...
Resizing a Scrolled Tkinter Text Box
I'd like a to make a scrolled Tkinter textbox that fills the maximum alloted space. I have it working kind of... For some reason when I stretch the window the text widget is fine; However, the scroll bar gets a ton of padding on the x axis. The second problem is when I shrink the window the scrollbar goes of the scree...
[ "Your scrollbar gets all the padding because you use fill='both'. Even though it's a vertical scrollbar you asked it to take up extra space along the x axis, which results in the padding since the scrollbar itself won't stretch to make a wide scrollbar. You want vertical scrollbars to only fill in the Y direction a...
[ 7 ]
[]
[]
[ "python", "text", "tkinter" ]
stackoverflow_0004421362_python_text_tkinter.txt
Q: Trying to get which Radiobutton triggered an event I'm trying to create a set of radiobuttons in Tkinter. One of the attributes I'd really like to have is the ability to tell which radiobutton was last entered. I tried to bind to each radiobutton. However when the event is triggered it returns the same value each ...
Trying to get which Radiobutton triggered an event
I'm trying to create a set of radiobuttons in Tkinter. One of the attributes I'd really like to have is the ability to tell which radiobutton was last entered. I tried to bind to each radiobutton. However when the event is triggered it returns the same value each time. What am I doing wrong? snippet: i = 0 ...
[ "Your lambda needs to be something like this:\nlambda event, i=i: self.WSRB_UD(event, i))\n\nThis creates a local variable i inside the lambda that is bound to the value of i at the time the binding was created.\n" ]
[ 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004419595_python_tkinter.txt
Q: Can you embed Python into a C program and then call it from C#/ASP.NET with no outside tools? I got a question about embedding Python into C/C++ programs. I'm new to .NET and C sharp, and I was recently able to call a few dlls (one simple hello world C I made from scratch with the help of Vladimir Tskhvaradze's ...
Can you embed Python into a C program and then call it from C#/ASP.NET with no outside tools?
I got a question about embedding Python into C/C++ programs. I'm new to .NET and C sharp, and I was recently able to call a few dlls (one simple hello world C I made from scratch with the help of Vladimir Tskhvaradze's 05 how to, and a user.32 out of the 70-536 book). I see in my Python documentation 2.6 that I can...
[ "I recommend to use COM: write a COM server in Python (using win32com), and then access it from C# (using .NET's COM interop). You should start with a hello-world style application, to make sure it can work at all. This should not require any additional tools, and no C code.\n" ]
[ 2 ]
[]
[]
[ "c", "c#", "python" ]
stackoverflow_0004431398_c_c#_python.txt
Q: Random Word List Issue Alright so far I have created a list containing a long list of words each on it's own line... I'm wanting to pick a random word only once and then also print to the screen with a little extra information saying, "Define: (and then the word it picked random)". Anyways when I run the below cod...
Random Word List Issue
Alright so far I have created a list containing a long list of words each on it's own line... I'm wanting to pick a random word only once and then also print to the screen with a little extra information saying, "Define: (and then the word it picked random)". Anyways when I run the below code I only get the define text...
[ "Words needs to be an actual list\n#Wrong\nwords = ['''\nword1\nword2\nword3\n''']\n#Better\nwords = ['word1','word2','word3']\n\nYou only get the prompt once because you're using a list of length 1.\n", "words = [\n'word1',\n'word2',\n'word3',\n]\n\nwhile len(words) > 0:\n word = random.choice(words)\n p...
[ 2, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004430729_python.txt
Q: BEGINNER: Python Value error: invalid literal for int() Im making a simple blackjack program in python, but im getting a "ValueError: invalid literal for int() with base 10: ..." In order to get the total value of the player hands, after creating the card object, i try to get the rank of the card: rank1 = Card.Ca...
BEGINNER: Python Value error: invalid literal for int()
Im making a simple blackjack program in python, but im getting a "ValueError: invalid literal for int() with base 10: ..." In order to get the total value of the player hands, after creating the card object, i try to get the rank of the card: rank1 = Card.Card.getRank(card1) heres the classs method: def getRank(self)...
[ "This line isn't right:\n if self.__rank == ('J' or 'Q' or 'K'):\n\n('J' or 'Q' or 'K') evaluates to 'J', so this line just checks whether self.__rank == 'J'.\nYou actually want:\n if self.__rank in ('J', 'Q', 'K'):\n\nI think your first code example should work. Are you sure that you're actually running the new ...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004424871_python.txt
Q: Accurate trig in python Straight to the chase I want to create a function which calculates the length of a step. This is what I have: def humanstep(angle): global human human[1]+=math.sin(math.radians(angle))*0.06 human[2]+=math.cos(math.radians(angle))*0.06 So if the angle is 90 then the x value (hum...
Accurate trig in python
Straight to the chase I want to create a function which calculates the length of a step. This is what I have: def humanstep(angle): global human human[1]+=math.sin(math.radians(angle))*0.06 human[2]+=math.cos(math.radians(angle))*0.06 So if the angle is 90 then the x value (human[1]) should equal 0.06 and ...
[ "This is representation error due to how floating point arithmetic works. See the following page from the Python documentation: Floating Point Arithmetic: Issues and Limitations.\nFTA:\n\nNote that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code eit...
[ 5, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004431551_python.txt
Q: Batch existence check + save - Django I have a CSV file listing items that I need to store within the database. I need to check which items are not already stored, and if not stored I need to save them within the database. There are 2-5 million rows. The model is Django's User model. I have a CSV file of this for...
Batch existence check + save - Django
I have a CSV file listing items that I need to store within the database. I need to check which items are not already stored, and if not stored I need to save them within the database. There are 2-5 million rows. The model is Django's User model. I have a CSV file of this form: Item_ID, Surname, Policy_number, Sex,...
[ "Depends on the situation. If the csv data can be converted to a model, something like this should do:\n\nload the csv data \nfor each row:\n\ncheck if a model for it exists\nif not:\n\ncreate a new model based on the data and save it.\n\n\n\nEdit:\nI think a batch check for existence will be hard.\nA batch save of...
[ 2, 2, 1, 1 ]
[]
[]
[ "django", "django_models", "python", "sql", "sql_server" ]
stackoverflow_0004429644_django_django_models_python_sql_sql_server.txt
Q: WingIDE brace matching colours Has anyone figured out a way to change the brace matching colours in WingIDE? I have managed to manually port my favourite colour scheme across from my text editor and the default green just doesn't do it for me. I've been unable to find instructions on how to do this in the UI, us...
WingIDE brace matching colours
Has anyone figured out a way to change the brace matching colours in WingIDE? I have managed to manually port my favourite colour scheme across from my text editor and the default green just doesn't do it for me. I've been unable to find instructions on how to do this in the UI, user manual and mailing lists.
[ "I've contacted Wingware support and they have confirmed that there is no way to set the brace matching colour.\n" ]
[ 1 ]
[]
[]
[ "python", "wing_ide" ]
stackoverflow_0004418839_python_wing_ide.txt
Q: Reading and writing binary data of dynamic sizes question I am trying to read data from a file in binary mode and manipulate that data. try: resultfile = open("binfile", "rb") except: print "Error" resultsize = os.path.getsize("binfile") There is a 32 byte header which I parse fine then the buffer of bin...
Reading and writing binary data of dynamic sizes question
I am trying to read data from a file in binary mode and manipulate that data. try: resultfile = open("binfile", "rb") except: print "Error" resultsize = os.path.getsize("binfile") There is a 32 byte header which I parse fine then the buffer of binary data starts. The data can be of any size from 16 to 4092 a...
[ "You need to open your output file in binary mode, as you do your input file. Otherwise, newline characters may get changed. You can see that this is what happens in your hex dump: 0A characters ('\\n') are changed into OD 0A ('\\r\\n').\nThis should work:\ninput_file = open('f1', 'rb')\ncontents = input_file.read(...
[ 2, 0 ]
[]
[]
[ "binaryfiles", "python" ]
stackoverflow_0004431759_binaryfiles_python.txt
Q: Frequency detection from a sound file What I am trying to achieve is the following: I need the frequency values of a sound file (.wav) for analysis. I know a lot of programs will give a visual graph (spectrogram) of the values but I need to raw data. I know this can be done with FFT and should be fairly easily scr...
Frequency detection from a sound file
What I am trying to achieve is the following: I need the frequency values of a sound file (.wav) for analysis. I know a lot of programs will give a visual graph (spectrogram) of the values but I need to raw data. I know this can be done with FFT and should be fairly easily scriptable in python but not sure how to do it...
[ "I'm not sure if this is what you want, if you just want the FFT:\nimport scikits.audiolab, scipy\nx, fs, nbits = scikits.audiolab.wavread(filename)\nX = scipy.fft(x)\n\nIf you want the magnitude response:\nimport pylab\nXdb = 20*scipy.log10(scipy.absolute(X))\nf = scipy.linspace(0, fs, len(Xdb))\npylab.plot(f, Xdb...
[ 8, 5 ]
[]
[]
[ "audio", "fft", "frequency", "numpy", "python" ]
stackoverflow_0004431481_audio_fft_frequency_numpy_python.txt
Q: Is it a good practice to use pickled data instead of additional tables? Many times while creating database structure, I get stuck at the question, what would be more effective, storing data in pickled format in a column in the same table or create additional table and then use JOIN. Which path should be followed, ...
Is it a good practice to use pickled data instead of additional tables?
Many times while creating database structure, I get stuck at the question, what would be more effective, storing data in pickled format in a column in the same table or create additional table and then use JOIN. Which path should be followed, any advice ? For example: There is a table of Customers, containing fields li...
[ "It's usually better to create seperate tables. If you go with pickling and later find you want to query the data in a different way, it could be difficult.\nSee Database normalization.\n", "Usually it's best to keep your data normalized (i.e. create more tables). Storing data 'pickled' as you say, is acceptable,...
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004428613_mysql_python.txt
Q: A module's __setattr__ and __getattr__ when accessing globals __getattr__ and __setattr__ works well when i get or set an object's attributes using dot notation. How do i intercept getting and setting module global variables from inside the module? I subclass module type: from types import ModuleType class WUserMo...
A module's __setattr__ and __getattr__ when accessing globals
__getattr__ and __setattr__ works well when i get or set an object's attributes using dot notation. How do i intercept getting and setting module global variables from inside the module? I subclass module type: from types import ModuleType class WUserModule(ModuleType): def __init__(self, name): super().__i...
[ "You can't. \nThe basic problem is that attribute overloads only work when you are accessing an attribute, specifically that means: \n\nexpr . ident\n\nWithout the dot, there can be no attribute overload. Thus, no matter what you do, a sequence like\n\na\n\nCan never invoke an attribute overload, no matter what e...
[ 2, 0 ]
[]
[]
[ "module", "python" ]
stackoverflow_0004432376_module_python.txt
Q: Trouble Installing iGraph on Windows (i386 and x64) I usually install R packages using the command below, but it will not work for the network graph ad-on iGraph. T think this is because I am using the new version of R (2.12) which seems to have changed package installation (now split between i386/x64). My questio...
Trouble Installing iGraph on Windows (i386 and x64)
I usually install R packages using the command below, but it will not work for the network graph ad-on iGraph. T think this is because I am using the new version of R (2.12) which seems to have changed package installation (now split between i386/x64). My question is, what is the easiest way to get up and running with ...
[ "In version 2.12.0 using the following GUI commands worked for me\nPackages -> Select Repositories -> CTRL Click all repositories\nPackages -> Install Packages -> Click igraph\nOnce you have this done, be sure to add \"library(igraph)\" to your script.\n", "Generally users of Windows packages are discouraged from...
[ 2, 0 ]
[]
[]
[ "compiler_construction", "python", "r", "windows" ]
stackoverflow_0004432975_compiler_construction_python_r_windows.txt
Q: Python chat client-server modification goes horribly wrong As an exercise, I looked for a simple Python chat client-server system to modify and toy with. The first major failing I found in the system was that it used a single tcp connection for the server and client to communicate. The second was that you could on...
Python chat client-server modification goes horribly wrong
As an exercise, I looked for a simple Python chat client-server system to modify and toy with. The first major failing I found in the system was that it used a single tcp connection for the server and client to communicate. The second was that you could only have two people (one using the client, and the other using th...
[ "I am working on something alot like this, but I am instead going to implement text encryption. I see you are suing lists for the client list... but I would say there is a better way of doing that. I am using a dictionary.\nif you are familiar with dictionaries, skip the next paragraph.\nDicionaries can handle basi...
[ 0 ]
[]
[]
[ "chat", "client", "python" ]
stackoverflow_0004240956_chat_client_python.txt
Q: Matching two subsequent words with a regex? I have the following string: The Wild won 2 - 1 over the Flames. I need to extract the team names and the scores from that string. In Python I did the following: foo = re.findall(r'The (\w+) won (\d+) - (\d+) over the (\w+)\.', mystring) Now the problem is, there are...
Matching two subsequent words with a regex?
I have the following string: The Wild won 2 - 1 over the Flames. I need to extract the team names and the scores from that string. In Python I did the following: foo = re.findall(r'The (\w+) won (\d+) - (\d+) over the (\w+)\.', mystring) Now the problem is, there are team names with whitespace in it like this: The...
[ "Use ([\\w ]+) instead of (\\w+).\n", "You can just edit your original regex to include spaces in the team name groups:\nfoo = re.findall(r'The ([\\w ]+) won (\\d+) - (\\d+) over the ([\\w ]+)\\.', mystring)\n\n", "If the format is really that consistent, you can just relax your expression a little and it'll wo...
[ 3, 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004433307_python_regex.txt
Q: Shortest way to convert these bytes to int in python? I'm converting the following string to it's unsigned integer representation: str = '\x00\x00\x00\x00\x00\x00\x01\xFF' I can use struct.unpack('8B', str) to get the tuple representation (0,0,0,0,0,0,1,255), but what's the quickest/easiest way to convert this tup...
Shortest way to convert these bytes to int in python?
I'm converting the following string to it's unsigned integer representation: str = '\x00\x00\x00\x00\x00\x00\x01\xFF' I can use struct.unpack('8B', str) to get the tuple representation (0,0,0,0,0,0,1,255), but what's the quickest/easiest way to convert this tuple to an int? Right now, my code is def unpack_str(s): i ...
[ ">>> struct.unpack('>q', s)[0]\n511\n\n", "Just unpack as a long long (64-bit integer):\nstruct.unpack('>Q', str)\n\nQ = unsigned long long. Switch to q if the string represents a signed long long.\nThe > indicates big-endian byte order. Use < to indicate little-endian byte order.\n", "def unpack_str(bytes):\n ...
[ 6, 2, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004433017_python.txt
Q: Synchronize a cleanup process between threads I am planning a Python thread based project. Each thread needs to run an external program using subprocess.Popen and collect some output. As a side affect,the external program may leave: Temp files Zombie Process I can't run this cleanup for each thread, cause I don...
Synchronize a cleanup process between threads
I am planning a Python thread based project. Each thread needs to run an external program using subprocess.Popen and collect some output. As a side affect,the external program may leave: Temp files Zombie Process I can't run this cleanup for each thread, cause I don't have a way to make the association of a threads ...
[ "OK, you've really got two things to look out for:\n\nThe cleanup mustn't start until the worker threads have finished a round of iteration\nThe worker threads mustn't start the next iteration until the cleanup is complete.\n\nI think the best way to do this is to give each worker thread a pair of events (threading...
[ 1 ]
[]
[]
[ "multithreading", "python", "thread_safety" ]
stackoverflow_0004433207_multithreading_python_thread_safety.txt
Q: Python EOF for multi byte requests of file.read() The Python docs on file.read() state that An empty string is returned when EOF is encountered immediately. The documentation further states: Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to s...
Python EOF for multi byte requests of file.read()
The Python docs on file.read() state that An empty string is returned when EOF is encountered immediately. The documentation further states: Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blo...
[ "You are not thinking with your snake skin on... Python is not C. \nFirst, a review: \n\nst=f.read() reads to EOF, or if opened as a binary, to the last byte;\nst=f.read(n) attempts to reads n bytes and in no case more than n bytes;\nst=f.readline() reads a line at a time, the line ends with '\\n' or EOF;\nst=f.rea...
[ 23, 0 ]
[]
[]
[ "eof", "python" ]
stackoverflow_0004426581_eof_python.txt
Q: python 2.5: how to convert float to hex? I want to convert a float (the output of time.time()) in hex using python 2.4/2.5. I found tons of examples that convert hex to float, but I cannot find anything that allows me to do what the float.hex() of python >= 2.6 does. A: It can't be done portably in Python before...
python 2.5: how to convert float to hex?
I want to convert a float (the output of time.time()) in hex using python 2.4/2.5. I found tons of examples that convert hex to float, but I cannot find anything that allows me to do what the float.hex() of python >= 2.6 does.
[ "It can't be done portably in Python before version 2.6; it needs the information in sys.float_info, which is new in Python 2.6.\nIf you want to do it non-portably, i.e. for your particular platform, you would need to look at the float.h file for the C compiler that was used to produce your 2.4/5 Python, or at the ...
[ 3, 1, 1 ]
[]
[]
[ "floating_point", "hex", "python" ]
stackoverflow_0004432491_floating_point_hex_python.txt
Q: Python ctypes module: NULL pointer access while extending pointer array I was trying to use the ctypes module for a project. I was creating a dynamically allocated array of "max_entries" pairs and once the array was exhausted, I was creating a new array of size (1.5 * max_entries) and copying the contents from the...
Python ctypes module: NULL pointer access while extending pointer array
I was trying to use the ctypes module for a project. I was creating a dynamically allocated array of "max_entries" pairs and once the array was exhausted, I was creating a new array of size (1.5 * max_entries) and copying the contents from the old array to the new array. Unfortunately, when I try to access the content...
[ "The problem is that the statement\nold_arr = x.entries\n\ndoesn't do what you expect it to. Take a look at old_arr._b_base_, and you see that it is a pointer pointing into MY_ARR. So when the underlying pointer changes, old_arr suddenly points to the new array, and the loop assigns lots of null pointers. To fix th...
[ 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0004431329_ctypes_python.txt
Q: How can I store objects other than strings in a wxPython ComboBox? I have a list of Vertex objects, each with their own labels and id's. How can I use this list as a model for a wxPython ComboBox such that when a user selects an option, I can immediately retrieve the Vertex id? It appears that ComboBox only accep...
How can I store objects other than strings in a wxPython ComboBox?
I have a list of Vertex objects, each with their own labels and id's. How can I use this list as a model for a wxPython ComboBox such that when a user selects an option, I can immediately retrieve the Vertex id? It appears that ComboBox only accepts strings as a model. I cannot create a dictionary of label to id pairs...
[ "This topic came up on the wxPython IRC channel earlier today, but in regards to the ListBox. Fortunately, both the widgets inherit from wx.ItemContainer, so you can do the following:\nfor item in ObjList:\n self.myCboBox.append(item.label, item)\n\nThen in the event handler, you'd do something like:\nitemObject...
[ 5, 0 ]
[]
[]
[ "combobox", "python", "wxpython" ]
stackoverflow_0004433715_combobox_python_wxpython.txt
Q: how can i get value fron the URL in python appengine? if i have this URL in from python code on appengine http://localhost:8080/blog/view/2f1cab5844fb432b8426ae666c4ac493 how can i get the value of the key : 2f1cab5844fb432b8426ae666c4ac493 A: @Herms answer will work, but you may prefer this instead: In the co...
how can i get value fron the URL in python appengine?
if i have this URL in from python code on appengine http://localhost:8080/blog/view/2f1cab5844fb432b8426ae666c4ac493 how can i get the value of the key : 2f1cab5844fb432b8426ae666c4ac493
[ "@Herms answer will work, but you may prefer this instead:\nIn the code that creates your webapp instance, capture the key part of the URL with a regex, like:\ndef main():\n application = webapp.WSGIApplication( [\n (r'/blog/view/(\\w+)', MyBlogViewHandler),\n ## others listed here...\n ]...
[ 2, 0 ]
[]
[]
[ "android", "python", "url" ]
stackoverflow_0004433893_android_python_url.txt
Q: Dict key as function in a class How do I call the get_productname function from the dictionary in the code below? test = { 'get_productname' : { 'id' : 1, 'active' : 1, } } class search(object): def __init__(self): f...
Dict key as function in a class
How do I call the get_productname function from the dictionary in the code below? test = { 'get_productname' : { 'id' : 1, 'active' : 1, } } class search(object): def __init__(self): for key, value in test.items(): ...
[ "You want the getattr function.\nclass search(object):\n def __init__(self):\n for key, value in test.items():\n if test[key]['active']:\n getattr(self, key)(test['key']['id'])\n\nPer the comments, if you're not 100% positive that the method will exist you can perform a hasattr(self, name) check ahe...
[ 8, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004433683_python.txt
Q: Python, Linux: How to delete unicode files? I have a file whose name contains accents. I'm trying to use Python's os.remove to delete it, but I keep getting an UnicodeDecodeError. I'm using Ubuntu, Python 2.6 and my locale LANG=en_US.utf-8 Thanks. A: There are no "unicode files" in Linux. Encode your unicode wit...
Python, Linux: How to delete unicode files?
I have a file whose name contains accents. I'm trying to use Python's os.remove to delete it, but I keep getting an UnicodeDecodeError. I'm using Ubuntu, Python 2.6 and my locale LANG=en_US.utf-8 Thanks.
[ "There are no \"unicode files\" in Linux. Encode your unicode with the encoding used by the filesystem.\n", "I'm guessing you are doing this:\nos.unlink(u\"Thé file näme.dôc\")\n\nTry this instead:\nos.unlink(u\"Thé file näme.dôc\".encode(\"utf8\"))\n\n" ]
[ 5, 5 ]
[]
[]
[ "linux", "python", "ubuntu", "unicode" ]
stackoverflow_0004434384_linux_python_ubuntu_unicode.txt
Q: Font location for django-cairo-text Where do you put custom fonts for django-cairo-text? https://github.com/akaihola/django-cairo-text A: Wherever the font engine for your OS expects them to be. If you want to use a custom font file then you'll need to load it manually then inject it into the CAIROTEXT_PRESETS ...
Font location for django-cairo-text
Where do you put custom fonts for django-cairo-text? https://github.com/akaihola/django-cairo-text
[ "Wherever the font engine for your OS expects them to be. If you want to use a custom font file then you'll need to load it manually then inject it into the CAIROTEXT_PRESETS setting.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "text" ]
stackoverflow_0004434421_django_python_text.txt
Q: Upnp: list portmappings I'm currently looking at the miranda upnp tool (http://code.google.com/p/mirandaupnptool/). Is there a way for upnp to list all portmappings. I was able to forward ports an delete portmappings but I couldn't find a way to list all mappings. I've read somewhere that this mac os x tool does l...
Upnp: list portmappings
I'm currently looking at the miranda upnp tool (http://code.google.com/p/mirandaupnptool/). Is there a way for upnp to list all portmappings. I was able to forward ports an delete portmappings but I couldn't find a way to list all mappings. I've read somewhere that this mac os x tool does list all portmappings on your ...
[ "Some devices support the GetGenericPortMappingEntry method.\n" ]
[ 0 ]
[]
[]
[ "python", "upnp" ]
stackoverflow_0004434201_python_upnp.txt
Q: python - support .send() for a class? Writing a class, how do I implement foo.send(item) ? __iter__ allows iterating over the class like a generator, what if I want it to be a coroutine? A: Here is a basic example of a coroutine: def coroutine(func): def start(*args,**kwargs): cr = func(*args,**kwarg...
python - support .send() for a class?
Writing a class, how do I implement foo.send(item) ? __iter__ allows iterating over the class like a generator, what if I want it to be a coroutine?
[ "Here is a basic example of a coroutine:\ndef coroutine(func):\n def start(*args,**kwargs):\n cr = func(*args,**kwargs)\n cr.next()\n return cr\n return start\n\n@coroutine\ndef grep(pattern):\n print \"Looking for %s\" % pattern\n while True:\n line = (yield)\n if pat...
[ 7 ]
[]
[]
[ "class", "coroutine", "python" ]
stackoverflow_0004433886_class_coroutine_python.txt
Q: USB Barcode scanner research I'm doing some feasibility research with regards to a (large) book cataloging project. Any help would w/r/t good sources of information would be appreciated but the things I would specifically like to know are: 1.)does python have any modules for use with barcode readers (preferably US...
USB Barcode scanner research
I'm doing some feasibility research with regards to a (large) book cataloging project. Any help would w/r/t good sources of information would be appreciated but the things I would specifically like to know are: 1.)does python have any modules for use with barcode readers (preferably USB)? What other programs are availa...
[ "\nYou don't need any - most USB barcode scanners emulate a keyboard - if you scan a barcode it simply sends a series of key presses representing the numbers (or text if it's a more advanced barcode encoding) encoded in the barcode. Most scanners are pretty configurable so you could configure it to send a special ...
[ 10, 3 ]
[]
[]
[ "barcode", "barcode_scanner", "python" ]
stackoverflow_0004434959_barcode_barcode_scanner_python.txt