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: Turbogears2 and py.test I'm switching our testing environment from Nose to py.test for testing a Turbogears2 web application. Currently, when Nose runs it gathers information from a testing configuration file (test.ini) that holds all the testing variables the application needs. And it seems to do so in an automat...
Turbogears2 and py.test
I'm switching our testing environment from Nose to py.test for testing a Turbogears2 web application. Currently, when Nose runs it gathers information from a testing configuration file (test.ini) that holds all the testing variables the application needs. And it seems to do so in an automatic way (I'm simply running no...
[ "As far as py.test's part is concerned, you can implement something like this:\n# content of conftest.py\ndef pytest_sessionstart():\n # setup resources before any test is executed\n\ndef pytest_sessionfinish():\n # teardown resources after the last test has executed\n\nSuch a conftest.py file should currentl...
[ 1 ]
[]
[]
[ "pytest", "python", "testing", "turbogears", "unit_testing" ]
stackoverflow_0003835078_pytest_python_testing_turbogears_unit_testing.txt
Q: google storage api put file problem in python I'm trying to upload a file to Google storage, but my code freezes and does not respond. Please help me. Mycode : def PutFile(self,filename): conn = httplib.HTTPConnection("%s.commondatastorage.googleapis.com" % self.bucket) conn.set_debuglevel(2) dd = "...
google storage api put file problem in python
I'm trying to upload a file to Google storage, but my code freezes and does not respond. Please help me. Mycode : def PutFile(self,filename): conn = httplib.HTTPConnection("%s.commondatastorage.googleapis.com" % self.bucket) conn.set_debuglevel(2) dd = "%s" % datetime.datetime.utcnow().strftime("%a, %d %...
[ "i resolve my problem myself :) my code :\n conn = httplib.HTTPConnection(\"mustafa-yontar.commondatastorage.googleapis.com\")\n conn.set_debuglevel(2)\n f = open(filename,\"r\")\n m = hashlib.md5()\n m.update(f.read())\n h = m.hexdigest()\n has = h\n dd = \"%...
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003822385_python.txt
Q: Python and executing php files? Possible Duplicate: Start local PHP script w/ local Python script How do you execute a php file and then view the output of it? os.system("php ./index.php") Does not work only returns 0 A: What you need is the os.popen function. It runs the command and returns the stdout pipe f...
Python and executing php files?
Possible Duplicate: Start local PHP script w/ local Python script How do you execute a php file and then view the output of it? os.system("php ./index.php") Does not work only returns 0
[ "What you need is the os.popen function. It runs the command and returns the stdout pipe for that commands output. You can also capture the stdin, stderr by using os.popen2, popen3\nimport os\n\noutp = os.popen('php ./index.php')\ntext = outp.read() # this will block until php finishes\n # and ret...
[ 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0003837605_php_python.txt
Q: Popen.communicate() throws OSError: "[Errno 10] No child processes" I'm trying to start up a child process and get its output on Linux from Python using the subprocess module: #!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, ...
Popen.communicate() throws OSError: "[Errno 10] No child processes"
I'm trying to start up a child process and get its output on Linux from Python using the subprocess module: #!/usr/bin/python2.4 import subprocess p = subprocess.Popen(['ls', '-l', '/etc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() However, I expe...
[ "Are you intercepting SIGCHLD in the script? If you are then Popen will not run as expected since it relies on it's own handler for that signal. \nYou can check for SIGCHLD handlers by commenting out the Popen call and then running:\nstrace python <your_script.py> | grep SIGCHLD\n\nif you see something similar to:\...
[ 7, 3, 0, 0 ]
[]
[]
[ "linux", "python" ]
stackoverflow_0001008858_linux_python.txt
Q: Python : No translation file found for domain using custom locale folder I have the following structure : / |- main.py |- brainz | |- __init__.py | |- Brainz.py |- datas |- locale |- en_US |- LC_MESSAGES |- brainz.mo |- brainz.po In my __...
Python : No translation file found for domain using custom locale folder
I have the following structure : / |- main.py |- brainz | |- __init__.py | |- Brainz.py |- datas |- locale |- en_US |- LC_MESSAGES |- brainz.mo |- brainz.po In my __init__.py there is the following lines : import locale import gettext import o...
[ "I think your __init__.py should be something like:\nimport locale\nimport gettext\nimport os\n\ncurrent_locale, encoding = locale.getdefaultlocale()\n\nlocale_path = 'datas/locale/'\nlanguage = gettext.translation ('brainz', locale_path, [current_locale] )\nlanguage.install()\n\n" ]
[ 10 ]
[]
[]
[ "gettext", "python" ]
stackoverflow_0003837683_gettext_python.txt
Q: How to create a simple Gradient Descent algorithm I'm studying simple machine learning algorithms, beginning with a simple gradient descent, but I've got some trouble trying to implement it in python. Here is the example I'm trying to reproduce, I've got data about houses with the (living area (in feet2), and num...
How to create a simple Gradient Descent algorithm
I'm studying simple machine learning algorithms, beginning with a simple gradient descent, but I've got some trouble trying to implement it in python. Here is the example I'm trying to reproduce, I've got data about houses with the (living area (in feet2), and number of bedrooms) with the resulting price : Living area...
[ "First issue is that running this with only one piece of data gives you an underdetermined system... this means it may have an infinite number of solutions. With three variables, you'd expect to have at least 3 data points, preferably much higher.\nSecondly using gradient descent where the step size is a scaled ver...
[ 8 ]
[]
[]
[ "machine_learning", "python" ]
stackoverflow_0003837692_machine_learning_python.txt
Q: Set producer value for PDFs created by QPrinter I'm currently producing PDFs using python and PyQT. I'd like to change the "Producer" value of the PDF's document information, currently it is set to "Qt 4.6.2 (C) 2010 Nokia Corporation and/or its subsidiary(-ies)". I've looked through the QPrinter reference, and ...
Set producer value for PDFs created by QPrinter
I'm currently producing PDFs using python and PyQT. I'd like to change the "Producer" value of the PDF's document information, currently it is set to "Qt 4.6.2 (C) 2010 Nokia Corporation and/or its subsidiary(-ies)". I've looked through the QPrinter reference, and nothing obvious stuck out that I could set. How do I ...
[ "You could use pdftk to change the metadata of your PDFs:\necho \"InfoKey: Producer\" > producerinfo\necho \"InfoValue: my program\" >> producerinfo\npdftk file.pdf update_info producerinfo output newfile.pdf\nrm producerinfo\n\n" ]
[ 2 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0003835921_pyqt_python_qt.txt
Q: how to run python inside netbeans? I installed the plugin for python and it detects the python code, but how do I run it from Netbeans? A: You need to install python first. Then Netbeans will detect the installation and you can run it from there. More info here: http://wiki.netbeans.org/Python
how to run python inside netbeans?
I installed the plugin for python and it detects the python code, but how do I run it from Netbeans?
[ "You need to install python first.\nThen Netbeans will detect the installation and you can run it from there. More info here: http://wiki.netbeans.org/Python\n" ]
[ 1 ]
[]
[]
[ "netbeans", "python" ]
stackoverflow_0003838875_netbeans_python.txt
Q: Python: pytz returning unusable __repr__() I understand that repr()'s purpose is to return a string, that can be used to be evaluated as a python command and return the same object. Unfortunately, pytz does not seem to be very friendly with this function, although it should be quite easy, since pytz instances are ...
Python: pytz returning unusable __repr__()
I understand that repr()'s purpose is to return a string, that can be used to be evaluated as a python command and return the same object. Unfortunately, pytz does not seem to be very friendly with this function, although it should be quite easy, since pytz instances are created with a single call: import datetime, p...
[ "import datetime\nimport pytz\nimport pytz.tzinfo\n\ndef tzinfo_repr(self):\n return 'pytz.timezone({z})'.format(z=self.zone)\npytz.tzinfo.DstTzInfo.__repr__=tzinfo_repr\n\nberlin=pytz.timezone('Europe/Berlin')\nnow = datetime.datetime.now(berlin)\nprint(repr(now))\n# datetime.datetime(2010, 10, 1, 14, 39, 4, 45...
[ 1 ]
[]
[]
[ "instance", "python", "pytz", "representation" ]
stackoverflow_0003838578_instance_python_pytz_representation.txt
Q: Django : load a restricted set of fields of objects loaded using a foreign key I have the following code, using Django ORM routes =Routes.objects.filter(scheduleid=schedule.id).only('externalid') t_list = [(route.externalid, route.vehicle.name) for route in routes]) and it is very slow, because the vehicl...
Django : load a restricted set of fields of objects loaded using a foreign key
I have the following code, using Django ORM routes =Routes.objects.filter(scheduleid=schedule.id).only('externalid') t_list = [(route.externalid, route.vehicle.name) for route in routes]) and it is very slow, because the vehicle objects are huge (dozens of fields, and I cannot change that, it is coming from a ...
[ "You should be able to do this, I think. Warning: not tested Tested using local models. Generated query looked good.\nroutes = Routes.objects.select_related('vehicle').filter(**conditions).only(\n 'externalid', 'vehicle__name')\n\nFor this to work there should be a vehicle foreign key field declared in R...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003838833_django_django_models_python.txt
Q: Parsing Windows Event Logs, is it possible? I am doing a little research into the feasibility of a project I have in mind. It involves doing a little forensic work on images of hard drives, and I have been looking for information on how to analyze saved windows event log files. I do not require the ability to moni...
Parsing Windows Event Logs, is it possible?
I am doing a little research into the feasibility of a project I have in mind. It involves doing a little forensic work on images of hard drives, and I have been looking for information on how to analyze saved windows event log files. I do not require the ability to monitor current events, I simply want to be able to v...
[ "You can use Microsoft's LogParser, a command line tool, to extract data from the event logs into CSV or various other formats. The default mode extracts from the event log on the running system, but according to the documentation you can also tell it to query against a group of EVT files. In your case, you coul...
[ 3, 0 ]
[]
[]
[ "java", "python" ]
stackoverflow_0002907640_java_python.txt
Q: how to include python modules in linux? I found this xgoogle python modules http://github.com/pkrumins/xgoogle, very interesting. How exactly should i include or install these files in linux?? if i want to do something like this using xgoogle python module? >>from xgoogle.search import GoogleSearch I know that w...
how to include python modules in linux?
I found this xgoogle python modules http://github.com/pkrumins/xgoogle, very interesting. How exactly should i include or install these files in linux?? if i want to do something like this using xgoogle python module? >>from xgoogle.search import GoogleSearch I know that we can use from, import to use modules, but to...
[ "You could either do the usual install dance:\npython setup.py install\n\nor simply include the files in a known directory and include that directory in the PYTHONPATH:\n$ export PYTHONPATH=/contains/modules:$PYTHONPATH\n\nHere's a detailed documentation on Installing Python Modules: http://docs.python.org/install/...
[ 5, 0 ]
[]
[]
[ "linux", "module", "python", "xgoogle" ]
stackoverflow_0003839334_linux_module_python_xgoogle.txt
Q: How to check if a QWidget is already showing? I'm developing a plugin UI for an existing application using PyQt4. The window is created using uic.loadUi() on the press of a button in the main window. The problem is that if I press the button again (while the window is showing) the window is re-created and unsaved ...
How to check if a QWidget is already showing?
I'm developing a plugin UI for an existing application using PyQt4. The window is created using uic.loadUi() on the press of a button in the main window. The problem is that if I press the button again (while the window is showing) the window is re-created and unsaved changes are lost. I don't want to make the window m...
[ "You should initializer a pointer to the QWidget (member variable) to 0.\nWhen the button is pressed, check if the pointer is 0 - if it is, load and show the widget, and assign the pointer variable to point to the new widget. If the pointer is not null when the button is pressed, call widget->raise() and widget->ac...
[ 2, 0 ]
[]
[]
[ "pyqt4", "python", "qt4", "user_interface" ]
stackoverflow_0003839426_pyqt4_python_qt4_user_interface.txt
Q: compress a string in python 3? I don't understand in 2.X it worked : import zlib zlib.compress('Hello, world') now i have a : zlib.compress("Hello world!") TypeError: must be bytes or buffer, not str How can i compress my string ? Regards Bussiere A: This is meant to enforce that you actually have a defined en...
compress a string in python 3?
I don't understand in 2.X it worked : import zlib zlib.compress('Hello, world') now i have a : zlib.compress("Hello world!") TypeError: must be bytes or buffer, not str How can i compress my string ? Regards Bussiere
[ "This is meant to enforce that you actually have a defined encoding.\nzlib.compress(\"Hello, world\".encode(\"utf-8\"))\nb'x\\x9c\\xf3H\\xcd\\xc9\\xc9\\xd7Q(\\xcf/\\xcaI\\x01\\x00\\x1b\\xd4\\x04i'\nzlib.compress(\"Hello, world\".encode(\"ascii\"))\nb'x\\x9c\\xf3H\\xcd\\xc9\\xc9\\xd7Q(\\xcf/\\xcaI\\x01\\x00\\x1b\\xd...
[ 21, 20 ]
[]
[]
[ "compression", "python", "python_3.x", "string", "zlib" ]
stackoverflow_0003839323_compression_python_python_3.x_string_zlib.txt
Q: Tkinter coordinates start at 3? I have the following code: from Tkinter import * master = Tk() canvas = Canvas(master, width=640, height=480, bd=0) canvas.pack() line_coords = (3, 3, 3, 100) canvas.create_line(*line_coords, fill='red') mainloop() This will draw a line in the top-left corner. Why is it that if ...
Tkinter coordinates start at 3?
I have the following code: from Tkinter import * master = Tk() canvas = Canvas(master, width=640, height=480, bd=0) canvas.pack() line_coords = (3, 3, 3, 100) canvas.create_line(*line_coords, fill='red') mainloop() This will draw a line in the top-left corner. Why is it that if I change line_coords to (2, 2, 2, 100...
[ "Canvas coordinates unequivocally start at zero, and the window frame has nothing to do with your problem. \nThe problem is that the default highlightthickness for a canvas on your system is 3, and that is what is obscuring your line. Try setting the highlightthickness to zero and you'll see your line even if the x...
[ 3, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0003835610_python_tkinter.txt
Q: Python set intersection question I have three sets: s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] # true, 16 and 14 s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] # false I want a function that will return True if every set in the list intersects with at least one other set in the list. ...
Python set intersection question
I have three sets: s0 = [set([16,9,2,10]), set([16,14,22,15]), set([14,7])] # true, 16 and 14 s1 = [set([16,9,2,10]), set([16,14,22,15]), set([7,8])] # false I want a function that will return True if every set in the list intersects with at least one other set in the list. Is there a built-in for this or a simp...
[ "all(any(a & b for a in s if a is not b) for b in s)\n\n", "Here's a very simple solution that's very efficient for large inputs:\ndef g(s):\n import collections\n count = collections.defaultdict(int)\n for a in s:\n for x in a:\n count[x] += 1\n return all(any(count[x] > 1 for x in ...
[ 14, 5, 2, 2, 1, 1, 0, 0 ]
[]
[]
[ "python", "set" ]
stackoverflow_0003837426_python_set.txt
Q: Trouble importing BeautifulSoup in python I've unpacked BeautifulSoup into c:\python2.6\lib\site-packages, which is in sys.path, but when I enter import BeautifulSoup I get an import error saying no such module exists. Obviously I'm doing something stupid... what is it? A: You might have more than one python ver...
Trouble importing BeautifulSoup in python
I've unpacked BeautifulSoup into c:\python2.6\lib\site-packages, which is in sys.path, but when I enter import BeautifulSoup I get an import error saying no such module exists. Obviously I'm doing something stupid... what is it?
[ "You might have more than one python version installed? Check the version you are running.\nAlso, I found using easy_install worked well for installing BeautifulSoup.\n" ]
[ 2 ]
[]
[]
[ "importerror", "module", "python" ]
stackoverflow_0003840177_importerror_module_python.txt
Q: Numpy csv script gives 'ValueError: setting an array element with a sequence' I have a python script that successfully loads a csv file into a 2d numpy array and which then successfully extracts the value of a desired cell based on its column and row header values. For diagnostic purposes, I have the script print...
Numpy csv script gives 'ValueError: setting an array element with a sequence'
I have a python script that successfully loads a csv file into a 2d numpy array and which then successfully extracts the value of a desired cell based on its column and row header values. For diagnostic purposes, I have the script print the contents of the data matrix before it is put into a numpy array. The script w...
[ "found the answer.\nI needed to change the following line of code:\ndata = [[] for dummy in xrange(11)]\n\nxrange needed to be set to 11 and not to 13.\nsimple answer, but it took a lot of digging.\nthis thread is answered/finished now.\n", "why do you write your own csv loader?\nnumpy.loadtxt? or in your case wi...
[ 3, 0 ]
[]
[]
[ "arrays", "csv", "numpy", "python" ]
stackoverflow_0003835083_arrays_csv_numpy_python.txt
Q: Running a command on Window minimization in Tkinter I have a Tkinter window whenever the minimize button is pressed I'd like to run a command, how do I do this? I know w.protocol("WM_DELETE_WINDOW", w.command) will run a command on exit. A: You can bind to the <Unmap> event. For example, run the following cod...
Running a command on Window minimization in Tkinter
I have a Tkinter window whenever the minimize button is pressed I'd like to run a command, how do I do this? I know w.protocol("WM_DELETE_WINDOW", w.command) will run a command on exit.
[ "You can bind to the <Unmap> event. \nFor example, run the following code and then minimize the main window. The tool window should disappear when the main window is minimized.\nimport Tkinter as tk\n\nclass App:\n def __init__(self):\n self.root = tk.Tk()\n tk.Label(self.root, text=\"main window\"...
[ 5 ]
[]
[]
[ "python", "tkinter", "windows_7" ]
stackoverflow_0003836489_python_tkinter_windows_7.txt
Q: What's the best way to transfer data with a remote application across the internet? I'm making a relatively simple program which will also be running on a few friends computers and they need to share some information. They will need to exchange ips in case they are changed via dhcp and maybe a few other things in ...
What's the best way to transfer data with a remote application across the internet?
I'm making a relatively simple program which will also be running on a few friends computers and they need to share some information. They will need to exchange ips in case they are changed via dhcp and maybe a few other things in the future, but right now that's it (this will likely be used to update the program if I ...
[ "If change of IP address is your main concern, a service like dyndns.com would certainly be helpful. (You can get automatic clients as well, which will update your DNS entry when your IP address changes.)\nAfter this for data transfer, you're probably better off using existing protocols (e.g. HTTP, FTP, ...). There...
[ 2 ]
[]
[]
[ "network_programming", "networking", "python" ]
stackoverflow_0003840284_network_programming_networking_python.txt
Q: Cairo context and persistence? I am just getting started using pycairo, and I ran into the following interesting error. The program I write creates a simple gtk window, draws a rectangle on it, and then has a callback to draw a random line on any kind of keyboard input. However, it seems that with each keyboard in...
Cairo context and persistence?
I am just getting started using pycairo, and I ran into the following interesting error. The program I write creates a simple gtk window, draws a rectangle on it, and then has a callback to draw a random line on any kind of keyboard input. However, it seems that with each keyboard input, I have to create a new context,...
[ "Cairo drawings don't persist at all. (It's best not to think of them as \"objects\" -- it's not like a canvas library where you can move them around or transform them after you've drawn them.) You have to do all drawing in the expose handler, or it will, as you have found out, disappear whenever the window is redr...
[ 2, 1, 0 ]
[]
[]
[ "cairo", "gtk", "pycairo", "pygtk", "python" ]
stackoverflow_0003513172_cairo_gtk_pycairo_pygtk_python.txt
Q: vlc python bindings - how to receive keyboard input? I'm trying to use VLC's python bindings to create my own little video player. The demo implementation is quite simple and nice, but it requires all the keyboard commands to be typed into the console from which the script was run. Is there any way I can handle ke...
vlc python bindings - how to receive keyboard input?
I'm trying to use VLC's python bindings to create my own little video player. The demo implementation is quite simple and nice, but it requires all the keyboard commands to be typed into the console from which the script was run. Is there any way I can handle keyboard input also when the video player itself has focus? ...
[ "The best way to control VLC from Python is to talk via the web interface. I tried to get the VLC Python bindings to work and it was more trouble than it's worth, especially for cross-platform stuff. Just use wireshark or something similar to see what the web interface commands look like(they're very simple). I'...
[ 1, 1, 0 ]
[]
[]
[ "event_handling", "python", "vlc", "windows" ]
stackoverflow_0002643244_event_handling_python_vlc_windows.txt
Q: Optimize two simple nested loops I have been trying to optimize the two following nested loops: def startbars(query_name, commodity_name): global h_list nc, s, h_list = [], {}, {} query = """ SELECT wbcode, Year, """+query_name+""" FROM innovotable WHERE commodity='"""+commodity_n...
Optimize two simple nested loops
I have been trying to optimize the two following nested loops: def startbars(query_name, commodity_name): global h_list nc, s, h_list = [], {}, {} query = """ SELECT wbcode, Year, """+query_name+""" FROM innovotable WHERE commodity='"""+commodity_name+"""' and """+que...
[ "Your code isn't complete which makes it hard to give good advice but:\n\nInner loop doesn't depend on outer-loop, so pull it out of the outer loop.\nmax(nc) is a constant after first loop, so pull it out of the loops.\n\nAlso you need to know how slow the current code is, and how fast you need it to be, otherwise ...
[ 5 ]
[]
[]
[ "nested_loops", "optimizer_hints", "python" ]
stackoverflow_0003841051_nested_loops_optimizer_hints_python.txt
Q: Monitor Synchronization: Implementing multiple condition variables I am implementing monitor synchronization. I was wondering how does implementing multiple condition variables works. So a condition variable has method wait() which puts it on the wait queue for a specific lock tied to this condition variable. So i...
Monitor Synchronization: Implementing multiple condition variables
I am implementing monitor synchronization. I was wondering how does implementing multiple condition variables works. So a condition variable has method wait() which puts it on the wait queue for a specific lock tied to this condition variable. So if I have multiple condition variables, do each wait call create its own ...
[ "A.notifyAll() should only wake up the thread running foo(). The wait queue your threads are wait()-ing in is part of the condition variable, not the lock. The lock does have its own wait queue, but it's only used by threads trying to acquire the lock. When your thread sleeps in a CV, it doesn't hold the lock, a...
[ 2 ]
[]
[]
[ "monitor", "operating_system", "python", "synchronization" ]
stackoverflow_0003826167_monitor_operating_system_python_synchronization.txt
Q: Read the print values of an imported class This is probably very basic, but it's giving me a headache, and I'm not sure what method to even approach it with, making the googling tough. If I have a class in a module that I'm importing with various prints throughout, how can I read the prints as they come so that I ...
Read the print values of an imported class
This is probably very basic, but it's giving me a headache, and I'm not sure what method to even approach it with, making the googling tough. If I have a class in a module that I'm importing with various prints throughout, how can I read the prints as they come so that I may output them to a PyQT text label? class Work...
[ "Instead of writing your own statusWrapper class, you could use a StringIO object as stdout. Something like: \ndef __init__(self, widget):\n QtCore.QThread.__init__(self)\n\ndef run(self):\n real_stdout = sys.stdout\n sys.stdout = StringIO.StringIO()\n self.runModule()\n label_text = sys.stdout.getva...
[ 1, 1, 0 ]
[]
[]
[ "class", "printing", "pyqt", "python" ]
stackoverflow_0003840050_class_printing_pyqt_python.txt
Q: Getting %def references in mako python is there a way to use %def references somehow, basic idea being: % if condition_a: % func = %def_a % elif condition_b: % func = %def_b ... etc ... ${func( params )} A: Yes like this: % if condition_a: <% func = def_a %> % elif condition_b: <% func = def_b %> % endif ...
Getting %def references in mako python
is there a way to use %def references somehow, basic idea being: % if condition_a: % func = %def_a % elif condition_b: % func = %def_b ... etc ... ${func( params )}
[ "Yes like this:\n% if condition_a:\n<% func = def_a %>\n% elif condition_b:\n<% func = def_b %>\n% endif\n\n${func( params )}\n\n@timmy: I have no idea what you mean, maybe this?\n<% func = some_dict[key] %>\n${func( params )}\n\nYou can put any Python code inside <% .. %>, see the mako docs!\n" ]
[ 2 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003841512_mako_python.txt
Q: Which XML style is better when handling it with Python's ElementTree? I'd like to store some relatively simple stuff in XML in a cascading manner. The idea is that a build can have a number of parameter sets and the Python scripts creates the necessary build artifacts (*.h etc) by reading these sets and if two set...
Which XML style is better when handling it with Python's ElementTree?
I'd like to store some relatively simple stuff in XML in a cascading manner. The idea is that a build can have a number of parameter sets and the Python scripts creates the necessary build artifacts (*.h etc) by reading these sets and if two sets have the same parameter, the latter one replaces the former. There are (a...
[ "You're both right, but I would pick #1 where possible, except for the text content:\n\n1 is much more succinct and human-readable, thus less error-prone.\n\nComplete extensibility: YAGNI. YAGNI is not always true but if you're confident that you won't need extensibility, don't sacrifice other benefits for the sake...
[ 3, 1 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0003836866_lxml_python_xml.txt
Q: Django Admin app or roll my own? I'm just starting to use Django for a personal project. What are the pros and cons of using the built-in Admin application versus integrating my administrative functions into the app itself (by checking request.user.is_staff)? This is a community wiki because it could be considered...
Django Admin app or roll my own?
I'm just starting to use Django for a personal project. What are the pros and cons of using the built-in Admin application versus integrating my administrative functions into the app itself (by checking request.user.is_staff)? This is a community wiki because it could be considered a poll.
[ "It really depends on the project I guess. While you can do everything in the admin, when your app gets more complex using the admin gets more complex too. And if you want to make your app really easy to manage you want control over every little detail, which is not really possible with the admin app.\nI guess you ...
[ 17, 17, 7, 3, 3, 1, 1 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0000495879_django_django_admin_python.txt
Q: Extension Crashing Python on Import? I have a python extension that is built and installed through distutils (using mingw on windows). However on import of this module the interpreter crashes. Is there anyway to debug and figure out why it crashes? I did look around online and couldn't find anything specific, or a...
Extension Crashing Python on Import?
I have a python extension that is built and installed through distutils (using mingw on windows). However on import of this module the interpreter crashes. Is there anyway to debug and figure out why it crashes? I did look around online and couldn't find anything specific, or any examples. EDIT Sorry i am trying to com...
[ "Simply running the following may give you a clue about what call is causing the issue without having to break out a debugger. But if you just get a silent crash you're going to have to put on your detective hat as per Xavier's answer.\nstrace python -v -c \"import faultylib\"\n\n", "I suppose using gdb see http:...
[ 3, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0003840770_debugging_python.txt
Q: Python - Most efficient way to find how often each possible pair of words occurs in the same line in a text file? This particular problem is easy to solve, but I'm not so sure that the solution I'd arrive at would be computationally efficient. So I'm asking the experts! What would be the best way to go through a l...
Python - Most efficient way to find how often each possible pair of words occurs in the same line in a text file?
This particular problem is easy to solve, but I'm not so sure that the solution I'd arrive at would be computationally efficient. So I'm asking the experts! What would be the best way to go through a large file, collecting stats (for the entire file) on how often two words occur in the same line? For instance, if the t...
[ "from collections import defaultdict\nimport itertools as it\nimport re\n\npairs = defaultdict(int)\n\nfor line in lines:\n for pair in it.combinations(re.findall('\\w+', line), 2):\n pairs[tuple(pair)] += 1\n\nresultList = [pair + (occurences, ) for pair, occurences in pairs.iterkeys()]\n\n" ]
[ 4 ]
[]
[]
[ "compare", "dictionary", "line", "python", "statistics" ]
stackoverflow_0003842206_compare_dictionary_line_python_statistics.txt
Q: How do I get a size of an UTF-8 string in Bytes with Python Having an UTF-8 string like this: mystring = "işğüı" is it possible to get its (in memory) size in Bytes with Python (2.5)? A: Assuming you mean the number of UTF-8 bytes (and not the extra bytes that Python requires to store the object), it’s the same...
How do I get a size of an UTF-8 string in Bytes with Python
Having an UTF-8 string like this: mystring = "işğüı" is it possible to get its (in memory) size in Bytes with Python (2.5)?
[ "Assuming you mean the number of UTF-8 bytes (and not the extra bytes that Python requires to store the object), it’s the same as for the length of any other string. A string literal in Python 2.x is a string of encoded bytes, not Unicode characters.\nByte strings:\n>>> mystring = \"işğüı\"\n>>> print \"length of {...
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0003842487_python.txt
Q: Why does Tkinter frame resize when text box is added to it? With this code, the window is 500 by 500, which is what I'm going for: from tkinter import * root = Tk() frame = Frame(root, width=500, height=500) frame.pack() root.mainloop() When I add a text box to the frame, though, it shrinks to just the size of ...
Why does Tkinter frame resize when text box is added to it?
With this code, the window is 500 by 500, which is what I'm going for: from tkinter import * root = Tk() frame = Frame(root, width=500, height=500) frame.pack() root.mainloop() When I add a text box to the frame, though, it shrinks to just the size of the text box: from tkinter import * root = Tk() frame = Frame(ro...
[ "The frame by default has \"pack propagation\" turned on. That means the packer \"computes how large a master must be to just exactly meet the needs of its slaves, and it sets the requested width and height of the master to these dimensions\" (quoting from the official tcl/tk man pages [1]).\nFor the vast majority ...
[ 6 ]
[]
[]
[ "python", "tkinter", "user_interface" ]
stackoverflow_0003842551_python_tkinter_user_interface.txt
Q: Inline SVG Served By Python Script in Google App Engine Not Appearing I'm writing an app that pulls chunks of svg together and serves them as part of a page mixed with css and javascript. I'm using Python and Google App Engine. What I'm doing works fine on my local development server but fails to render once it's ...
Inline SVG Served By Python Script in Google App Engine Not Appearing
I'm writing an app that pulls chunks of svg together and serves them as part of a page mixed with css and javascript. I'm using Python and Google App Engine. What I'm doing works fine on my local development server but fails to render once it's deployed. So here's some test python to build a response: self.response.he...
[ "I solved the problem.\nThis line:\nself.response.headers.add_header('Content-Type','application/xhtml+xml')\n\nwas not working. I determined that by using http://web-sniffer.net to see what content-type accompanied the page, and it was always returning the default text/html.\nThe correct syntax is:\nself.response....
[ 6 ]
[]
[]
[ "google_app_engine", "python", "svg", "xhtml" ]
stackoverflow_0003840166_google_app_engine_python_svg_xhtml.txt
Q: Concatenate sequence from a predefined datastructure I've been struggling a little to build this piece of code, and I was wondering if there are others more simple/efficient way of doing this: fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}} def __buildPathFromSchema(s...
Concatenate sequence from a predefined datastructure
I've been struggling a little to build this piece of code, and I was wondering if there are others more simple/efficient way of doing this: fsSchema = {'published': {'renders': {'SIM': ('fold1', 'fold2'), 'REN': ('fold1', 'fold2')}}} def __buildPathFromSchema(self, schema, root=''): metaDirs = [] for ...
[ "You can use a recursive function to generate all the paths:\ndef flatten(data):\n if isinstance(data, tuple):\n for v in data:\n yield v\n else:\n for k in data:\n for v in flatten(data[k]):\n yield k + '\\\\' + v\n\nThis should be able to handle any kind of nested dictiona...
[ 2, 0, 0 ]
[]
[]
[ "python", "recursion" ]
stackoverflow_0003842927_python_recursion.txt
Q: Searching a python list quickly? I have a dictionary and a list. The list is made up of values. The dictionary has all of the values plus some more values. I'm trying to count the number of times the values in the list show up in the dictionary per key/values pair. It looks something like this: for k in dict: ...
Searching a python list quickly?
I have a dictionary and a list. The list is made up of values. The dictionary has all of the values plus some more values. I'm trying to count the number of times the values in the list show up in the dictionary per key/values pair. It looks something like this: for k in dict: count = 0 for value in dict[k]: if ...
[ "If you search in a list, then convert this list to a set, it will be much faster:\nlistSet = set(list)\n\nfor k, values in dict.iteritems():\n count = 0\n for value in values:\n if value in listSet:\n count += 1\n listSet.remove(value)\n dict[k].append(count)\n\nlist = [elem f...
[ 2, 2, 0, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0003842856_dictionary_list_python.txt
Q: How to write a "joiner" extension for Jinja2? Hi I've been trying to create an extension for jinja2 that would join multiple items with a separator, while skipping items (template fragments) that evaluate to whitespace. There are several of those fragments and you never know in advance which ones will be non-empty...
How to write a "joiner" extension for Jinja2?
Hi I've been trying to create an extension for jinja2 that would join multiple items with a separator, while skipping items (template fragments) that evaluate to whitespace. There are several of those fragments and you never know in advance which ones will be non-empty and which ones will. Sounds like a trivial task, b...
[ "Would the built-in joiner class potentially work? Here is a simple example from the documentation.\n{% set pipe = joiner(\"|\") %}\n{% if categories %} {{ pipe() }}\n Categories: {{ categories|join(\", \") }}\n{% endif %}\n{% if author %} {{ pipe() }}\n Author: {{ author() }}\n{% endif %}\n{% if can_edit %}...
[ 4 ]
[]
[]
[ "jinja2", "python", "templates" ]
stackoverflow_0003836770_jinja2_python_templates.txt
Q: Does urllib2 in Python 2.6.1 support proxy via https Does urllib2 in Python 2.6.1 support proxy via https? I've found the following at http://www.voidspace.org.uk/python/articles/urllib2.shtml: NOTE Currently urllib2 does not support fetching of https locations through a proxy. This can be a problem. I'm try...
Does urllib2 in Python 2.6.1 support proxy via https
Does urllib2 in Python 2.6.1 support proxy via https? I've found the following at http://www.voidspace.org.uk/python/articles/urllib2.shtml: NOTE Currently urllib2 does not support fetching of https locations through a proxy. This can be a problem. I'm trying automate login in to web site and downloading document...
[ "Fixed in Python 2.6.3 and several other branches:\n\n_bugs.python.org/issue1424152 (replace _ with http...)\nhttp://www.python.org/download/releases/2.6.3/NEWS.txt\nIssue #1424152: Fix for httplib, urllib2 to support SSL while working through\nproxy. Original patch by Christopher Li, changes made by Senthil Kumara...
[ 6, 3, 3 ]
[]
[]
[ "https", "proxy", "python", "urllib2" ]
stackoverflow_0001030113_https_proxy_python_urllib2.txt
Q: Mako calling function from string? Is there an easy way to call a function given a string name in mako? A: You should be able to look it up in the dict returned by globals(). Eg.: <$ func_name = 'my_function_name' %> ${globals()[func_name](...)} Although, this does smell rather nasty to me. If you could expand ...
Mako calling function from string?
Is there an easy way to call a function given a string name in mako?
[ "You should be able to look it up in the dict returned by globals(). Eg.:\n<$ func_name = 'my_function_name' %>\n${globals()[func_name](...)}\n\nAlthough, this does smell rather nasty to me. If you could expand upon your end game perhaps we can figure out something a bit saner.\n" ]
[ 5 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003843095_mako_python.txt
Q: Is there a way to cleanly exit out of a thread which is processing data from a (never-ending) generator? Here's the issue: I have a thread which runs a for-loop reading from a generator, doing some processing on that data, etc.. The generator always has data coming in, so no StopIteration exception is ever raised...
Is there a way to cleanly exit out of a thread which is processing data from a (never-ending) generator?
Here's the issue: I have a thread which runs a for-loop reading from a generator, doing some processing on that data, etc.. The generator always has data coming in, so no StopIteration exception is ever raised by it. I would like to stop this thread (cleanly) from the main thread (i.e., exit out of the for-loop which...
[ "You need the self:generator to have a timeout capability. Conceptually\nwait(1 sec);\n\nrather than just\nwait();\n\nI don't know if that's possible (show us your generator code). For example if you were reading from a pipe or a socket don't code\ngiveMeSomeBytes( buffer); // wait indefinately\n\ncode\ngiveMeSome...
[ 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003842410_python.txt
Q: Python lookup function I want to set up a lookup function with mako. on top of the template, i have <%! lookup = { 'key': function } %> <%def name="function()"> Output </%def> so i can use it later <%def name="body()"> ${lookup['key']()} </%def> this gives me a function is not a defined error. can...
Python lookup function
I want to set up a lookup function with mako. on top of the template, i have <%! lookup = { 'key': function } %> <%def name="function()"> Output </%def> so i can use it later <%def name="body()"> ${lookup['key']()} </%def> this gives me a function is not a defined error. can i get around this? i know...
[ "Maybe you could delay the lookup of function from dict-creation time to invocation time?\n<%!\n lookup = { 'key': lambda: function() }\n%>\n\nI haven't used Mako, but it works in the Python shell:\n>>> x = lambda: foo()\n>>> x\n<function <lambda> at 0x10047e050>\n>>> x()\nTraceback (most recent call last):\n F...
[ 1, 1 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0003842458_mako_python.txt
Q: Where is the source code for a Python egg? I'm attempting to add a video extension to the Python Markdown-2.0.3-py2.7.egg Things aren't working, so I want to use pdb debugger to see what's going on. I can't seem to find the source code to insert pdb. The egg is located here: /usr/local/lib/python2.7/site-package...
Where is the source code for a Python egg?
I'm attempting to add a video extension to the Python Markdown-2.0.3-py2.7.egg Things aren't working, so I want to use pdb debugger to see what's going on. I can't seem to find the source code to insert pdb. The egg is located here: /usr/local/lib/python2.7/site-packages/Markdown-2.0.3-py2.7.egg Using iPython, I can...
[ "An .egg file is a simple ZIP archive, you can extract the files using any ZIP-enabled application if you want. That being said, you can install an .egg into a folder for development by passing the develop option to setup.py. This will make setuptools use the sources in the specified folder and just link to them by...
[ 9, 5, 1 ]
[]
[]
[ "django", "egg", "markdown", "python", "setuptools" ]
stackoverflow_0003843097_django_egg_markdown_python_setuptools.txt
Q: py-appscript & events Is it possible to subscribe to events using py-appscript ? Example: I'd like to get a callback when a user changes a rating on iTunes. A: Some very few applications are recordable: that is, they'll send Apple Events to themselves which can be intercepted. iTunes is not one of these applicat...
py-appscript & events
Is it possible to subscribe to events using py-appscript ? Example: I'd like to get a callback when a user changes a rating on iTunes.
[ "Some very few applications are recordable: that is, they'll send Apple Events to themselves which can be intercepted. iTunes is not one of these applications. iTunes does send distributed notifications for music start/stop, but not for rating changes. Assuming you don't want to patch iTunes itself, your only rea...
[ 1 ]
[]
[]
[ "itunes", "macos", "py_appscript", "python", "sourceforge_appscript" ]
stackoverflow_0003842882_itunes_macos_py_appscript_python_sourceforge_appscript.txt
Q: Does this function have to use reduce() or is there a more pythonic way? If I have a value, and a list of additional terms I want multiplied to the value: n = 10 terms = [1,2,3,4] Is it possible to use a list comprehension to do something like this: n *= (term for term in terms) #not working... Or is the only wa...
Does this function have to use reduce() or is there a more pythonic way?
If I have a value, and a list of additional terms I want multiplied to the value: n = 10 terms = [1,2,3,4] Is it possible to use a list comprehension to do something like this: n *= (term for term in terms) #not working... Or is the only way: n *= reduce(lambda x,y: x*y, terms) This is on Python 2.6.2. Thanks!
[ "reduce is the best way to do this IMO, but you don't have to use a lambda; instead, you can use the * operator directly:\nimport operator\nn *= reduce(operator.mul, terms)\n\nn is now 240. See the docs for the operator module for more info.\n", "Reduce is not the only way. You can also write it as a simple loop:...
[ 8, 7, 2 ]
[]
[]
[ "list_comprehension", "python", "reduce" ]
stackoverflow_0003843188_list_comprehension_python_reduce.txt
Q: Python: callback when accessing the value of a variable? Suppose a function f() returns a value of arbitrary type, perhaps an object but possibly even a builtin type like int or list. Is there a way to assign a variable to that return value, and have a function of my choosing be called the first time the variable ...
Python: callback when accessing the value of a variable?
Suppose a function f() returns a value of arbitrary type, perhaps an object but possibly even a builtin type like int or list. Is there a way to assign a variable to that return value, and have a function of my choosing be called the first time the variable is used? I suppose this is similar to lazy evaluation except t...
[ "Sounds like you want properties.\nclass DeepThought(object):\n\n @property\n def answer(self):\n print (\"Computing the Ultimate Answer to the Ultimate Question\"\n \" of Life, The Universe, and Everything \")\n return 42\n\nprint DeepThought().answer\n\nYou can do that only i...
[ 1, 1, 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003842338_python.txt
Q: SWIG passing argument to python callback function So I'm almost done. Now I have working code which calls python callback function. Only thing I need now is how to pass argument to the python callback function. My callback.c is: #include <stdio.h> typedef void (*CALLBACK)(void); CALLBACK my_callback = 0; void se...
SWIG passing argument to python callback function
So I'm almost done. Now I have working code which calls python callback function. Only thing I need now is how to pass argument to the python callback function. My callback.c is: #include <stdio.h> typedef void (*CALLBACK)(void); CALLBACK my_callback = 0; void set_callback(CALLBACK c); void test(void); void set_call...
[ "The arguments to the callback are the second argument to PyEval_CallObject(). Right now you're building an empty tuple, which means \"no arguments\". So, change that. Where you now do:\narglist = Py_BuildValue(\"()\"); /* No arguments needed */\n\nyou instead pass Py_BuildValue whatever arguments you want the Pyt...
[ 3 ]
[]
[]
[ "callback", "python", "swig" ]
stackoverflow_0003843064_callback_python_swig.txt
Q: Starting a web app now which will use python that later this need to embed nicely into a Drupal site? This week, I want to start a web mapping and data visualization site for my work. Unfortunately, I just found out my work place will be using Drupal in a few months down the road. (Most of my web development exper...
Starting a web app now which will use python that later this need to embed nicely into a Drupal site?
This week, I want to start a web mapping and data visualization site for my work. Unfortunately, I just found out my work place will be using Drupal in a few months down the road. (Most of my web development experience is with App Engine.) My problem is that I need to make sure my web application embeds nicely into th...
[ "If you write API calls and utilize Drupal Services module, you can hook into just about anything and send/receive JSON/XML data.\n" ]
[ 1 ]
[]
[]
[ "drupal", "python" ]
stackoverflow_0003843218_drupal_python.txt
Q: Why doesn't Python's `except` use `isinstance`? The Python documentation for except says: For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if...
Why doesn't Python's `except` use `isinstance`?
The Python documentation for except says: For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception obj...
[ "The simple answer is probably that nobody considered it. A more complex answer would be that nobody considered it because it's hard to get this right, because it would mean executing potentially arbitrary Python code while handling an exception, and that it is of dubious value. Exception classes in Python are typi...
[ 4, 1 ]
[]
[]
[ "exception", "exception_handling", "isinstance", "python", "types" ]
stackoverflow_0003843469_exception_exception_handling_isinstance_python_types.txt
Q: Why is the notebook control not showing up in my window? Although I am not new to Python, this is my first attempt at using Glade to design the interface. My Python file looks like this: import gobject import gtk import gtk.glade class prefs_dialog: def __init__ (self): # Initialize the dialog ...
Why is the notebook control not showing up in my window?
Although I am not new to Python, this is my first attempt at using Glade to design the interface. My Python file looks like this: import gobject import gtk import gtk.glade class prefs_dialog: def __init__ (self): # Initialize the dialog self.window = gtk.glade.XML("file.glade").get_widget("pref...
[ "Okay, so it seems like the problem is that the notebook control had no widgets in the tabs. Adding something caused the control to finally show up.\n" ]
[ 2 ]
[]
[]
[ "glade", "pygtk", "python" ]
stackoverflow_0003843311_glade_pygtk_python.txt
Q: search list for exact match How can I search list(s) where all the elements exactly match what I'm looking for. For instance, I want to verify if the following list consist of 'a', 'b' and 'c', and nothing more or less. lst=['a', 'b', 'c'] I did this: if 'a' in lst and 'b' in lst and 'c' in lst: #do something ...
search list for exact match
How can I search list(s) where all the elements exactly match what I'm looking for. For instance, I want to verify if the following list consist of 'a', 'b' and 'c', and nothing more or less. lst=['a', 'b', 'c'] I did this: if 'a' in lst and 'b' in lst and 'c' in lst: #do something Many thanks in advance.
[ "You can sort the lists and then simply compare them: sorted( list_one ) == sorted( list_two ).\nAlso you can convert both lists to sets and compare them. But be careful, sets eat duplicate items! set( list_one ) == set( list_two ). \nSets can also tell you which items either set is lacking: set(list_one) ^ set(lis...
[ 6, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003843571_python.txt
Q: Broken Pipe when calling subprocess.Popen() within a multiprocessing.Process() I am having an issue when making a shell call from within a multiprocessing.Process(). The error seems to be coming from Git, but I just can't figure out why it only happens from within a multiprocessing.Process(). Note, below is an e...
Broken Pipe when calling subprocess.Popen() within a multiprocessing.Process()
I am having an issue when making a shell call from within a multiprocessing.Process(). The error seems to be coming from Git, but I just can't figure out why it only happens from within a multiprocessing.Process(). Note, below is an example to demonstrate what's happening... in real code there is a lot more going on ...
[ "Hrm, I just realized I was running on Python 2.6.1 .... running the same example on 2.6.4 does not have the same issue. Looks like a bug that was fix in Python.\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python", "subprocess" ]
stackoverflow_0003843789_multiprocessing_python_subprocess.txt
Q: Increasing a datetime field with queryset.update My model looks like this class MyModel(models.Model): end_time = DateTimeField() and this is what I'm trying to achieve: m=MyModel.objects.get(pk=1) m.end_time += timedelta(seconds=34) m.save() but I want to do it with update() to avoid race conditions: MyMode...
Increasing a datetime field with queryset.update
My model looks like this class MyModel(models.Model): end_time = DateTimeField() and this is what I'm trying to achieve: m=MyModel.objects.get(pk=1) m.end_time += timedelta(seconds=34) m.save() but I want to do it with update() to avoid race conditions: MyModel.objects.filter(pk=1).update(end_time=F('end_time')+t...
[ "This is completely possible. Not sure if you're looking at a cached value for your end_time, but here is a test I just ran:\n>>> e = Estimate.objects.get(pk=17)\n>>> e.departure_date\ndatetime.datetime(2010, 8, 12, 0, 1, 8)\n>>> Estimate.objects.filter(pk=17).update(departure_date=F('departure_date')+timedelta(se...
[ 2 ]
[]
[]
[ "datetime", "django", "django_orm", "python" ]
stackoverflow_0003843250_datetime_django_django_orm_python.txt
Q: python app gets stuck on shuffle and loop I am working on this small little piece in python and when I run it, It never gets past the print 'c' line and is stuck on the while loop. What am I doing wrong? link to text file: http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip enter code here import sys import ...
python app gets stuck on shuffle and loop
I am working on this small little piece in python and when I run it, It never gets past the print 'c' line and is stuck on the while loop. What am I doing wrong? link to text file: http://downloads.sourceforge.net/wordlist/12dicts-5.0.zip enter code here import sys import random inp = open('5desk.txt', 'r') lis = inp....
[ "Perhaps you meant this instead:\nwhile copy in lis:\n\nEither way there is no guarantee that rearranging the letters will eventually create a word that either is or is not in the list. In particular if the input contains only one letter then the shuffle will have no effect at all. It might be better to iterate ove...
[ 1, 1 ]
[]
[]
[ "list", "loops", "python" ]
stackoverflow_0003843709_list_loops_python.txt
Q: Python: replacing method in calendar module I'm trying to replace two methods in calendar module: import calendar c = calendar.HTMLCalendar(calendar.MONDAY) def ext_formatday(self, day, weekday, *notes): if day == 0: return '<td class="noday">&nbsp;</td>' if len(notes) == 0: return '<td cl...
Python: replacing method in calendar module
I'm trying to replace two methods in calendar module: import calendar c = calendar.HTMLCalendar(calendar.MONDAY) def ext_formatday(self, day, weekday, *notes): if day == 0: return '<td class="noday">&nbsp;</td>' if len(notes) == 0: return '<td class="%s">%d<br /></td>' % (self.cssclasses[weekd...
[ "Try replacing the method at the class instead of the instance.\nLike this:\nimport calendar \n\n\ndef ext_formatday(self, day, weekday, *notes): \n if ...
[ 1, 0, 0 ]
[]
[]
[ "calendar", "python" ]
stackoverflow_0003843800_calendar_python.txt
Q: Modifying The Template For New Pylons Controllers I'm at a point in my Pylons projects where I end up creating and deleting controllers often (probably more often than I should). I grow tired of adding my own imports and tweaks to the top of every controller. There was a recent question about modifying the new co...
Modifying The Template For New Pylons Controllers
I'm at a point in my Pylons projects where I end up creating and deleting controllers often (probably more often than I should). I grow tired of adding my own imports and tweaks to the top of every controller. There was a recent question about modifying the new controller template that got me part-way to not having to...
[ "Pylons creates new controllers and projects by adding command to paste. The commands are defined in setup.py and you can add new commands.\nFor example (this is taken from the Paste docs) lets assume you have a project called Foo that is in a package also called foo.\nIn setup.py add 'foo' to the 'paster_plugins' ...
[ 1 ]
[]
[]
[ "paste", "paster", "pylons", "python" ]
stackoverflow_0003791790_paste_paster_pylons_python.txt
Q: Tracd Realm I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the site I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using tra...
Tracd Realm
I am trying to setup tracd for the project I am currently working on. After creating a password file with the python script given in the site I am trying to start the server with authentication on. But it throws up warning saying No users found in the realm. What actually is a realm - I tried using trac as the value an...
[ "Replacing the above said command line with the one bellow helps.\ntracd --port 8000 --auth=Trac,D:\\My_Test_Project\\Documents\\Trac\\digest.txt,Trac D:\\My_Test_Project\\Documents\\Trac\nThe string after --auth= should be the environment name and not the project name.\n", "Check your password digest file. Look...
[ 6, 5, 1 ]
[]
[]
[ "project_management", "python", "trac", "wiki" ]
stackoverflow_0000200447_project_management_python_trac_wiki.txt
Q: How to diagnose reason for slow access to sqlite database? As I have stated in this question some time ago, I am having performance problems when accessing an sqlite database from Python. To make that clear once more, the identical code runs more than 20 times faster using apsw. I recently installed a different ve...
How to diagnose reason for slow access to sqlite database?
As I have stated in this question some time ago, I am having performance problems when accessing an sqlite database from Python. To make that clear once more, the identical code runs more than 20 times faster using apsw. I recently installed a different version of Python in parallel and installed a new version of apsw ...
[ "Just in case you may have overlooked this, make sure you are working with the latest versions of both the pysqlite2 data base adapter and the sqlite3 library. The linked answer also shows how to determine exactly which version of each you are using, data which you might want to add to your question.\n", "I can ...
[ 1, 0 ]
[]
[]
[ "performance", "python", "sqlite" ]
stackoverflow_0003842250_performance_python_sqlite.txt
Q: Please recommend some Python hashing algorithms I'm doing a password hashing program in python. I need to make my hashing dynamic, i.e. each time I need to get different hashed code. I am using md5 library. A: The information that you want can be found in Python's hashlib module. From the documentation: This mo...
Please recommend some Python hashing algorithms
I'm doing a password hashing program in python. I need to make my hashing dynamic, i.e. each time I need to get different hashed code. I am using md5 library.
[ "The information that you want can be found in Python's hashlib module. From the documentation:\n\nThis module implements a common interface to many different secure hash and message digest \n algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and \n SHA512 (defined in ...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003844062_python.txt
Q: Static or constant or what are they? I just want to know how I can call certian classes in design pattern here, like which type are they classified in OO design (1) I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class....
Static or constant or what are they?
I just want to know how I can call certian classes in design pattern here, like which type are they classified in OO design (1) I use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class. (2) I use a class with full of static met...
[ "\nWhat are these kinda classes classified under OOdesign? Can I do it in a more elegant way?\n\nYou do have better alternatives, IMHO.\n\nI use a class that has just named constants , this class is used directly other classes to get values of constants in it.I dont instantiate the class.\n\nFor e.g. in this case y...
[ 8, 1 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0003844158_oop_python.txt
Q: simple python connect 4 game. why doesnt this test work? Everything about this code seems to work perfectly, except the tests for diagonal wins. The tests for vertical and horizontal wins seem to be exactly the same concept, and they work perfectly. The comments should mostly explain it, but the test should basic...
simple python connect 4 game. why doesnt this test work?
Everything about this code seems to work perfectly, except the tests for diagonal wins. The tests for vertical and horizontal wins seem to be exactly the same concept, and they work perfectly. The comments should mostly explain it, but the test should basically iterate through the board and check for x's in the bottom...
[ "It worked for me. I started in the bottom right hand corner with an X and worked it up diagonally to the left. I also started one to the left of that initial position. However, when I got 4 X's in a row, it didn't immediately stop - I had to put another O in because it only checks to see if the game should stop af...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003844306_python.txt
Q: Django Group By I'm writing a simple private messenger using Django and am implementing message threading. Each series of messages and replies will have a unique thread_id that will allow me to string sets of messages together. However, in the inbox view ALL of the messages are showing up, I'd just like to group ...
Django Group By
I'm writing a simple private messenger using Django and am implementing message threading. Each series of messages and replies will have a unique thread_id that will allow me to string sets of messages together. However, in the inbox view ALL of the messages are showing up, I'd just like to group by the thread_id so t...
[ "What do you want to achieve with this SQL statement?\nIt will work on some DBMS (ie. MySQL), but it isn't legal. When your are using GROUP BY statement, you can select only columns your are grouping by, and aggregates (SUM, AVG, COUNT etc.). Other columns are forbidden, because DBMS don't know what data return (ie...
[ 1 ]
[]
[]
[ "django", "python", "sql" ]
stackoverflow_0003844392_django_python_sql.txt
Q: Why is there no "compound method call statement", i.e. ".="? Lots of programming languages already have the compound statements +=, -=, /=, etc. A relatively new style of programming is to "chain" method calls onto each other, e.g. in Linq, JQuery and Django's ORM. I sometimes, more often than I'd like, find the n...
Why is there no "compound method call statement", i.e. ".="?
Lots of programming languages already have the compound statements +=, -=, /=, etc. A relatively new style of programming is to "chain" method calls onto each other, e.g. in Linq, JQuery and Django's ORM. I sometimes, more often than I'd like, find the need to do this in Django: # Get all items whose description beginn...
[ "This is supported in Perl 6.\n", "IMHO, i don't like it.\njust imagine this,\nitems .= click(function(){...});\n\nit's not a syntax error anymore, but it doesn't make sense, does it?\nI can say it does not make sense simply because if you expand my example, it would be like this,\nitems = items.click(function(){...
[ 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "jquery", "linq", "programming_languages", "python", "syntax" ]
stackoverflow_0003829078_jquery_linq_programming_languages_python_syntax.txt
Q: Can't upload file in Google App Engine I don't know why I can't upload my file? When I hit submit instead of redirecting to the default page (which is http://localhost:8082), it redirects to http://localhost:8082/sign. I didn't build no such path, so it return link broken. Here's my html: <form action="/sign" enct...
Can't upload file in Google App Engine
I don't know why I can't upload my file? When I hit submit instead of redirecting to the default page (which is http://localhost:8082), it redirects to http://localhost:8082/sign. I didn't build no such path, so it return link broken. Here's my html: <form action="/sign" enctype="multipart/form-data" method="post"> ...
[ "Why are you sending the form data to a page that doesn't exist?\nTry changing the HTML to:\n<form action=\"/\" enctype=\"multipart/form-data\" method=\"post\">\n...\n\n...since \"/\" is where your form-handling code resides.\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003844488_google_app_engine_python.txt
Q: My .yaml is not redirecting properly app.yaml application: classscheduler9000 version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /images static_dir: static/images - url: /stylesheets static_dir: static/stylesheets - url: /users\.html script: main.py - url: ...
My .yaml is not redirecting properly
app.yaml application: classscheduler9000 version: 1 runtime: python api_version: 1 handlers: - url: /static static_dir: static - url: /images static_dir: static/images - url: /stylesheets static_dir: static/stylesheets - url: /users\.html script: main.py - url: /.* script: login.py main.py import has...
[ "The issue is with your application definition. \napplication = webapp.WSGIApplication([('/user\\.html', MainPage),\n ('/sign', UserWrite)],\n debug=True)\n\nThe documentation about this is here, although it does not have \"simple\" examples....
[ 2 ]
[]
[]
[ "google_app_engine", "python", "yaml" ]
stackoverflow_0003844293_google_app_engine_python_yaml.txt
Q: What structured text format is the best supported in Python? This question may be seen as subjective, but I'd like to ask SO users which common structured textual data format is best supported in Python. My initial choices are: XML JSON and YAML Which of these three is easiest to work with in Python (ie. has the...
What structured text format is the best supported in Python?
This question may be seen as subjective, but I'd like to ask SO users which common structured textual data format is best supported in Python. My initial choices are: XML JSON and YAML Which of these three is easiest to work with in Python (ie. has the best library support / performance) ... or is there another forma...
[ "I would go with JSON, I mean YAML is awesome but interop with it is not that great.\nXML is just an ugly mess to look at and has too much fat. \nPython has a built-in JSON module since version 2.6.\n", "JSON has great python support and it is much more compact than XML (and the API is generally more convenient i...
[ 4, 3, 1, 0 ]
[]
[]
[ "python", "structured_data", "text" ]
stackoverflow_0003844556_python_structured_data_text.txt
Q: Receiving 0.0 when expecting a non-zero value after division Hai... i am facing a problem while inserting values to an array. the programming language using is python. the problem is, i need to insert a value to array after performing a division. but every the value in array is always 0.0 . i am attach...
Receiving 0.0 when expecting a non-zero value after division
Hai... i am facing a problem while inserting values to an array. the programming language using is python. the problem is, i need to insert a value to array after performing a division. but every the value in array is always 0.0 . i am attaching the code here.... print len(extract_list1) ratio1=range(len(ex...
[ "My best guess is that you are performing integer division and then converting to a float yielding the value of 0.0 which is what gets stuck in the list. you want to convert to float before the division. Sift through that wall of code and find out \n\nwhere you are inserting the value into the list.\nWhere that va...
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0003844637_python.txt
Q: Mercurial for Windows - Python version? What version of Python is needed to run Mercurial? I see that the website says it requires 2.4. Does that mean 2.4, or 2.x? or something higher than 2.4, i.e., could I install 3.x? I've installed Mercurial without reading the requirements and I installed it anyway and hg.ex...
Mercurial for Windows - Python version?
What version of Python is needed to run Mercurial? I see that the website says it requires 2.4. Does that mean 2.4, or 2.x? or something higher than 2.4, i.e., could I install 3.x? I've installed Mercurial without reading the requirements and I installed it anyway and hg.exe executes fine. Looking in the directory tha...
[ "Yes, it comes bundled. If you install Mercurial using the Windows installer, then you don't need to worry about which version of Python you are using. Mercurial uses py2exe to create an executable that runs without a Python installation.\n", "Python 3.x is not compatible with 2.x. \nIf Mercurial supports 2.4 and...
[ 10, 1 ]
[]
[]
[ "mercurial", "python", "version", "windows" ]
stackoverflow_0003844859_mercurial_python_version_windows.txt
Q: python and matplotlib server side to generate .pdf documents i would like to write a server side python script that generate .pdf documents. for the moment i have Python 2.7 installed server side and matplolib installed server side too. A simple script that create a simple plot and generate a .png picture works. t...
python and matplotlib server side to generate .pdf documents
i would like to write a server side python script that generate .pdf documents. for the moment i have Python 2.7 installed server side and matplolib installed server side too. A simple script that create a simple plot and generate a .png picture works. this is the script i use : # to access standard output : import sys...
[ "First of all, in your code you send to stdout both the words from the print statement and the figure itself. \nI've just tried your script, changing the comments like this\n# plt.savefig(sys.stdout, format='png')\n# plt.savefig(sys.stdout, format='PDF')\nplt.savefig( \"test.pdf\", format='pdf' ) \n\nand it works ...
[ 4, 2 ]
[]
[]
[ "cgi", "matplotlib", "python" ]
stackoverflow_0003842633_cgi_matplotlib_python.txt
Q: Is it possible to solve this problem with Regular Expression? I'm trying to divide long text in small parts, so that every part is at least N characters and ended with some of the stop punctuation marks (? . !). If the part is bigger than N characters we sttoped when the next punctuation mark appear. For example ...
Is it possible to solve this problem with Regular Expression?
I'm trying to divide long text in small parts, so that every part is at least N characters and ended with some of the stop punctuation marks (? . !). If the part is bigger than N characters we sttoped when the next punctuation mark appear. For example : Lets say N = 10 Do you want lime? Yes. I love when I drink tequil...
[ "Maybe like this? (Thanks to KennyTM for final optimizations.)\n.{10}[^.?!]*[.?!]+\n\n", ".{10,}?[.!?]+\\s*\n\nshould work. It will also keep repeated punctuation characters together, so it splits Do you want lime??? Yes. I love when I drink tequila. into Do you want lime??? and Yes. I love when I drink tequila.\...
[ 2, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003845284_python_regex.txt
Q: Django: request.GET and KeyError Code: # it's an ajax request, so parameters are passed via GET method def my_view(request): my_param = request.GET['param'] // should I check for KeyError exception? In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not....
Django: request.GET and KeyError
Code: # it's an ajax request, so parameters are passed via GET method def my_view(request): my_param = request.GET['param'] // should I check for KeyError exception? In PHP Frameworks I typically have to check for parameter to exists and redirect user somewhere if it does not. But in Django unexisted parameter res...
[ "Your server should never produce a 500 error page.\nYou can avoid the error by using:\nmy_param = request.GET.get('param', default_value)\n\nor:\nmy_param = request.GET.get('param')\nif my_param is None:\n return HttpResponseBadRequest()\n\n", "Yes, you should check for KeyError in that case. Or you could do...
[ 59, 9, 1 ]
[]
[]
[ "django", "django_urls", "python" ]
stackoverflow_0003845582_django_django_urls_python.txt
Q: How can I check if a key exists in a dictionary? Let's say I have an associative array like so: {'key1': 22, 'key2': 42}. How can I check if key1 exists in the dictionary? A: if key in array: # do something Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes ...
How can I check if a key exists in a dictionary?
Let's say I have an associative array like so: {'key1': 22, 'key2': 42}. How can I check if key1 exists in the dictionary?
[ "if key in array:\n # do something\n\nAssociative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.\n", "If you want to retrieve the key's value if it exists, you can also use\ntry:\n value = a[key]\nexcept KeyError:\n # Key is not present\n pass\n...
[ 699, 64, 62 ]
[]
[]
[ "python" ]
stackoverflow_0003845362_python.txt
Q: Precompose Unicode Character Sequences in Python How can I convert decomposed unicode character sequences like "LATIN SMALL LETTER E" + "COMBINING ACUTE ACCENT" (or U+0075 + U+0301) so they become the precomposed form: "LATIN SMALL LETTER E WITH ACUTE" (or U+00E9) using native Python 2.5+ functions? If it matters,...
Precompose Unicode Character Sequences in Python
How can I convert decomposed unicode character sequences like "LATIN SMALL LETTER E" + "COMBINING ACUTE ACCENT" (or U+0075 + U+0301) so they become the precomposed form: "LATIN SMALL LETTER E WITH ACUTE" (or U+00E9) using native Python 2.5+ functions? If it matters, I am on Mac OS X (10.6.4) and I have seen the questio...
[ "import unicodedata as ud\n\nastr=u\"\\N{LATIN SMALL LETTER E}\" + u\"\\N{COMBINING ACUTE ACCENT}\"\ncombined_astr=ud.normalize('NFC',astr)\n\n'NFC' tells ud.normalize to apply the canonical decomposition ('NFD'), then\ncompose pre-combined characters:\nprint(ud.name(combined_astr))\n# LATIN SMALL LETTER E WITH ACU...
[ 10 ]
[]
[]
[ "macos", "python", "unicode" ]
stackoverflow_0003845793_macos_python_unicode.txt
Q: AttributeError - Django, GAE This is my code for views.py def addCategory(request): user = users.get_current_user() if users.is_current_user_admin(): if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): cd = form.cleaned_data ...
AttributeError - Django, GAE
This is my code for views.py def addCategory(request): user = users.get_current_user() if users.is_current_user_admin(): if request.method == 'POST': form = CategoryForm(request.POST) if form.is_valid(): cd = form.cleaned_data Category.objects.crea...
[ "Django does not support GAE currently. You have to use patched Django, for example, http://www.allbuttonspressed.com/projects/djangoappengine and then rewrite your model using standard django db model (currently you are using GAE one). However djangoappengine does not provide 100% compatibility.\n" ]
[ 2 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003845272_django_google_app_engine_python.txt
Q: C++ vs Python precision Trying out a problem of finding the first k digits of a num^num I wrote the same program in C++ and Python C++ long double intpart,num,f_digit,k; cin>>num>>k; f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1); cout<<f_digit; Python (a,b) = modf(num*log10(num)) f_digits = pow(10,b+k-1) ...
C++ vs Python precision
Trying out a problem of finding the first k digits of a num^num I wrote the same program in C++ and Python C++ long double intpart,num,f_digit,k; cin>>num>>k; f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1); cout<<f_digit; Python (a,b) = modf(num*log10(num)) f_digits = pow(10,b+k-1) print f_digits Input 194234...
[ "Decimal is a built in python class that handles floating points correctly (as base 10, not as IEEE 7somethingsomething standard). I don't know if it supports logarithms and all that though.\nEdit: It does indeed support logarithms \"and all that\".\nYou can set the precision of it as well. Default is 28 places, bu...
[ 11, 2, 0 ]
[]
[]
[ "c++", "floating_accuracy", "floating_point", "precision", "python" ]
stackoverflow_0003846631_c++_floating_accuracy_floating_point_precision_python.txt
Q: Print variable in python without space or newline print a variable without newline or space python3 does it by print (x,end='') how to do it in python 2.5 A: sys.stdout.write writes (only) strings without newlines unless specified. >>> x = 4 >>> print x 4 >>> import sys >>> sys.stdout.write(str(x)) # you have to...
Print variable in python without space or newline
print a variable without newline or space python3 does it by print (x,end='') how to do it in python 2.5
[ "sys.stdout.write writes (only) strings without newlines unless specified.\n>>> x = 4\n>>> print x\n4\n>>> import sys\n>>> sys.stdout.write(str(x)) # you have to str() your variables\n4>>> # <- no newline\n\n", "Easy:\nprint x,\n\nNote comma at the end.\n" ]
[ 11, 0 ]
[]
[]
[ "formatting", "printing", "python", "python_2.5", "python_2.x" ]
stackoverflow_0003846801_formatting_printing_python_python_2.5_python_2.x.txt
Q: Why does importing a dotted module name fail when upper level is matched by a module in current directory? I was trying out one of the Python standard library modules, let's call it foo.bar.baz. So I wrote a little script starting with import foo.bar.baz and saved it as foo.py. When I executed the script I got an...
Why does importing a dotted module name fail when upper level is matched by a module in current directory?
I was trying out one of the Python standard library modules, let's call it foo.bar.baz. So I wrote a little script starting with import foo.bar.baz and saved it as foo.py. When I executed the script I got an ImportError. It took me a while (I'm still learning Python), but I finally realized the problem was how I name...
[ "An import statement like import foo.bar.baz first imports foo, then asks it for bar, and then asks foo.bar for baz. Whether foo will, once imported, be able to satisfy the request for bar or bar.baz is unimportant to the import of foo. It's just a module. There is only one foo module. Both import foo and import fo...
[ 6 ]
[]
[]
[ "import", "python" ]
stackoverflow_0003846821_import_python.txt
Q: parse html beautiful soup I have a html page <a email="corporate@max.ru" href="http://www.max.ru/agent?message&to=corporate@max.ru" title="Click herе" class="mf_spIco spr-mrim-9"></a><a class="mf_t11" type="booster" href="http://max.ru/mail/corporate/"> I neeed a parse email string soup = BeautifulSoup(data ...
parse html beautiful soup
I have a html page <a email="corporate@max.ru" href="http://www.max.ru/agent?message&to=corporate@max.ru" title="Click herе" class="mf_spIco spr-mrim-9"></a><a class="mf_t11" type="booster" href="http://max.ru/mail/corporate/"> I neeed a parse email string soup = BeautifulSoup(data string = soup.find("a",{"em...
[ "Your mistake was in using the attrs dict to look for elements with an email attribute that is empty. Try this instead.\n#!/usr/bin/env python\n\nfrom BeautifulSoup import BeautifulSoup\nimport urllib2\n\nreq = urllib2.urlopen('http://worldnuclearwar.ru')\n\nsoup = BeautifulSoup(req)\nprint soup.find(\"a\", email=T...
[ 4 ]
[]
[]
[ "beautifulsoup", "python", "regex" ]
stackoverflow_0003847020_beautifulsoup_python_regex.txt
Q: handling manual user creation with get_current_user() (GAE) I am using GAE's Python environment and Janrain in order to provide multiple ways to login in my service. Based on login information I receive from Janrain, I create a google.appengine.api.User object and store it to the datastore. Is there a way to hand...
handling manual user creation with get_current_user() (GAE)
I am using GAE's Python environment and Janrain in order to provide multiple ways to login in my service. Based on login information I receive from Janrain, I create a google.appengine.api.User object and store it to the datastore. Is there a way to handle this new object with the built-in get_current_user()? I need ...
[ "No, you cannot use your custom user objects with the native GAE Users API.\nYou could use a sessions library to track whether or not the request is coming from a logged in user (and who that user is). I recommend gae-sessions. The source includes a demo which shows how to integrate the sessions library with Janr...
[ 2 ]
[]
[]
[ "authentication", "google_app_engine", "python" ]
stackoverflow_0003846900_authentication_google_app_engine_python.txt
Q: Multithread DNS Query against specific DNS, domain and recordtype supporting Library Resolved, used adns with python bindings... I have a scenario in which i have to do the following: Load a domain Load what record type is to be queried Load list of DNS Perform query, fetch results and display them. I have tried...
Multithread DNS Query against specific DNS, domain and recordtype supporting Library
Resolved, used adns with python bindings... I have a scenario in which i have to do the following: Load a domain Load what record type is to be queried Load list of DNS Perform query, fetch results and display them. I have tried this but its not multi threaded and even a single query takes about 3 seconds. I looked a...
[ "If you do go with PHP for the client side and feed it with domains to query, you should consider stream_select for working with many streams (each one a dns query) in a non-blocking way. Wez Furlong explains it well.\n" ]
[ 1 ]
[]
[]
[ "dns", "multithreading", "php", "python" ]
stackoverflow_0003846266_dns_multithreading_php_python.txt
Q: Routes/Pylons Fails Before Touching My Code I am very puzzled over this error. In a previously functional Pylons app (running on apache/mod_wsgi), Routes has exploded. When I attempt to access my application, no matter what URL I use, I get the Apache "Internal server error" page and the following traceback in /...
Routes/Pylons Fails Before Touching My Code
I am very puzzled over this error. In a previously functional Pylons app (running on apache/mod_wsgi), Routes has exploded. When I attempt to access my application, no matter what URL I use, I get the Apache "Internal server error" page and the following traceback in /var/log/apache2/error.log. [Sat Oct 02 2010] WS...
[ "I'd look in your app's config/routing.py file, and add some debugging steps there, or try editing or removing some of the map.connect(...) calls. If you comment out each controller's mapping one at a time, you might be able to narrow down one controller's mapping that is causing this.\n" ]
[ 1 ]
[]
[]
[ "mod_wsgi", "pylons", "python", "regex", "routes" ]
stackoverflow_0003846849_mod_wsgi_pylons_python_regex_routes.txt
Q: Image Sent via XML from iPhone to App Engine I am trying to send a small image along with some XML information to App Engine from my iPhone app. I am having trouble with the image somewhere along the path. There is no error given and data is being transfered into a Blob entry in Datastore Viewer but the blob fi...
Image Sent via XML from iPhone to App Engine
I am trying to send a small image along with some XML information to App Engine from my iPhone app. I am having trouble with the image somewhere along the path. There is no error given and data is being transfered into a Blob entry in Datastore Viewer but the blob files on App Engine do not appear in Blob Viewer. I...
[ "The Blob Viewer displays files uploaded with the Blobstore API, not those added to regular datastore entities in Blob Properties.\n", "What I ended up doing was sending the image to the Blobstore prior to sending the XML then, if successful, send the XML including a key to the blobstore image data. I did not re...
[ 2, 0 ]
[]
[]
[ "google_app_engine", "iphone", "objective_c", "python", "xml" ]
stackoverflow_0003692697_google_app_engine_iphone_objective_c_python_xml.txt
Q: Customize HTML Output of Django ModelForm I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML. class LeagueForm(Mod...
Customize HTML Output of Django ModelForm
I am trying to add multiple inline form items to a page using Djangos ModelForms. I need Select boxes bound to database models. The forms are formatted and placed in a tabular format so I need to display only the ModelForm without ANY surrounding HTML. class LeagueForm(ModelForm): league = forms.ModelChoiceField(querys...
[ "Just refer to each field separately.\n{{ nhl_form.league }}\n\nwill only show the league field, with no surrounding cruft.\n", "see also http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-field-types-or-widgets \n" ]
[ 16, 0 ]
[]
[]
[ "django", "django_forms", "django_templates", "python" ]
stackoverflow_0001717715_django_django_forms_django_templates_python.txt
Q: alphabetically sorted if statement not working The if statement below has a problem in it somewhere and I can not figure it out. Any conventions or method misuses that might be causing it to not function right? checkList is a user inputed sentence and lis is a large list of words. def realCheck(checkList): ...
alphabetically sorted if statement not working
The if statement below has a problem in it somewhere and I can not figure it out. Any conventions or method misuses that might be causing it to not function right? checkList is a user inputed sentence and lis is a large list of words. def realCheck(checkList): string = "".join(checkList) print string ...
[ "\nIf checkList is a string, then there\nis no need for \"\".join(checkList).\nIt just gives you back the same\nstring:\nIn [94]: checkList=\"This is a sentence\" \nIn [95]: \"\".join(checkList)\nOut[95]: 'This is a sentence'\n\nThe first line, string =\n\"\".join(checkList) has the wrong\nindentation. Move it b...
[ 5, 4 ]
[]
[]
[ "mutators", "python" ]
stackoverflow_0003847934_mutators_python.txt
Q: Import statement with Django I'm having an issue with a failing import statement, it is called by a manage.py command. It works in the manage.py shell. It also recently worked, i've tried to retrace my steps to no avail. Any advice? A: Your question does not have enough information to answer definitively, but I ...
Import statement with Django
I'm having an issue with a failing import statement, it is called by a manage.py command. It works in the manage.py shell. It also recently worked, i've tried to retrace my steps to no avail. Any advice?
[ "Your question does not have enough information to answer definitively, but I can at least offer some hints to debug the problem.\nUnderstand the import statement\nRead and understand the documentation for the import statement for your version of Python..\nCheck the Python path\nOne key step towards debugging any i...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003843285_django_python.txt
Q: Getting current class in method call class A: def x ( self ): print( self.__class__ ) class B ( A ): pass b = B() b.x() In the above situation, is there any way for the method x to get a reference to class A instead of B? Of course simply writing print( A ) is not allowed, as I want to add some ...
Getting current class in method call
class A: def x ( self ): print( self.__class__ ) class B ( A ): pass b = B() b.x() In the above situation, is there any way for the method x to get a reference to class A instead of B? Of course simply writing print( A ) is not allowed, as I want to add some functionality with a decorator that needs ...
[ "Unless you have super-calls involved (or more generally subclasses that override x and call directly to A.x(self) as part of their override's implementation), looking for the first item in type(self).mro() that has an x attribute would work --\nnext(c for c in type(self).mro() if hasattr(c, 'x'))\n\nIf you do need...
[ 4, 2 ]
[]
[]
[ "inheritance", "python" ]
stackoverflow_0003848033_inheritance_python.txt
Q: Calling variable superclass method I'm trying to call a method of the superclass by using a variable method name. Normally, I would see the following two lines of code as equivalent: someObj.method() someObj.__getattribute__( 'method' )() And in fact I believe, this is also what actually happens when I use the fi...
Calling variable superclass method
I'm trying to call a method of the superclass by using a variable method name. Normally, I would see the following two lines of code as equivalent: someObj.method() someObj.__getattribute__( 'method' )() And in fact I believe, this is also what actually happens when I use the first line. However, in the following exam...
[ "Don't use __getattribute__ for this: it does not do what you think it does. (It is a specialized part of Python's machinery, mainly for use if you're implementing new attribute access magic.)\nFor normal attribute access, use the getattr / setattr / delattr builtins:\nself.example == getattr(self, 'examp...
[ 5, 0 ]
[]
[]
[ "python", "super", "superclass" ]
stackoverflow_0003847919_python_super_superclass.txt
Q: Stdout captured from pipe in Python is truncated I want to capture the ouput of dpkg --list | grep linux-image in Python 2.6.5 on Ubuntu 10.04. from subprocess import Popen from subprocess import PIPE p1 = Popen(["dpkg", "--list"], stdout=PIPE) p2 = Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=PIPE) st...
Stdout captured from pipe in Python is truncated
I want to capture the ouput of dpkg --list | grep linux-image in Python 2.6.5 on Ubuntu 10.04. from subprocess import Popen from subprocess import PIPE p1 = Popen(["dpkg", "--list"], stdout=PIPE) p2 = Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=PIPE) stdout = p2.communicate()[0] The content of stdout is: ...
[ "import subprocess\np1 = subprocess.Popen([\"dpkg\", \"--list\"], stdout=subprocess.PIPE, env={'LANG':'C'})\np2 = subprocess.Popen([\"grep\", \"linux-image\"], stdin=p1.stdout, stdout=subprocess.PIPE)\nout,err=p2.communicate()\nprint(out)\n\nThe dpkg command's output depends on the value of the LANG environment var...
[ 4, 4 ]
[]
[]
[ "pipe", "python", "subprocess" ]
stackoverflow_0003848269_pipe_python_subprocess.txt
Q: Handling frame resize in matplotlib animation with WXAgg backend I am doing some animated plotting and using the the matplotlib examples as a guideline. matplotlib examples With the following linked example from that page the animation has some obvious problems when the frame is resized. What is the correct or bes...
Handling frame resize in matplotlib animation with WXAgg backend
I am doing some animated plotting and using the the matplotlib examples as a guideline. matplotlib examples With the following linked example from that page the animation has some obvious problems when the frame is resized. What is the correct or best way to deal with this? animation_blit_wx.py Thanks
[ "Take a look at the animation_blit_qt4.py example.\nYou have to check the figure size manually, and if it has changed you need to draw the background again. \nHeres the part which does that from the qt example, self is a Figure Canvas:\n current_size = self.ax.bbox.width, self.ax.bbox.height\n if self.old_size !...
[ 1 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0003835109_matplotlib_python_wxpython.txt
Q: Communication from arduino to a browser extension all run locally I am trying to figure out how I would go about taking serial information from an Arduino which controls a Javascript browser extension I have running in an open browser locally on a computer. It would seem that I would need some sort of middleman t...
Communication from arduino to a browser extension all run locally
I am trying to figure out how I would go about taking serial information from an Arduino which controls a Javascript browser extension I have running in an open browser locally on a computer. It would seem that I would need some sort of middleman to internalize the serial readings and pass them to the browser (to acti...
[ "Another option is to use a browser plug-in to access the serial port from javascript: http://code.google.com/p/seriality/\n", "A very simple http server in python would look like this\nfrom BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer\n\nclass MyServer(BaseHTTPRequestHandler):\n def do_GET(self):\n...
[ 2, 0 ]
[]
[]
[ "browser", "communication", "python", "serial_port" ]
stackoverflow_0003338323_browser_communication_python_serial_port.txt
Q: Python equivalent of ActionScript 3's restParam In ActionScript 3 (Flash's programming language, very similar to Java - to the point that it's disturbing), if I was defining a function and wanted it to be called with endless parameters, I could do this (restParam, I thought it was called): function annihilateUnico...
Python equivalent of ActionScript 3's restParam
In ActionScript 3 (Flash's programming language, very similar to Java - to the point that it's disturbing), if I was defining a function and wanted it to be called with endless parameters, I could do this (restParam, I thought it was called): function annihilateUnicorns(...unicorns):String { for(var i:int = 0; i<un...
[ "def annihilateUnicorns(*unicorns):\n for i in unicorns: # stored in a list\n i.splode()\n return \"404 Unicorns not found. They sploded.\"\n\n" ]
[ 4 ]
[]
[]
[ "function", "python" ]
stackoverflow_0003848454_function_python.txt
Q: Copy strings from multiple lineEdit slots as variable to one textEdit slot in PyQt4 To be more crystal clear, here how the things might work. In python, to create a variable, simply we use var1 = raw_input('your name?') So that when using print 'your name is ' +var1 It will print the string stored in var1. Th...
Copy strings from multiple lineEdit slots as variable to one textEdit slot in PyQt4
To be more crystal clear, here how the things might work. In python, to create a variable, simply we use var1 = raw_input('your name?') So that when using print 'your name is ' +var1 It will print the string stored in var1. The question is how to make that using Pyqt4? I have 3 lineEdit symbolize as name, age and ...
[ "When a push-button is clicked in Qt (and PyQt) it emits a signal. You can connect this signal to any slot (in PyQt that would be any Python method) and do whatever you wish in that slot - like look at text from 3 boxes and print something.\nFor example suppose you have a button you created with:\n self.start_bu...
[ 0, 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003845658_pyqt4_python.txt
Q: django template does not render complete context I am using templates with django. I am having a problem where the Context is not being rendered. The meta_k is null. The meta_description is not. t = get_template('projects.html') html = t.render(Context({ 'completed': completed, 'current':curr...
django template does not render complete context
I am using templates with django. I am having a problem where the Context is not being rendered. The meta_k is null. The meta_description is not. t = get_template('projects.html') html = t.render(Context({ 'completed': completed, 'current':current, 'description': sp.description, 'p...
[ "Only suggestion for you is that most probably it is bug in your code, for us it will be difficult to debug without running your whole project.\nSo i suggest you experiment on command line and see if you can replicate the bug in simple steps, so that we can try to fix it. I am sure in the process you will find the ...
[ 3, -1 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003848472_django_google_app_engine_python.txt
Q: Confusion about django app's name I learned Django following django book and the document. In the django book exmaple, the project is called mysite and there's an app called book inside this project. So in this case, the app is called "book". I've no problem with it. My confusion arises in front of reusable apps. ...
Confusion about django app's name
I learned Django following django book and the document. In the django book exmaple, the project is called mysite and there's an app called book inside this project. So in this case, the app is called "book". I've no problem with it. My confusion arises in front of reusable apps. Reusable apps usually reside outside th...
[ "The name of the app is the name of the directory, capitalization and all, unless you go to the extra work to change the name in the appropriate __init__.py file. Django apps are, after all, just Python modules, and all the same rules apply.\nIf you ever see an app or module name with different capitalization or ot...
[ 2, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003848490_django_python.txt
Q: Python comparing two lists Hello I wanna compare two lists like this a=[1,2] b=10,20] compare(a,b) will return True if each element in a is > corresponding element in b so compare( [1,2] > [3,4] ) is True compare( [1,20] > [3,4] ) is False hiow to do this the pythonic way Cheers A: Use zip: len(a) == len(b) and ...
Python comparing two lists
Hello I wanna compare two lists like this a=[1,2] b=10,20] compare(a,b) will return True if each element in a is > corresponding element in b so compare( [1,2] > [3,4] ) is True compare( [1,20] > [3,4] ) is False hiow to do this the pythonic way Cheers
[ "Use zip:\nlen(a) == len(b) and all(j > i for i, j in zip(a, b))\n\n", "I'm not exactly sure what you're looking for since the result shown in your example seems to contradict what you said you wanted returned, nor do you specify what is desired if the length of the two lists are unequal or both are empty. \nFor ...
[ 10, 1 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0003848242_python_python_3.x.txt
Q: How to map a list of data to a list of functions? I have the following Python code: data = ['1', '4.6', 'txt'] funcs = [int, float, str] How to call every function with data in corresponding index as an argument to the function? Now I'm using the code: result = [] for i, func in enumerate(funcs): result.appe...
How to map a list of data to a list of functions?
I have the following Python code: data = ['1', '4.6', 'txt'] funcs = [int, float, str] How to call every function with data in corresponding index as an argument to the function? Now I'm using the code: result = [] for i, func in enumerate(funcs): result.append(func(data[i])) map(funcs, data) don't work with li...
[ "You could use zip* to combine many sequences together:\nzip([a,b,c,...], [x,y,z,...]) == [(a,x), (b,y), (c,z), ...]\n\nthen you could iterate on this new sequence and make each function apply on the corresponding data. Since you just want to collect them into a list, list comprehension is much better than a for-lo...
[ 9, 2, 2, 2, 0 ]
[]
[]
[ "arguments", "function", "list", "mapping", "python" ]
stackoverflow_0003848829_arguments_function_list_mapping_python.txt
Q: Python: a could be rounded to b in the general case As a part of some unit testing code that I'm writing, I wrote the following function. The purpose of which is to determine if 'a' could be rounded to 'b', regardless of how accurate 'a' or 'b' are. def couldRoundTo(a,b): """Can you round a to some number of ...
Python: a could be rounded to b in the general case
As a part of some unit testing code that I'm writing, I wrote the following function. The purpose of which is to determine if 'a' could be rounded to 'b', regardless of how accurate 'a' or 'b' are. def couldRoundTo(a,b): """Can you round a to some number of digits, such that it equals b?""" roundEnd = len(str(...
[ "\nCould someone tell me if this is an appropriate way to implement this function? \n\nIt depends. The given function will behave surprisingly if b isn't precisely equal to a value that would normally be obtained directly from decimal-to-binary-float conversion.\nFor example:\n>>> print(0.1, 0.2/2, 0.3/3)\n0.1 0.1 ...
[ 3, 1, 0, 0 ]
[]
[]
[ "floating_point", "python", "rounding" ]
stackoverflow_0003848865_floating_point_python_rounding.txt
Q: IndentationError: unindent does not match any outer indentation level def LCS(word_list1, word_list2): m = len(word_list1) n = len(word_list2) print m print n C = [[0] * (n+1) for i in range(m+1)] # IndentationError: unindent does not match any outer indentation level print C ...
IndentationError: unindent does not match any outer indentation level
def LCS(word_list1, word_list2): m = len(word_list1) n = len(word_list2) print m print n C = [[0] * (n+1) for i in range(m+1)] # IndentationError: unindent does not match any outer indentation level print C i=0 j=0 for word in word_list1: j=0 for word in wo...
[ "It's hard to answer a question on why indentation is incorrect when the question keeps being edited and the indentation corrected.\nHowever, I suggest you read PEP8 before writing any more Python code and avoid mixing tabs and spaces. This would explain why you still see an IndentationError on line seven after you...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003849021_python.txt
Q: Python: how to use value stored in a variable to decide which class instance to initiate? I'm building a Django site. I need to model many different product categories such as TV, laptops, women's apparel, men's shoes, etc. Since different product categories have different product attributes, each category has its...
Python: how to use value stored in a variable to decide which class instance to initiate?
I'm building a Django site. I need to model many different product categories such as TV, laptops, women's apparel, men's shoes, etc. Since different product categories have different product attributes, each category has its own separate Model: TV, Laptop, WomensApparel, MensShoes, etc. And for each Model I created a ...
[ "If all your *Form classes are in the one module (let's call it forms), you can do this:\nimport forms\n\nform = getattr(forms, category + \"Form\")()\n\n(Obviously, add whatever verification is necessary, such as catching AttributeError. Security-wise, if you are using a named module rather than the global namespa...
[ 10, 9, 1 ]
[]
[]
[ "django", "django_forms", "django_models", "metaprogramming", "python" ]
stackoverflow_0003849047_django_django_forms_django_models_metaprogramming_python.txt
Q: WSAEventSelect with FD_ACCEPT, recv returns WSAEWOULDBLOCK I'm trying to setup a socket that won't block on accept(...), using the following code: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 1234)) event = win32event.CreateEvent(None, True, False, None) win32file.WSAEventSelect...
WSAEventSelect with FD_ACCEPT, recv returns WSAEWOULDBLOCK
I'm trying to setup a socket that won't block on accept(...), using the following code: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("127.0.0.1", 1234)) event = win32event.CreateEvent(None, True, False, None) win32file.WSAEventSelect(sock.fileno(), event, win32file.FD_ACCEPT) sock.listen(5) rc = ...
[ "Solved this by: adding the following lines before accept:\nwin32file.WSAEventSelect(sock.fileno(), event, 0)\nsock.setblocking(1)\n\n" ]
[ 0 ]
[]
[]
[ "python", "winapi" ]
stackoverflow_0003849410_python_winapi.txt
Q: Codechef python runtime error I always get a runtime error using python for submission on codechef. Can some one please help. Tried answering other questions too.. same error Works fine on my comp though!(I use python 2.6.5 on my comp. Answer is checked with python 2.5) This is an easy level question where i get R...
Codechef python runtime error
I always get a runtime error using python for submission on codechef. Can some one please help. Tried answering other questions too.. same error Works fine on my comp though!(I use python 2.6.5 on my comp. Answer is checked with python 2.5) This is an easy level question where i get Runtime error http://www.codechef.co...
[ "I don't compete/submit at Codechef, but AFAIK it uses Python 2.5 rather than 2.6. Perhaps you are using something that is 2.5-specific? (although I can't find anything that is). \nEdit:\nIt looks to me now that the problem isn't with Python versions at all. Notice in the problem statement that the input value N ca...
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003846971_python.txt
Q: Is Celery appropriate for use with many small, distributed systems? I'm writing some software which will manage a few hundred small systems in “the field” over an intermittent 3G (or similar) connection. Home base will need to send jobs to the systems in the field (eg, “report on your status”, “update your softwar...
Is Celery appropriate for use with many small, distributed systems?
I'm writing some software which will manage a few hundred small systems in “the field” over an intermittent 3G (or similar) connection. Home base will need to send jobs to the systems in the field (eg, “report on your status”, “update your software”, etc), and the systems in the field will need to send jobs back to the...
[ "\nThe majority of tasks will be directed\n to an individual worker (eg, “send the\n ‘get_status’ job to ‘system51’”) —\n will this be a problem?\n\nNot at all. Just create a queue for each worker, e.g. say each node listens to a round robin queue called default and each node has its own queue named after its no...
[ 12, 1 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0003848024_celery_python.txt