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: Nested for loops in Python I want to do something like for a in [0..1]: for b in [0..1]: for c in [0..1]: do something But, I might have 15 different variables. Is there a simpler way like for a, b, c in [0..1]: do something Thanks for any help A: itertools.product: import itertool...
Nested for loops in Python
I want to do something like for a in [0..1]: for b in [0..1]: for c in [0..1]: do something But, I might have 15 different variables. Is there a simpler way like for a, b, c in [0..1]: do something Thanks for any help
[ "itertools.product:\nimport itertools\nfor a,b,c in itertools.product([0, 1], repeat=3):\n # do something\n\n", "You can iterate over the product of all of them. Use itertools.product and pass in your ranges.\nimport itertools\nfor i in itertools.product(range(2), range(3), range(2)):\nprint (i)\n\nyields\n(0, 0...
[ 12, 4, 1 ]
[]
[]
[ "loops", "python" ]
stackoverflow_0007164162_loops_python.txt
Q: Any difference between these 2 imports? Do the below 2 import statements have some difference? Or just the same thing? from package import * import package A: from package import * imports everything from package into the local namespace; this is not recommended because it may introduce unwanted things (like a ...
Any difference between these 2 imports?
Do the below 2 import statements have some difference? Or just the same thing? from package import * import package
[ "from package import * imports everything from package into the local namespace; this is not recommended because it may introduce unwanted things (like a function that overwrites a local one). This is a quick and handy import tool, but if things get serious, you should use the from package import X,Y,Z, or import p...
[ 12, 3 ]
[]
[]
[ "python" ]
stackoverflow_0007164234_python.txt
Q: Missing scipy functions in fftpack I installed scipy with easy_install scipy, but Python cannot find the scipy.fftpack.dct() function. What did I do wrong? A: scipy.fftpack.dct is available in scipy version 0.10.dev, but is missing in version 0.9. So you probably have version 0.9 or earlier.
Missing scipy functions in fftpack
I installed scipy with easy_install scipy, but Python cannot find the scipy.fftpack.dct() function. What did I do wrong?
[ "scipy.fftpack.dct is available in scipy version 0.10.dev, but is missing in version 0.9. So you probably have version 0.9 or earlier.\n" ]
[ 4 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0007164216_numpy_python_scipy.txt
Q: Validating checkboxes from form in Django Relatively new to Python.. I would like to know how to check if a check box has been selected. I am reading the form values into a python script and am unsure how to go about validating. Using the Web Framework Django. The form is being posted back to a views.py script. I...
Validating checkboxes from form in Django
Relatively new to Python.. I would like to know how to check if a check box has been selected. I am reading the form values into a python script and am unsure how to go about validating. Using the Web Framework Django. The form is being posted back to a views.py script. I am loading up a dictionary with many different...
[ "The documentation for Django is really quite good. Check out the description of the HttpRequest class for more information on how this part works. The short answer is that you can do something like this:\ndef myview(request):\n # do stuff\n option_checked = 'myvariable.checkboxoption' in request.REQUEST\n ...
[ 2 ]
[]
[]
[ "checkbox", "django", "python", "validation" ]
stackoverflow_0007163567_checkbox_django_python_validation.txt
Q: Adding widgets from Glade file to a subclass of gtk.Window in Python. How? I've made an interface using Glade. I want to then create a subclass of gtk.Window - in Python - and pass in that file to it. Then I'd like to be able to play with the widgets that I added in Glade as I would if I'd created them using regul...
Adding widgets from Glade file to a subclass of gtk.Window in Python. How?
I've made an interface using Glade. I want to then create a subclass of gtk.Window - in Python - and pass in that file to it. Then I'd like to be able to play with the widgets that I added in Glade as I would if I'd created them using regular code. Here is something I'd quite like to do: class MainWindow (gtk.Window): ...
[ "Try this:\nclass MainWindow (gtk.Window):\n def __init__(self):\n self.builder = gtk.Builder()\n self.builder.add_from_file('gladefile.ui')\n self.builder.get_object('button1').set_label(\"Hello, World!\")\n\nGtk.Window and Gtk.Builder are different.\n" ]
[ 0 ]
[]
[]
[ "glade", "gtk", "pygtk", "python" ]
stackoverflow_0007135743_glade_gtk_pygtk_python.txt
Q: How do I create a modal dialog with no title bar icon in PyGTK? Using PyGTK on Windows, I want to create a modal dialog that does not have a title bar icon, per Microsoft's user interface guidelines for dialogs. The guidelines specify that most dialog boxes should not have title bar icons (except dialogs that impl...
How do I create a modal dialog with no title bar icon in PyGTK?
Using PyGTK on Windows, I want to create a modal dialog that does not have a title bar icon, per Microsoft's user interface guidelines for dialogs. The guidelines specify that most dialog boxes should not have title bar icons (except dialogs that implement a main window or utility, and appear on the taskbar). A lack of...
[ "Try this\nwindow = gtk.Window()\ndialog = gtk.Dialog()\n\ndialog.set_modal(True)\ndialog.set_transient_for(window)\ndialog.set_decorated(False)\n\nwindow.show()\ndialog.show()\n\ngtk.main()\n\n" ]
[ 4 ]
[]
[]
[ "gtk", "pygtk", "python" ]
stackoverflow_0005357479_gtk_pygtk_python.txt
Q: Extending Google Appstats After watching Guido's Google IO talk and hearing the mention that it can be extended (thus providing an instrumentation mechanism for recording your own events) I am still at a loss on how this would be done. The functions are all for handling RPC and not simply start/stop calls an expen...
Extending Google Appstats
After watching Guido's Google IO talk and hearing the mention that it can be extended (thus providing an instrumentation mechanism for recording your own events) I am still at a loss on how this would be done. The functions are all for handling RPC and not simply start/stop calls an expensive function (or wrapper) can ...
[ "I was referring to the ability to record custom events. A simple example is:\nfrom google.appengine.ext.appstats import recording\nrecording.recorder.record_custom_event('hello', 'data')\n\nNote that you should really check whether recorder is not None before calling its record_custom_event() method.\n" ]
[ 2 ]
[]
[]
[ "appstats", "google_app_engine", "python" ]
stackoverflow_0007151930_appstats_google_app_engine_python.txt
Q: How to extend this python script to take in user input by command line instead of prompting? Currently, I have a python script which takes in a text file, checks for passages enclosed by a tag ##Somethinghere## and asks the user how many times does he/she want to copy it. So for instance if I have the text file: R...
How to extend this python script to take in user input by command line instead of prompting?
Currently, I have a python script which takes in a text file, checks for passages enclosed by a tag ##Somethinghere## and asks the user how many times does he/she want to copy it. So for instance if I have the text file: Random Text File ##RandomLine1## Random Line 1 ##RandomLine1## Random Line 2 ##RandomLine3## Ran...
[ "Yes you can do this by adding default values to your arguments:\nparser.add_argument(\"--RandomLine1\", default=None)\n# same for RandomLine2\n\n# ...\n\nif args.RandomLine1 is not None:\n # use args.RandomLine1 as a number\n #...\nelse:\n # RandomNumber1 is not given in the args\n #...\n\n", "How ab...
[ 2, 2 ]
[]
[]
[ "python", "scripting" ]
stackoverflow_0007162045_python_scripting.txt
Q: How to compile and execute code dynamically? There are some websites (like this one) that allows users to submit code in different languages and the system compiles and executes test cases on them. As a developer, I am curious to know how they do this and how are they supporting multiple languages (PHP, Python, C,...
How to compile and execute code dynamically?
There are some websites (like this one) that allows users to submit code in different languages and the system compiles and executes test cases on them. As a developer, I am curious to know how they do this and how are they supporting multiple languages (PHP, Python, C, .NET, javascript)? Isn't it possible that the cod...
[ "\nam curious to know how they do this and how are they supporting multiple languages (PHP, Python, C, .NET, javascript)?\n\nSimple: Have multiple language installations installed and invoke the correct one for the given input (which is of course given by the user).\n\nIsn't it possible that the code submitted can ...
[ 3, 0 ]
[]
[]
[ ".net", "c", "php", "python" ]
stackoverflow_0007165381_.net_c_php_python.txt
Q: simple server with multiple clients I'm trying to implement simple server with multiple clients. It should receive data from necessary socket, process and then send data to other clients. I use select module from Python standard library. Here's server: class ProcessingServer: def __init__(self, bindaddress="l...
simple server with multiple clients
I'm trying to implement simple server with multiple clients. It should receive data from necessary socket, process and then send data to other clients. I use select module from Python standard library. Here's server: class ProcessingServer: def __init__(self, bindaddress="localhost", portname=50001, maxqueue=5): ...
[ "Yeah...use zeromq instead:\nserver.py\nimport zmq\ncontext = zmq.Context()\nsocket = context.socket(zmq.REP)\nsocket.bind(\"tcp://127.0.0.1:50001\")\n\nwhile True:\n msg = socket.recv()\n print \"Got\", msg\n socket.send(msg)\n\nclient.py\nimport zmq\ncontext = zmq.Context()\nsocket = context.socket(zmq.R...
[ 2, 2 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0007162578_networking_python_sockets.txt
Q: Allow a wxPanel dervied object to accept focus I'm using matplotlib to generate charts and displaying these in a WxPython based frontend using FigureCanvasWxAgg object (from matplotlib) which is derived from WxPanel. I want to add functionality to each chart to allow the arrow keys to control the position of an ov...
Allow a wxPanel dervied object to accept focus
I'm using matplotlib to generate charts and displaying these in a WxPython based frontend using FigureCanvasWxAgg object (from matplotlib) which is derived from WxPanel. I want to add functionality to each chart to allow the arrow keys to control the position of an overlay if that chart is selected. In order to do this...
[ "wx.Panel doesn't really accept focus. It just passes the focus on to a widget that can. Only when it doesn't have a child can it accept focus. You may need to call SetFocus() on it though. This article tries to explain it: http://www.blog.pythonlibrary.org/2009/08/27/wxpython-learning-to-focus/\n" ]
[ 1 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0007145970_matplotlib_python_wxpython.txt
Q: Return all lines following a matched date and time up, but not including the next date and time? I'm trying to grab a snippet of text from a file that exists between two lines. Specifically I need to be able to grab a line and all the following lines up until another specific line. For example, the Raw file would ...
Return all lines following a matched date and time up, but not including the next date and time?
I'm trying to grab a snippet of text from a file that exists between two lines. Specifically I need to be able to grab a line and all the following lines up until another specific line. For example, the Raw file would contain something like this: Aug 23, 2011 10:31:35 AM This is the start of the text. This is more...
[ "import re\n\ns = '''Aug 23, 2011 10:31:35 AM This is the start of the text.\n This is more Text.\nThis is another line\nThis is another line\n This is more.\nAug 23, 2011 10:41:00 AM This is the next in the series.\nThis is another line\n This is more Text.\nThis is another line\n This is anoth...
[ 1 ]
[]
[]
[ "logging", "parsing", "python", "regex" ]
stackoverflow_0007165119_logging_parsing_python_regex.txt
Q: Python: Random item from list combining only two I'm making a slot machine program in Python and for some reason, the random selector wants to combine a known two elements. itmlist = random.choice(['banana', 'cherry', 'bar', 'seven', 'banana', 'cherry' 'banana', 'cherry', 'seven']) print itmlist It shows ...
Python: Random item from list combining only two
I'm making a slot machine program in Python and for some reason, the random selector wants to combine a known two elements. itmlist = random.choice(['banana', 'cherry', 'bar', 'seven', 'banana', 'cherry' 'banana', 'cherry', 'seven']) print itmlist It shows up as "cherrybanana" every once in a while and I am re...
[ "You miss a comma between 'cherry' and 'banana' near the end of the list.\nPython concatenate the strings so it becomes 'cherrybanana'\nitmlist = random.choice(['banana', 'cherry', 'bar', 'seven', 'banana', 'cherry' 'banana', 'cherry', 'seven'])\n" ]
[ 11 ]
[]
[]
[ "python" ]
stackoverflow_0007165654_python.txt
Q: python aboutdialog space between program name/version and logo please how can i set space between program name/version and logo in this code? I am using pygtk. thanks about = gtk.AboutDialog() about.set_program_name("name") about.set_version("0.0.1") about.set_logo(gtk.gdk.pixbuf_new_from_file("file.png")) A: It...
python aboutdialog space between program name/version and logo
please how can i set space between program name/version and logo in this code? I am using pygtk. thanks about = gtk.AboutDialog() about.set_program_name("name") about.set_version("0.0.1") about.set_logo(gtk.gdk.pixbuf_new_from_file("file.png"))
[ "It's kind of hacky I suppose, but this works:\nimport gtk\n\nabout = gtk.AboutDialog()\nabout.set_program_name(\"name\")\nabout.set_version(\"0.0.1\")\nabout.set_logo(gtk.gdk.pixbuf_new_from_file(\"file.png\"))\nabout.show()\n\nvbox = about.get_children()[0].get_children()[0] # vbox containing everything but the ...
[ 1 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0007163858_pygtk_python.txt
Q: python Matplotlib -- Multiple Chart Objects? How can I use matplotlib to create many different chart objects and then have the ability to control each chart object separately (without affecting the other chart objects)? Ideally, I'd like to have something of the following: # creating the chart handler object chart...
python Matplotlib -- Multiple Chart Objects?
How can I use matplotlib to create many different chart objects and then have the ability to control each chart object separately (without affecting the other chart objects)? Ideally, I'd like to have something of the following: # creating the chart handler object chartHandler = ChartHandler() # plotting some values fo...
[ "Unless you are talking about something that I haven't dealt with in matplotlib yet, I think that what you are looking for is figure.add_subplot(). You should be able to capture the return from each figure.add_subplot() and operate on each individually from then on, kind of like this:\nimport matplotlib.pyplot as ...
[ 2 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0007164017_matplotlib_python.txt
Q: Defer processing in Python I'm trying to write events in a non-blocking fashion so as not to slow down any of our existing processes. It seems like the two options available are: use Twisted's defer object create a python logging handler Are there other options. Anybody have experience with this? Background: W...
Defer processing in Python
I'm trying to write events in a non-blocking fashion so as not to slow down any of our existing processes. It seems like the two options available are: use Twisted's defer object create a python logging handler Are there other options. Anybody have experience with this? Background: We're planning to write events to...
[ "If logging fits your application, and it sounds so, it should be simpler than using twisted. You could log to a thread safe queue in memory and have a separate thread (or several) pull from it and push to the cloud.\nThat said, twisted may be faster or at least more scalable, but, especially if you don't know it, ...
[ 1, 1 ]
[]
[]
[ "boto", "eventlet", "gevent", "python", "twisted" ]
stackoverflow_0007100155_boto_eventlet_gevent_python_twisted.txt
Q: Which web application framework to use with existing database? My company wants to start mobile web application development, as an addition to our own ERP software. We do not have any expert knowledge about this, that is why I have to research which tools/frameworks/languages we are going to use. We already have a...
Which web application framework to use with existing database?
My company wants to start mobile web application development, as an addition to our own ERP software. We do not have any expert knowledge about this, that is why I have to research which tools/frameworks/languages we are going to use. We already have an existing database, and want to be able to quickly build an extra s...
[ "\nWe develop our desktop software in Delphi, and therefore are not experienced web developers.\n\nIn that case, I think you are solving the wrong problem:\nHire a team lead who is (even if it is just as a contract role for the first project or two). You need to have someone on board who is aware of all the technol...
[ 2, 1, 0 ]
[]
[]
[ "frameworks", "mobile", "php", "python" ]
stackoverflow_0007158952_frameworks_mobile_php_python.txt
Q: Connect to authenticated REST service c# to get back JSON data I am trying to call a REST Api to get back some JSON data and I can't make it connect. I think it needs a cached cookie or something to work. Any ideas or people that have used the REST Bitbucket.org api? Here is api address I am using https://api.bitb...
Connect to authenticated REST service c# to get back JSON data
I am trying to call a REST Api to get back some JSON data and I can't make it connect. I think it needs a cached cookie or something to work. Any ideas or people that have used the REST Bitbucket.org api? Here is api address I am using https://api.bitbucket.org/1.0/user/repositories/. It works if you used directly in t...
[ "Use Fiddler or Wireshark to compare what goes over the wire when it works (browser) and when it doesn't work (your code)... once you know the differences you can change your code accordingly...\n" ]
[ 1 ]
[]
[]
[ "bitbucket", "c#", "http", "python", "rest" ]
stackoverflow_0007166671_bitbucket_c#_http_python_rest.txt
Q: How do you allow a Python script access to mkdir in a protected directory without su access in Linux? I'm trying to create a python shell script to create a number of directories in Ubuntu Linux. The main directory I'm trying to create directories in is protected from write access. Is there a way to allow the Pyth...
How do you allow a Python script access to mkdir in a protected directory without su access in Linux?
I'm trying to create a python shell script to create a number of directories in Ubuntu Linux. The main directory I'm trying to create directories in is protected from write access. Is there a way to allow the Python script to be allowed to create directories in there as if it's the root user but not have to run the scr...
[ "This question is not really related to Python. The Python script is just a process like any other process and needs to have to right permissions to do things. The usual method is to create a group, and make the parent directory g+ws for that group. Then add the appropriate users to that group as a supplemental gro...
[ 6, 2, 0, 0, 0 ]
[]
[]
[ "filesystems", "linux", "python", "shell" ]
stackoverflow_0007166528_filesystems_linux_python_shell.txt
Q: Twisted time counter I'm trying to write time counter with Twisted so that when I request GET /timer then it returns current count. First request starts the counter. Unfortunately, always when I request /timer it makes an additional new counter beginning from 0. Does anybody know, how to tweak the following code s...
Twisted time counter
I'm trying to write time counter with Twisted so that when I request GET /timer then it returns current count. First request starts the counter. Unfortunately, always when I request /timer it makes an additional new counter beginning from 0. Does anybody know, how to tweak the following code so that it doesn't create n...
[ "Try this. I tested this out a few months ago and it worked fine. It will create a session cookie on the client.\nclass MyResource(Resource):\n # ...\n def render(self, request):\n session = request.getSession()\n if not hasattr(session, 'count'):\n session.count = itertools.count()\n request.writ...
[ 2 ]
[]
[]
[ "counter", "python", "time", "twisted" ]
stackoverflow_0007166826_counter_python_time_twisted.txt
Q: Python data to CSVs I'm having trouble getting my python data to write as csvs, either using pylab's rec2csv or using csv.writer. I'm having particular trouble with rec.arrays that are of width 1 with rec2csv. What I would like to do is have each element in an array (or list) as a column in a csv file. For exam...
Python data to CSVs
I'm having trouble getting my python data to write as csvs, either using pylab's rec2csv or using csv.writer. I'm having particular trouble with rec.arrays that are of width 1 with rec2csv. What I would like to do is have each element in an array (or list) as a column in a csv file. For example, using any of these d...
[ "I'm not familiar with rec2csv or some of the other (numpy? scipy?) stuff you're using, but here is a simple example with the standard csv module:\nimport csv\nwriter = csv.writer(open(\"test_out.csv\", 'wt'))\nl1 = ['a', 'b', 'c']\nl2 = [n for n in xrange(len(l1))]\nfor row in xrange(len(l1)):\n writer.writerow...
[ 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0007167068_csv_python.txt
Q: Python list greater than number I have discovered that a list is greater than a number. >>> [1,2,3] > 1000 True Is there some reason why this works? I can't convert a list to an int with int([1,2,3]). The int can't be converted to a list with list(1000). So how is python comparing the two? A: In this case of "m...
Python list greater than number
I have discovered that a list is greater than a number. >>> [1,2,3] > 1000 True Is there some reason why this works? I can't convert a list to an int with int([1,2,3]). The int can't be converted to a list with list(1000). So how is python comparing the two?
[ "In this case of \"mismatched\" types, the types are listed lexicographically by type name: a \"list\" comes after an \"int\" in alphabetical ordering, so it is greater.\n\nCPython implementation detail: Objects of different types except\n numbers are ordered by their type names; objects of the same types\n that ...
[ 27, 10 ]
[]
[]
[ "python", "python_2.7" ]
stackoverflow_0007167657_python_python_2.7.txt
Q: Catch socket timeout exception I would like to catch the socket timeout (preferably in an exception) ... except urllib.error.URLError: can catch it but I need to distinguished between a dead link and a timeout .... If I take out the except urllib.error.URLError: the socket timeout does not catch and script termina...
Catch socket timeout exception
I would like to catch the socket timeout (preferably in an exception) ... except urllib.error.URLError: can catch it but I need to distinguished between a dead link and a timeout .... If I take out the except urllib.error.URLError: the socket timeout does not catch and script terminates with an socket.timeout error imp...
[ "...\nexcept urllib.error.URLError, e:\n print type(e.reason)\n\nYou will see <class 'socket.timeout'> whenever there is a socket timeout. Is this what you want?\nFor example:\ntry:\n data = urllib2.urlopen(\"http://www.abcnonexistingurlxyz.com\")\nexcept Exception,e:\n print type(e.reason)\n... \n<class 'sock...
[ 5 ]
[]
[]
[ "python", "python_3.x", "sockets", "timeout" ]
stackoverflow_0007167107_python_python_3.x_sockets_timeout.txt
Q: How can I compare version numbers in SQLAlchemy? (Given a function to do so) I have this function for comparing version numbers: def version_gt(left, right): """ Compare two version numbers telling which is greater Returns True if left is greater, False if right is greater. """ left = map(...
How can I compare version numbers in SQLAlchemy? (Given a function to do so)
I have this function for comparing version numbers: def version_gt(left, right): """ Compare two version numbers telling which is greater Returns True if left is greater, False if right is greater. """ left = map(int, filter(None, str(left).split('.'))) right = map(int, filter(None, str(rig...
[ "The sqlite database engine is not quite expressive enough to do that kind of comparison on a single column, even in raw SQL. The best option will be to split out the version column into several, or to simply accept a simple string comparison (something to the effect of updates1.version > updates2.version. If non...
[ 1 ]
[]
[]
[ "comparator", "python", "sqlalchemy" ]
stackoverflow_0007167583_comparator_python_sqlalchemy.txt
Q: Parent/Child database contains cyclical references I have a keyword table where each keyword is assigned an id and is unique. I have a second table that links ids of parent keywords to ids of child keywords. One keyword can have up to approx 800 children or have none at all. Children can be parents of yet more key...
Parent/Child database contains cyclical references
I have a keyword table where each keyword is assigned an id and is unique. I have a second table that links ids of parent keywords to ids of child keywords. One keyword can have up to approx 800 children or have none at all. Children can be parents of yet more keywords (and on and on...) The issue I am running into is ...
[ "What you are trying to do is create a topological sort. There are a number of methods published for doing this optimally and it will depend on your schema and preferred method.\nIn your case it sounds like you do not have multi-parent.\nBut how I have dealt with it programmatically is to start with the leaf nodes ...
[ 2, 1 ]
[]
[]
[ "directed_acyclic_graphs", "mysql", "python", "topology" ]
stackoverflow_0007165595_directed_acyclic_graphs_mysql_python_topology.txt
Q: Optimizing Python Code I've been working on one of the coding challenges on InterviewStreet.com and I've run into a bit of an efficiency problem. Can anyone suggest where I might change the code to make it faster and more efficient? Here's the code Here's the problem statement if you're interested A: If your que...
Optimizing Python Code
I've been working on one of the coding challenges on InterviewStreet.com and I've run into a bit of an efficiency problem. Can anyone suggest where I might change the code to make it faster and more efficient? Here's the code Here's the problem statement if you're interested
[ "If your question is about optimising python code generally (which I think it should be ;) then there are all sorts of intesting things you can do, but first:\nYou probably shouldn't be obsessively optimising python code! If you're using the fastest algorithm for the problem you're trying to solve and python doesn'...
[ 108, 3, 2, 1 ]
[]
[]
[ "optimization", "performance", "python" ]
stackoverflow_0007165465_optimization_performance_python.txt
Q: How can I write each line of this python print function to a list of strings? I have... >>> for i in range(11): ... for j in range(103): ... print "./", '%02d' % i, "/IMG", '%04d' % j, ".jpg" ... >>> (prints a whole bunch of lines representing files in a group of directories) ...and what I want in...
How can I write each line of this python print function to a list of strings?
I have... >>> for i in range(11): ... for j in range(103): ... print "./", '%02d' % i, "/IMG", '%04d' % j, ".jpg" ... >>> (prints a whole bunch of lines representing files in a group of directories) ...and what I want instead is to concatenate the little strings and ints in those lines into single stri...
[ "ITYM\nl = []\nfor i in range(11):\n for j in range(103):\n l.append()\n\nor, shorter,\nl = ['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in range(103)]\n\n", "['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in xrange(103)]\n\n", "from itertools import product\n['./%02d/IMG%04d.jpg'%...
[ 4, 3, 3 ]
[]
[]
[ "python", "string", "string_concatenation" ]
stackoverflow_0007167865_python_string_string_concatenation.txt
Q: losing characters when going from unicode to ascii y0 I have this problem that characters that include ñ or ŕ í á ú etc are discarded when I apply text = text.encode('ascii', 'ignore') to a function that needs the input to be ascii. is there a way to force it to ascii without losing those characters or should I ...
losing characters when going from unicode to ascii
y0 I have this problem that characters that include ñ or ŕ í á ú etc are discarded when I apply text = text.encode('ascii', 'ignore') to a function that needs the input to be ascii. is there a way to force it to ascii without losing those characters or should I change the function to accept unicode characters? http:/...
[ "The 'ascii' encoding can't represent the characters you refer to. You have to choose a different encoding — perhaps 'cp850' or 'latin_1' — but then you have to be sure that your output terminal interprets 8-bit codes using the relevant code page.\nOn balance, life is easier if you just go Unicode all the way.\n", ...
[ 5, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007168186_django_python.txt
Q: Read/Write files problem I`ve been trying to copy a long text from one file to another file but it always copied me just a small part of it. It looks like a limit problem which i can solve. I would be glad if anyone can help me or explain which is my error. def runMenu(): print "\nMENU" print " 1) Copiar" print ...
Read/Write files problem
I`ve been trying to copy a long text from one file to another file but it always copied me just a small part of it. It looks like a limit problem which i can solve. I would be glad if anyone can help me or explain which is my error. def runMenu(): print "\nMENU" print " 1) Copiar" print " 0) Exit" response = int( r...
[ "Use shutil.copy()\nhttp://docs.python.org/library/shutil.html#shutil.copy\n\nshutil.copy(src, dst)\nCopy the file src to the file or directory dst. If dst is a directory, a file with the same basename as src is created (or overwritten) in the directory specified. Permission bits are copied. src and dst are path na...
[ 2, 0, 0, 0 ]
[ "Maybe you have to call the read/write function (archivo2.write(archivo.read())\n) more often than once.\nTry to get it in an Loop and copy the file data until the \"Eof\" (end of file).\nUse a loop, something like this:\nwhile not Eof(archivo) do\n...\n\n" ]
[ -1 ]
[ "file", "python" ]
stackoverflow_0007166220_file_python.txt
Q: Crypto module is not visible to Python after installation on Windows XP I'm trying to use the Crypto module in Python. I downloaded the Windows installer that was referenced here on StackOverflow (an msi) and the installation went fine. However, when the interpreter hits the 'from Crypto.Cipher import AES' line in...
Crypto module is not visible to Python after installation on Windows XP
I'm trying to use the Crypto module in Python. I downloaded the Windows installer that was referenced here on StackOverflow (an msi) and the installation went fine. However, when the interpreter hits the 'from Crypto.Cipher import AES' line in my code, it fails saying there is no such module. I've also done a help('mod...
[ "Works for me:\nPython 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on\nwin32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from Crypto.Cipher import AES\n>>>\n\nSome steps to try:\n\nDownload from this link: http://www.voidspace.org.uk/python/module...
[ 4 ]
[]
[]
[ "cryptography", "python", "windows_xp" ]
stackoverflow_0006132192_cryptography_python_windows_xp.txt
Q: Client authorization with python backend I'm writing panel for administrating nginx (domains, rewrites, etc), svn and other services. For that, i'm writing backend that will work on root (to change nginx configs, reload them, change user passwords, etc), and client (console client, and web app). App works on unix ...
Client authorization with python backend
I'm writing panel for administrating nginx (domains, rewrites, etc), svn and other services. For that, i'm writing backend that will work on root (to change nginx configs, reload them, change user passwords, etc), and client (console client, and web app). App works on unix sockets, and i made very simple protocol for i...
[ "Don't reinvent the wheel. ;) I found this discussion enlightening:\n\nhttp://cyberelk.net/tim/2007/03/08/cups-unix-domain-sockets-authentication/ Explains the concept of socket auth.\nhttp://pythonic.pocoo.org/2007/7/7/unix-socket-credentials-with-python Helpful details.\nhttp://atlee.ca/software/pam/ This mig...
[ 1 ]
[]
[]
[ "authorization", "python", "security", "sockets" ]
stackoverflow_0007164820_authorization_python_security_sockets.txt
Q: ElementTree returns no nodes parsing simple KML document I have a very simple KML file which returns no nodes when parsed with ElementTree. This is frustrating me :-). Any clues? from xml.etree import ElementTree from pprint import pprint kml = '''<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http...
ElementTree returns no nodes parsing simple KML document
I have a very simple KML file which returns no nodes when parsed with ElementTree. This is frustrating me :-). Any clues? from xml.etree import ElementTree from pprint import pprint kml = '''<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://earth.google.com/kml/2.0"> <Document> <name>NEXRAD Radar ...
[ "The tags are namespaced. If you try tree.iter() with no tag it will show what ElementTree thinks the tags are called. The wsr tag is called {http://earth.google.com/kml/2.0}wsr. This returns a node:\nlist(tree.iter('{http://earth.google.com/kml/2.0}wsr'))\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0007168432_python.txt
Q: cross platform gui..which tool to use? I am developing a python program (my native platform is Ubuntu) for which I would like to build a simple gui. I would like the GUI to be cross platform.I came across python-gtk/wxpython/qt. What is the best tool to use? Thanks suresh A: Your best bet would be either wxPyt...
cross platform gui..which tool to use?
I am developing a python program (my native platform is Ubuntu) for which I would like to build a simple gui. I would like the GUI to be cross platform.I came across python-gtk/wxpython/qt. What is the best tool to use? Thanks suresh
[ "Your best bet would be either wxPython or Qt, although I'd lean strongly towards wxPython based on my previous use. Both of these have fairly good fidelity on both Windows and OSX and feel and look like native applications.\nGTK has marginal Windows support and pretty bad support on OSX. I would recommend against ...
[ 4, 1, 0 ]
[]
[]
[ "cross_platform", "python", "user_interface" ]
stackoverflow_0007167985_cross_platform_python_user_interface.txt
Q: Python streaming std(in/out/err) to another process I have a python process running "in the background". It's a subprocess.Popen() call started in a totally different process. As I've implemented it so far, the two processes are using multiprocessing.connections.(Listener|Client) to communicate with eachother. ...
Python streaming std(in/out/err) to another process
I have a python process running "in the background". It's a subprocess.Popen() call started in a totally different process. As I've implemented it so far, the two processes are using multiprocessing.connections.(Listener|Client) to communicate with eachother. But I'm open to any way to accomplish the following. What...
[ "I'm not entirely sure I understand the question, but have you looked into using select with pipes/sockets to avoid blocking? I'm a bit vague on the other req that it \"not be read into memory.\"\n" ]
[ 1 ]
[]
[]
[ "io", "python" ]
stackoverflow_0007117189_io_python.txt
Q: Django site very slow to load after restart or period of inactivity I'm running a Django site on Apache, and am experiencing very slow intial page loads after a period of inactivity (about 1 hour). I can replicate by leaving for an hour, or bouncing the server. After the initial load, pages load consistently in ...
Django site very slow to load after restart or period of inactivity
I'm running a Django site on Apache, and am experiencing very slow intial page loads after a period of inactivity (about 1 hour). I can replicate by leaving for an hour, or bouncing the server. After the initial load, pages load consistently in < 1 sec. I'm assuming (guessing) the issue is the Python interpreter + Py...
[ "A few ideas:\n\nMake sure you have enough memory and that there is some free and a healthy disk cache available. You should have at least 1gb to 4+gb total depending on what you are doing. Top was mentioned, and I recommend htop: http://htop.sourceforge.net/\nIncrease disk caching, if for example, you are using ...
[ 0 ]
[]
[]
[ "apache", "django", "httpd.conf", "mod_wsgi", "python" ]
stackoverflow_0007094716_apache_django_httpd.conf_mod_wsgi_python.txt
Q: building executable using python,vtk and py2exe Is it possible to create a binary executable with py2exe for vtk? Could someone provide a minimum working example or at least some hints? Py2exe is not necessary. If there is a working solution on other similar programs (bbfreeze etc) I am intrested too. A: This ex...
building executable using python,vtk and py2exe
Is it possible to create a binary executable with py2exe for vtk? Could someone provide a minimum working example or at least some hints? Py2exe is not necessary. If there is a working solution on other similar programs (bbfreeze etc) I am intrested too.
[ "This example uses py2exe. Use packages to add any referenced libraries and options includes to add dependencies. I am not too sure about the exact semantics and I reached this stable configuration after much trial and error. Hopefully, you can use this as a template to go ahead.\nfrom distutils.core import setup\n...
[ 2 ]
[]
[]
[ "py2exe", "python", "vtk" ]
stackoverflow_0007050670_py2exe_python_vtk.txt
Q: How to solve this double encoding? I'm developing a website using python to preprocess request and a MySQL database to store information. All my tables are utf8 and I also use utf8 as Content-type. I have this code to establish connection to the db: database_connection = MySQLdb.connect(host = database_host, user ...
How to solve this double encoding?
I'm developing a website using python to preprocess request and a MySQL database to store information. All my tables are utf8 and I also use utf8 as Content-type. I have this code to establish connection to the db: database_connection = MySQLdb.connect(host = database_host, user = database_username, passwd = database_p...
[ "It sounds as though results contains a Unicode string that was incorrectly decoded from a byte string coming from the database. I.e. when you read the data from the database, it decoded the byte string as Latin-1 rather than the UTF-8 it really is.\nSo if you fix the decoding of the database contents, then you sho...
[ 1, 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0007168440_mysql_python.txt
Q: PyDev not capturing unittest.TextTestRunner output? The PyDev PyUnit perspective correctly displays the output of my unit tests when I run them as "Python unit-test" from the module they live in with this basic usage pattern: import unittest class MyTest(unittest.TestCase): def test_something(self): p...
PyDev not capturing unittest.TextTestRunner output?
The PyDev PyUnit perspective correctly displays the output of my unit tests when I run them as "Python unit-test" from the module they live in with this basic usage pattern: import unittest class MyTest(unittest.TestCase): def test_something(self): pass if __name__ == '__main__': unittest.main() Howe...
[ "PyDev will not run your __main__, it'll collect the classes itself, so, you need to have your classes loaded in the module for it to find them (and do a run as > Python Unittest, or even use the Ctrl+F9 shortcut directly -- it won't show classes in that case, but pressing Enter directly after the Ctrl+F9 should wo...
[ 1 ]
[]
[]
[ "pydev", "python" ]
stackoverflow_0007166321_pydev_python.txt
Q: Python to "Convert" YAML into XML 1. Background We have a application that depends on several XML configuration files. The XML files define things like connection settings, polling frequencies, multiple user accounts (using XSD nested types/sequences) etc. I have the XSD schema for these XML files. Small excerpt b...
Python to "Convert" YAML into XML
1. Background We have a application that depends on several XML configuration files. The XML files define things like connection settings, polling frequencies, multiple user accounts (using XSD nested types/sequences) etc. I have the XSD schema for these XML files. Small excerpt below: <?xml version="1.0" encoding="ISO...
[ "I'd avoid the XSD, sounds like a lot of bureaucracy for little gain.\n\nCreate YAML file with same hierarchy as the XML file.\nLoad file with pyyaml\nLoop over result creating the equivalent tree in elementtree.\nWrite tree to XML file\nSend XML to system, when it complains, fix YAML and return to step 2.\n\n" ]
[ 1 ]
[]
[]
[ "python", "xml", "yaml" ]
stackoverflow_0005467377_python_xml_yaml.txt
Q: How To Think Like A Computer Scientist (Chapter 9): I don't understand the following I'm finding difficulting what exactly the doctest in the following code is looking for in the function. Can someone make it more clear for me, please? Question 14: Write functions row_times_column and matrix_mult: def row_times_...
How To Think Like A Computer Scientist (Chapter 9): I don't understand the following
I'm finding difficulting what exactly the doctest in the following code is looking for in the function. Can someone make it more clear for me, please? Question 14: Write functions row_times_column and matrix_mult: def row_times_column(m1, row, m2, column): """ >>> row_times_column([[1, 2], [3, 4]], 0, [[5...
[ "Its asking you to implement some matrix multiplication methods.\nIn the first one, given a matrix, multiply the row of m1 x the column of m2. The first one given is:\n1 2 times 5 6\n3 4 7 8\n\nbut we only want row 0 times col 0, so it would be\n[1 2] x 5 \n 7\n\n= 5+14 = 19. And so on for the ...
[ 3, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007168971_python.txt
Q: AES implementation on Python, Windows I've experienced some trouble encrypting and decrypting data between the server and client application I'm developing. I'm using AES implementation using a script that can be downloaded here at birth-online.de. The implementation is working just fine when I'm trying to encode...
AES implementation on Python, Windows
I've experienced some trouble encrypting and decrypting data between the server and client application I'm developing. I'm using AES implementation using a script that can be downloaded here at birth-online.de. The implementation is working just fine when I'm trying to encode or decode data on my Ubuntu 10.04 Server. ...
[ "I would try using PyCrypto, I use it in a current project of mine and it has worked very well. You can learn more about it below:\nhttps://www.dlitz.net/software/pycrypto/\n", "I don't know the whole AES.py but a first look at your error says that this package is not ready for Python 3.\nThe problem seems to be ...
[ 2, 0 ]
[]
[]
[ "aes", "encryption", "exception", "python", "python_3.x" ]
stackoverflow_0007165916_aes_encryption_exception_python_python_3.x.txt
Q: pymongo + gevent: throw me a banana and just monkey_patch? Quickie here that needs more domain expertise on pymongo than I have right now: Are the "right" parts of the pymongo driver written in python for me to call gevent monkey_patch() and successfully alter pymongo's blocking behavior on r/w within gevent "asy...
pymongo + gevent: throw me a banana and just monkey_patch?
Quickie here that needs more domain expertise on pymongo than I have right now: Are the "right" parts of the pymongo driver written in python for me to call gevent monkey_patch() and successfully alter pymongo's blocking behavior on r/w within gevent "asynchronous" greenlets? If this will require a little more leg w...
[ "I have used PyMongo with Gevent and here are a few things you need to watch out for:\n\nInstantiate only one pymongo.Connection object, preferrably as a global or module-level variable. This is important because Connection has within itself a pool!\nMonkey patch everything, or at least BOTH socket and threading. D...
[ 19, 2 ]
[]
[]
[ "gevent", "mongodb", "monkeypatching", "pymongo", "python" ]
stackoverflow_0007166998_gevent_mongodb_monkeypatching_pymongo_python.txt
Q: URL regular expression help Using this regular espression in my urls.py file, I get only the last letter in the add_or_remove param. The url hits my view, but I am getting only d for add and e for remove. What am I doing wrong? r'(?P<add_or_remove>[add|remove])/' Thanks A: Change the square brackets to round ()...
URL regular expression help
Using this regular espression in my urls.py file, I get only the last letter in the add_or_remove param. The url hits my view, but I am getting only d for add and e for remove. What am I doing wrong? r'(?P<add_or_remove>[add|remove])/' Thanks
[ "Change the square brackets to round () brackets. The way it is now matches any of the characters a d d | r e etc...\n", "This happens because [...] matches any character from set. Just remove bracers (using bracers from (?P<>...) is usually enough):\nr'(?P<add_or_remove>add|remove)/'\n\n", "I'll admit I'm not ...
[ 1, 1, 0 ]
[]
[]
[ "django", "django_urls", "python", "regex" ]
stackoverflow_0007169332_django_django_urls_python_regex.txt
Q: How to extract Jeopardy Questions & Answers from a website? Here is the (mess) of a script I have thus far. http://pastebin.com/prpdJXsq #Jeopardy! #Goal is to create a list of lists ie. #[[Category 1, Question 1, Answer 1], [Category 1, Question 2, Answer 2]] #First iteration will just be Q import urllib.request...
How to extract Jeopardy Questions & Answers from a website?
Here is the (mess) of a script I have thus far. http://pastebin.com/prpdJXsq #Jeopardy! #Goal is to create a list of lists ie. #[[Category 1, Question 1, Answer 1], [Category 1, Question 2, Answer 2]] #First iteration will just be Q import urllib.request, re Question = [] first_game_id = 3458 last_game_id = 3713 f...
[ "I'd recommend using lxml, and take advantage of it's XPath support:\nimport lxml.html\n\ndoc = lxml.html.parse('http://www.j-archive.com/showgame.php?game_id=1')\n# get all td's with class=\"clue_text\", these are the clues\nclues = doc.xpath('//td[@class=\"clue_text\"]')\n# create a dict of clue_id, clue_text\ncl...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0007169188_python.txt
Q: Mako's analog of Django's "spaceless" tag? Is there a mechanism in Mako templates that would allow me to remove extra spaces from the template output, similar to Django's {% spaceless %} tag? A: There are some clues here, but basically it doesn't look like it's supported under Mako directly. I do want to point o...
Mako's analog of Django's "spaceless" tag?
Is there a mechanism in Mako templates that would allow me to remove extra spaces from the template output, similar to Django's {% spaceless %} tag?
[ "There are some clues here, but basically it doesn't look like it's supported under Mako directly.\nI do want to point out, however that Jinja2 does support whitespace removal via the {%- and -%} opening and closing tags. It is very easy to use under Pyramid via:\npip install pyramid_jinja2\n\nconfig.include('pyram...
[ 2 ]
[]
[]
[ "mako", "pyramid", "python" ]
stackoverflow_0007155183_mako_pyramid_python.txt
Q: Getting Enthought Python IDLE to run code when shell is restarted I'm running EPD and using IDLE for most of my coding. What I'd like to do is get IDLE to run a script to customize my environment whenever I restart the Python shell. I've tried reading all the various posts on customizing IDLE and the Python enviro...
Getting Enthought Python IDLE to run code when shell is restarted
I'm running EPD and using IDLE for most of my coding. What I'd like to do is get IDLE to run a script to customize my environment whenever I restart the Python shell. I've tried reading all the various posts on customizing IDLE and the Python environment, and I've yet to see anything that addresses this specific scenar...
[ "\nUpon startup with the -s option, IDLE will execute the file referenced by the environment variables IDLESTARTUP or PYTHONSTARTUP.\n\nCheck out: http://docs.python.org/library/idle.html#startup\nCheers,\nJohannes\n" ]
[ 1 ]
[]
[]
[ "enthought", "python", "python_idle" ]
stackoverflow_0007169248_enthought_python_python_idle.txt
Q: Is .append() time-consuming? I've been manipulating huge text files these days. Sometimes I need to delete lines. My way of doing is like below: f=open('txt','r').readlines() list=[] for line in f: if blablablabla: list.append(line) I know for large files, .readlines()is rate-limiting step, but what ab...
Is .append() time-consuming?
I've been manipulating huge text files these days. Sometimes I need to delete lines. My way of doing is like below: f=open('txt','r').readlines() list=[] for line in f: if blablablabla: list.append(line) I know for large files, .readlines()is rate-limiting step, but what about .append() step? Does append co...
[ "Why read the whole entire file in using readlines() if you're going to filter it later? Just iterate through it saving the lines you want to keep. You could reduce this down to a couple of lines using list comprehension instead:\nwith open('txt', 'r') as f:\n myList = [ line for line in f if blablablabla ]\n\...
[ 5, 2, 1, 1, 0 ]
[]
[]
[ "append", "python", "readlines" ]
stackoverflow_0007167666_append_python_readlines.txt
Q: Why is MenuBar item delayed in wxPython in Windows, while instant in OS X? Please refer to the stripped down example script below. When I run this in OS X the menubar behaves exactly like you'd expect it to. In Windows however there is a noticeable lag (~4s on my 2GHz Core 2 Duo) of the rendering of the 'Slow' me...
Why is MenuBar item delayed in wxPython in Windows, while instant in OS X?
Please refer to the stripped down example script below. When I run this in OS X the menubar behaves exactly like you'd expect it to. In Windows however there is a noticeable lag (~4s on my 2GHz Core 2 Duo) of the rendering of the 'Slow' menu item. This doesn't feel right at all, to have an application show the good ol...
[ "I posted this on the wxPython list later on, and got this reply. Nothing wrong really, just XP being XP that's all.\n" ]
[ 0 ]
[]
[]
[ "delay", "menubar", "python", "windows", "wxpython" ]
stackoverflow_0007129108_delay_menubar_python_windows_wxpython.txt
Q: Pymongo auto sort the input dictionary I am using Pymongo to access Mongo db. I want to search for all people nearby a specified location with name contains a string. For example, I want to search all people nearby [105.0133, 21.3434] and name contains 'Mark'. So I write the query like this: db.users.find({ "locat...
Pymongo auto sort the input dictionary
I am using Pymongo to access Mongo db. I want to search for all people nearby a specified location with name contains a string. For example, I want to search all people nearby [105.0133, 21.3434] and name contains 'Mark'. So I write the query like this: db.users.find({ "location.coords": { "$nearSphere": [105.0133, 21....
[ "The dictionary type is inherently orderless. From the python documentation:\n\nIt is best to think of a dictionary as an unordered set of key: value\n pairs, with the requirement that the keys are unique (within one\n dictionary).\n\nIf you want to index your dictionary in a specific order, you'll have to store ...
[ 0, 0 ]
[]
[]
[ "dictionary", "geospatial", "pymongo", "python" ]
stackoverflow_0007156010_dictionary_geospatial_pymongo_python.txt
Q: Making a window not resizable in Windows I've been working with Windows API calls so that I can get some native Windows window styles working with Tkinter. I've run into problems when I try to prevent the window from being resizable. Using root.resizable(False, False) before the window is mapped produces an effect...
Making a window not resizable in Windows
I've been working with Windows API calls so that I can get some native Windows window styles working with Tkinter. I've run into problems when I try to prevent the window from being resizable. Using root.resizable(False, False) before the window is mapped produces an effect not unlike that of the root.overrideredirect(...
[ "Here are a couple of ideas:\n\nYou can try removing the WS_THICKFRAME style:\nframe.ModifyStyle(win32con.WS_THICKFRAME, 0)\n\nAnother alternative is to handle the WM_GETMINMAXINFO message that returns the minimum and maximum width and height for a window. In your case, you would return the current width and height...
[ 3, 2 ]
[]
[]
[ "python", "pywin32", "tkinter", "winapi", "windows_7" ]
stackoverflow_0007135643_python_pywin32_tkinter_winapi_windows_7.txt
Q: Whoosh: Indexing MS documents, PDFs I want to make a document search using python. Solr was no-go as Java hosting was a constraint. So whoosh seems the obvious option. But it seems not to natively index doc or pdf files (as Solr can). What is the way to make it deirectly index these files? A: Whoosh just needs ...
Whoosh: Indexing MS documents, PDFs
I want to make a document search using python. Solr was no-go as Java hosting was a constraint. So whoosh seems the obvious option. But it seems not to natively index doc or pdf files (as Solr can). What is the way to make it deirectly index these files?
[ "Whoosh just needs the extracted text from those documents. While the Whoosh library wont do that extraction for you, there are Python libraries that will extract the text for you, like pdf miner, catdoc or antiword.\nSee these two discussions for more information:\n\nBest way to extract text from a Word doc withou...
[ 4 ]
[]
[]
[ "python", "whoosh" ]
stackoverflow_0006849582_python_whoosh.txt
Q: Moving large SQL query to NumPy I have a very large MySQL query in my web app that looks like this: query = SELECT video_tag.video_id, (sum(user_rating.rating) * video.rating_norm) as score FROM video_tag JOIN user_rating ON user_rating.item_id = video_tag.tag_id JOIN video ON video.id = video_tag.video_id W...
Moving large SQL query to NumPy
I have a very large MySQL query in my web app that looks like this: query = SELECT video_tag.video_id, (sum(user_rating.rating) * video.rating_norm) as score FROM video_tag JOIN user_rating ON user_rating.item_id = video_tag.tag_id JOIN video ON video.id = video_tag.video_id WHERE item_type = 3 AND user_id = 1 AN...
[ "What makes this exercise awkward is the single-data-type constraint for NumPy arrays. For instance, the GROUP BY operation implicitly requires (at least) one field/column of continuous values (to aggregate/sum) and one field/column to partition or group by.\nOf course, NumPy recarrays can represent a 2D array (or ...
[ 3 ]
[]
[]
[ "mysql_python", "numpy", "python" ]
stackoverflow_0007169240_mysql_python_numpy_python.txt
Q: Creating a form from an object in python Ok.. I am a noob to Python but work with PHP a lot. Basically I am trying to figure out how to take an object -- for example: {key:value,key:value} or {key:[value,value,value],key2:value2} and turn them into forms: <input name="key" value="value"> <input name="key" value=...
Creating a form from an object in python
Ok.. I am a noob to Python but work with PHP a lot. Basically I am trying to figure out how to take an object -- for example: {key:value,key:value} or {key:[value,value,value],key2:value2} and turn them into forms: <input name="key" value="value"> <input name="key" value="value"> and <input name="key[]" value="value...
[ "You can have a template with the structure of the html.\nThen you can replace #key# and #value# for the real values.\ntemplate = '<input name=\"#key#\" value=\"#value#\">'\nhtml = template\ndata = {key:value,key:value}\nfor key in data.keys():\n html = html.replace(\"#key#\", key).replace(\"#value#\", data[valu...
[ 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007170064_python.txt
Q: while loop multiple conditions Python Hello, I have the following function: def width(input,output,attr): import re input = input.strip() if re.search(attr, input): k = input.find(attr) for i in input: if i == attr[0]: j = k + len(attr)+1 whil...
while loop multiple conditions Python
Hello, I have the following function: def width(input,output,attr): import re input = input.strip() if re.search(attr, input): k = input.find(attr) for i in input: if i == attr[0]: j = k + len(attr)+1 while ((j <= len(input)) | (j != ' ') | (input...
[ "while ((j <= len(input)) | (j != ' ') | (input[j+1] != \"'\")):\n\n0) You should be using or.\n1) You should not use input as a variable name; it hides a built-in function.\n2) j is an integer, so it can never be equal to ' ', so that test is useless.\n3) j <= len(input) passes when j == len(input). The length of...
[ 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "conditional_statements", "loops", "python", "while_loop" ]
stackoverflow_0007169348_conditional_statements_loops_python_while_loop.txt
Q: How to code so the program finds multiple instances - Python I have this code: Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus', 'cheeseburger', 'binder', 'computer', 'pencil', 'school' 'artist', 'soccer', 'tennis', 'basketball', 'panda', 'zebra', 'horse', 'cereal', 'alphabet', 'u...
How to code so the program finds multiple instances - Python
I have this code: Words = ['python','candy', 'banana', 'chicken', 'pizza', 'calculus', 'cheeseburger', 'binder', 'computer', 'pencil', 'school' 'artist', 'soccer', 'tennis', 'basketball', 'panda', 'zebra', 'horse', 'cereal', 'alphabet', 'understand'] number = raw_input('Enter a 1 through 20: ') x = list...
[ "A simple solution would be to replace the found letters with something else, so they can't be found twice. You could grab all the indexes of a given letter using a list comprehension:\nif letter in find:\n # use a list comprehension to get the index of all occurrences of a given letter\n indexes = [i for i, ...
[ 1, 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007169254_python.txt
Q: Python 2.5 and Tskill I had the tskill operation working fine through a python script when using Python 2.7 but when I switched to 2.5 this code fails. import os import time import win32com.client os.startfile('cmd') shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('Administrator:C:\Windows\Syst...
Python 2.5 and Tskill
I had the tskill operation working fine through a python script when using Python 2.7 but when I switched to 2.5 this code fails. import os import time import win32com.client os.startfile('cmd') shell = win32com.client.Dispatch("WScript.Shell") shell.AppActivate('Administrator:C:\Windows\System32\cmd.exe') time.sleep(2...
[ "I don't have tskill on my system, but I think it's similar to taskkill /F /FI \"IMAGENAME eq java*\". Anyway, here's how to call a normal console application in the background (i.e. a hidden window) using the subprocess module (tested in Python 2.5.2, but using taskkill instead):\nimport subprocess\n\ndef tskill(...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0007170159_python.txt
Q: How to make process wide editable variable (storage) in django? I want create project wide accessible storage for project/application settings. What i want to achieve: - Each app has it's own app specific settings stored in db - When you spawn django wsgi process each settings are stored in memory storage and are...
How to make process wide editable variable (storage) in django?
I want create project wide accessible storage for project/application settings. What i want to achieve: - Each app has it's own app specific settings stored in db - When you spawn django wsgi process each settings are stored in memory storage and are available project wide - Whenever you change any setting value in db...
[ "Before giving any specific advice to you, you need to be aware of the limitations of these systems.\nISSUES\n\nArchitectural Differences between Django and PHP/other popular language.\nPHP re-reads and re-evaluates the entire code tree every time a page is accessed. This allows PHP to re-read settings from DB/cach...
[ 0 ]
[]
[]
[ "data_storage", "django", "python" ]
stackoverflow_0007169852_data_storage_django_python.txt
Q: How can I send data from a python script to Matplotlib? I am fairly new to programing and have a question regarding matplotlib. I wrote a python script that reads in data from the outfile of another program then prints out the data from one column. f = open( '/home/student/AstroSimulation/out.0001.z0.753.AHF_halo...
How can I send data from a python script to Matplotlib?
I am fairly new to programing and have a question regarding matplotlib. I wrote a python script that reads in data from the outfile of another program then prints out the data from one column. f = open( '/home/student/AstroSimulation/out.0001.z0.753.AHF_halos','r') for line in f: if line != ' ': line = lin...
[ "You will call matplotlib from within your script, so matplotlib will not \"get data from a script\" as such. You send it into matplotlib.\nYou will need to save the masses outside the loop however, but then, it's just a call to the plot() and show() functions in it's most basic form:\nimport matplotlib.pyplot as p...
[ 2, 1 ]
[]
[]
[ "ipython", "matplotlib", "python" ]
stackoverflow_0007170661_ipython_matplotlib_python.txt
Q: Stream stdio to a website (like buildbot) So I am trying to work in a stdio stream for a webapp similar to Buildbot. Does anyone know how Buildbot deals with stdio? It is streaming (so it seems) and that would be exactly what I need for this program. Does anyone know how to do this? Any help would be greatly app...
Stream stdio to a website (like buildbot)
So I am trying to work in a stdio stream for a webapp similar to Buildbot. Does anyone know how Buildbot deals with stdio? It is streaming (so it seems) and that would be exactly what I need for this program. Does anyone know how to do this? Any help would be greatly appreciated. I am using Python with Django by the...
[ "Buildbot uses Twisted, which has a rather different programming style from Django.\nI'd say you'd have to write a service in Twisted to do what you're after. Communicate with it from Django and have it do the streaming part you need.\n(In Django, as most web apps, you have one thread/call per request that blocks o...
[ 0, 0 ]
[]
[]
[ "django", "python", "stdio" ]
stackoverflow_0007166638_django_python_stdio.txt
Q: What can cause delay in my worker thread Queue.get()? Note: This is closely related to my other topic here and here, but is an independent question and you needn't read them if you're not interested to.. I have some unexpected delays in processing items from the queue. It seems to be related to the matplotlib GUI...
What can cause delay in my worker thread Queue.get()?
Note: This is closely related to my other topic here and here, but is an independent question and you needn't read them if you're not interested to.. I have some unexpected delays in processing items from the queue. It seems to be related to the matplotlib GUI thread, because I can make the delay arbitrarily long by a...
[ "I don't really know why, but the problem seems to go away if you declare matplotlib.use(backend) before importing pyplot:\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\nIn an interactive session, the problem can also be avoided by turning on interactive mode:\nimport matplotlib.pyp...
[ 1 ]
[]
[]
[ "event_handling", "matplotlib", "multithreading", "python", "queue" ]
stackoverflow_0007170631_event_handling_matplotlib_multithreading_python_queue.txt
Q: Getting Number of Comments of Online news article with Python BeautifulSoup I'm using the following code: import urllib from BeautifulSoup import BeautifulSoup import re comment_url = http://community.nytimes.com/comments/www.nytimes.com/2011/08/24/world/africa/24libya.html response_new = urllib.urlopen(comment...
Getting Number of Comments of Online news article with Python BeautifulSoup
I'm using the following code: import urllib from BeautifulSoup import BeautifulSoup import re comment_url = http://community.nytimes.com/comments/www.nytimes.com/2011/08/24/world/africa/24libya.html response_new = urllib.urlopen(comment_url) html_new = response.read() soup_new = BeautifulSoup(html_new) tags = soup_n...
[ "Use the attrs keyword parameter explicitly:\ntags = soup_new.findAll('h3', attrs={'class': 'share'})\n\nThe call signature for findAll is:\nsoup_new.findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs)\n\nso when you omit attrs=, you are assigning the second argument, {'class': 'shar...
[ 1 ]
[]
[]
[ "python", "screen_scraping", "web_scraping" ]
stackoverflow_0007171759_python_screen_scraping_web_scraping.txt
Q: How to print list of dict in django? I have list of dict named menu_dict_list: [{'date': datetime.datetime(2011, 8, 15, 0, 0), 'Popcorn': 5, 'Coke': 5, 'Chips': 0, 'Burger': 3}, {'date': datetime.datetime(2011, 8, 10, 0, 0), 'Popcorn': 4, 'Coke': 4, 'Chips': 0, 'Burger': 0}] I had followed this approach: ...
How to print list of dict in django?
I have list of dict named menu_dict_list: [{'date': datetime.datetime(2011, 8, 15, 0, 0), 'Popcorn': 5, 'Coke': 5, 'Chips': 0, 'Burger': 3}, {'date': datetime.datetime(2011, 8, 10, 0, 0), 'Popcorn': 4, 'Coke': 4, 'Chips': 0, 'Burger': 0}] I had followed this approach: **{% for menu_dict in menu_dict_list %} <...
[ "You have to use the .items method of the dict:\n{% for menu_dict in menu_dict_list %}\n <tr>\n {% for key,value in menu_dict.items %}\n <td>{{value}}</td>\n {% endfor %}\n </tr>\n{% endfor %}\n\nSee this\n", "if your problem is to iterate on the ...
[ 2, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007171955_django_python.txt
Q: Override python logging for test efficiency In many cases unit-tests are significantly slowed down by the use of python's logging package. Assuming logging isn't essential to the test, how would you cleanly override logging per-test, so that log commands would be effectively skipped. Assume the use of multiple log...
Override python logging for test efficiency
In many cases unit-tests are significantly slowed down by the use of python's logging package. Assuming logging isn't essential to the test, how would you cleanly override logging per-test, so that log commands would be effectively skipped. Assume the use of multiple loggers such as in: logger1 = logging.getLogger('log...
[ "Option 1:\nLogging can be disabled by calling\nlogging.disable(logging.CRITICAL)\n\nand turned back on with\nlogging.disable(logging.NOTSET)\n\nHowever, even after disabling logging, a logging statement such as logger.info would still cause Python to do a few attribute lookups and function calls before reaching th...
[ 12 ]
[]
[]
[ "logging", "performance", "python", "unit_testing" ]
stackoverflow_0007172290_logging_performance_python_unit_testing.txt
Q: import inside or outside function Possible Duplicate: Should Python import statements always be at the top of a module? In a very simple one-file python program like # ------------------------ # place 1 # import something def foo(): # place 2 # import something return something.foo() def bar(f): ...
import inside or outside function
Possible Duplicate: Should Python import statements always be at the top of a module? In a very simple one-file python program like # ------------------------ # place 1 # import something def foo(): # place 2 # import something return something.foo() def bar(f): ... def baz(): f = foo() bar...
[ "PEP 8 specifies that:\n\nImports are always put at the top of the file, just after any module\n comments and docstrings, and before module globals and constants.\nImports should be grouped in the following order:\n\nstandard library imports\nrelated third party imports\nlocal application/library specific imports\...
[ 12, 5 ]
[]
[]
[ "python" ]
stackoverflow_0007172585_python.txt
Q: python incorporate png/ico to exe and use it in application I am zsing py2exe to compile exe files. I would like to incorporate png and icon file into exe and then use it during program run (to show it in about dialog and system tray). How can I do it? For example now I use self.staticon.set_from_file(os.path.join...
python incorporate png/ico to exe and use it in application
I am zsing py2exe to compile exe files. I would like to incorporate png and icon file into exe and then use it during program run (to show it in about dialog and system tray). How can I do it? For example now I use self.staticon.set_from_file(os.path.join(module_path(), "icon.ico")) but I would like to prevent user fro...
[ "http://www.py2exe.org/index.cgi/CustomIcons\n", "Another approach is to build an installer with Innosetup ( http://www.jrsoftware.org/isinfo.php) , where you can specify icons for your software and icons for files depending on your software. In the end you have to modify the registry and Innosetup does this for ...
[ 0, 0 ]
[]
[]
[ "exe", "icons", "image", "png", "python" ]
stackoverflow_0007163261_exe_icons_image_png_python.txt
Q: Right-Click on a PyGTK Hbox in an Expander I've got a gtk.Expander object, containing in its label a gtk.HBox, which packed a gtk.Image and a gtk.Label. I want to launch a Webbrowser when the HBox is right-clicked. Here is my code: def launchBrowser(widget, host, event): print event print host if event...
Right-Click on a PyGTK Hbox in an Expander
I've got a gtk.Expander object, containing in its label a gtk.HBox, which packed a gtk.Image and a gtk.Label. I want to launch a Webbrowser when the HBox is right-clicked. Here is my code: def launchBrowser(widget, host, event): print event print host if event.type == gtk.gdk.BUTTON_PRESS: if event....
[]
[]
[ "Small change in your code.\nAdd \"button-press-event\" on Expander widget instead of Label widget\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\nclass MainWindow(gtk.Window):\n def __init__(self):\n gtk.Window.__init__(self)\n self.set_default_size(300, 300)\n self.addServer()\n\n def launchBro...
[ -1 ]
[ "events", "expander", "hbox", "pygtk", "python" ]
stackoverflow_0007160543_events_expander_hbox_pygtk_python.txt
Q: Python regex matching multiple lines I'm trying to get the contents of a <ul> tag from a webpage in python. I used the following code: matchResult = re.search(r'<ul\s*content="MSL">(.*)</ul>', queryResult, re.MULTILINE) This does not work. However if I remove the line breaks by using queryResult = queryResult.rep...
Python regex matching multiple lines
I'm trying to get the contents of a <ul> tag from a webpage in python. I used the following code: matchResult = re.search(r'<ul\s*content="MSL">(.*)</ul>', queryResult, re.MULTILINE) This does not work. However if I remove the line breaks by using queryResult = queryResult.replace('\r','').replace('\n','') It works. T...
[ "Include the re.DOTALL option as well, that will allow the . character to match newlines.\n" ]
[ 5 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007173171_python_regex.txt
Q: Dynamically importing a module and instantiating a class in Python My question is similar to this one, though I'd like to go on step further. I'm parsing a configuration file which calls a number of actions (with parameters) by name. For example: "on_click": "action1", "args": {"rate": 1.5} Actions are python cl...
Dynamically importing a module and instantiating a class in Python
My question is similar to this one, though I'd like to go on step further. I'm parsing a configuration file which calls a number of actions (with parameters) by name. For example: "on_click": "action1", "args": {"rate": 1.5} Actions are python classes, inheriting from a base Action class, and can take named arguments...
[ "If everything in your module are classes that you should instanciate, try something like this : \nfor a in actions:\ntry:\n module = __import__(\"actions.%s\" % a, globals(), locals(), fromlist=[\"*\"])\n # What goes here?\n # let's try to grab and instanciate objects\n for item_name in dir(module):\n ...
[ 2 ]
[]
[]
[ "import", "parsing", "python" ]
stackoverflow_0007173202_import_parsing_python.txt
Q: JSON serialize Django Queryset with values being called. Is there anything wrong with my approach? Here is the problem: Django's serializer doesn't support dictionaries and simplejson doesn't support Django Querysets. See JSON Serializing Django Models with simplejson I was wondering if there is anything wrong wit...
JSON serialize Django Queryset with values being called. Is there anything wrong with my approach?
Here is the problem: Django's serializer doesn't support dictionaries and simplejson doesn't support Django Querysets. See JSON Serializing Django Models with simplejson I was wondering if there is anything wrong with my solution. I have something like: people = People.objects.all().values('name', 'id') json.dumps(list...
[ "Your solution is totally valid and very clean in my own opinion.\nIf you need a list of lists (instead of a list of dictionaries) you can use too:\nfrom django.utils import simplejson\n\npeople = People.objects.all().values_list('name', 'id')\nsimplejson.dumps(list(people))\n\nSometimes when the json output is ver...
[ 13 ]
[]
[]
[ "django", "json", "python" ]
stackoverflow_0007047297_django_json_python.txt
Q: python egg cache I have 3 projects hosted in amazon bitnami ec2 and my none of project is running. When I check my logs it showing the error as follows: The Python egg cache directory is currently set to: /opt/bitnami/.tmp Perhaps your account does not have write access to this directory? You can change the c...
python egg cache
I have 3 projects hosted in amazon bitnami ec2 and my none of project is running. When I check my logs it showing the error as follows: The Python egg cache directory is currently set to: /opt/bitnami/.tmp Perhaps your account does not have write access to this directory? You can change the cache directory by sett...
[ "You just need to give permissions to the daemon user in that folder.\nsudo chown -R daemon.daemon /opt/bitnami/.tmp\nsudo chmod -R 700 /opt/bitnami/.tmp\n\nAlso if you are using a version of the BitNami Trac Stack that already uses mod_wsgi (0.12.2-1 or later) you can configure the PYTHON_EGG_CACHE to point to a d...
[ 6 ]
[]
[]
[ "caching", "egg", "python" ]
stackoverflow_0007172617_caching_egg_python.txt
Q: CFLAGS and gcc at configure not passed in makefile I am trying to compile python 32 bit on OSX. In order to do so, I want to specify -m32, so I dutifully specified CFLAGS='-m32' LDFLAGS='-m32' ./configure The configure executes correctly, but when I invoke make, the gcc execution has no trace of the -m32 flag. I...
CFLAGS and gcc at configure not passed in makefile
I am trying to compile python 32 bit on OSX. In order to do so, I want to specify -m32, so I dutifully specified CFLAGS='-m32' LDFLAGS='-m32' ./configure The configure executes correctly, but when I invoke make, the gcc execution has no trace of the -m32 flag. In order to have it, I had to do a more aggressive approa...
[ "Ok, I can reproduce that with Python-2.6. That seems to be a bug in that version, and is fixed in a newer one.\nStill, I can tell you that it is common for various packages to override or filter CFLAGS of values considered unsafe and so on. This often covers -m32 as well.\nMoreover, many packages simply ignore LDF...
[ 2 ]
[]
[]
[ "makefile", "python" ]
stackoverflow_0007173872_makefile_python.txt
Q: uWSGI "timeout waiting for header" Error I'm using uwsgi-0.9.8.4 under Ubuntu 10.04 (32bit), here's the uwsgi section in my Pyramid application (which works fine with paster) .ini file -- [uwsgi] socket = 127.0.0.1:6543 master = true processes = 1 pythonpath = /home/jerry/virtualenv/lib/python2.6/site-packages/*.e...
uWSGI "timeout waiting for header" Error
I'm using uwsgi-0.9.8.4 under Ubuntu 10.04 (32bit), here's the uwsgi section in my Pyramid application (which works fine with paster) .ini file -- [uwsgi] socket = 127.0.0.1:6543 master = true processes = 1 pythonpath = /home/jerry/virtualenv/lib/python2.6/site-packages/*.egg pythonpath = /home/jerry/myapp uwsgi runs ...
[ "uWSGI by default speaks the uwsgi (all lowercase) protocol, not the http one. So you cannot connect to it via browser. Add --protocol=http to let it speak http (slower obviously)\n" ]
[ 4 ]
[]
[]
[ "pyramid", "python", "uwsgi", "webserver", "wsgi" ]
stackoverflow_0007170876_pyramid_python_uwsgi_webserver_wsgi.txt
Q: Using os.forkpty() to create a pseudo-terminal to ssh to a remote server and communicate with it I'm trying to write a python script that can ssh into remote server and can execute simple commands like ls,cd from the python client. However, I'm not able to read the output from the pseudo-terminal after successfull...
Using os.forkpty() to create a pseudo-terminal to ssh to a remote server and communicate with it
I'm trying to write a python script that can ssh into remote server and can execute simple commands like ls,cd from the python client. However, I'm not able to read the output from the pseudo-terminal after successfully ssh'ing into the server. Could anyone please help me here so that I could execute some commands on t...
[ "I'd suggest trying the module pexpect, which is built exactly for this sort of thing (interfacing with other applications via pseudo-TTYs), or Fabric, which is built for this sort of thing more abstractly (automating system administration tasks on remote servers using SSH).\npexpect: http://pypi.python.org/pypi/pe...
[ 3, 2 ]
[]
[]
[ "fork", "python", "ssh", "terminal" ]
stackoverflow_0007173878_fork_python_ssh_terminal.txt
Q: rtorrent's session info in Python I'd like to get some basic info about rtorrent's torrents. I assume the only way is to read files from rtorrent's session directory. How would I do that in Python? Which encoding should I use? A: Rtorrent has an XML-RPC interface which you can use with pythons xmlrpclib.
rtorrent's session info in Python
I'd like to get some basic info about rtorrent's torrents. I assume the only way is to read files from rtorrent's session directory. How would I do that in Python? Which encoding should I use?
[ "Rtorrent has an XML-RPC interface which you can use with pythons xmlrpclib.\n" ]
[ 0 ]
[]
[]
[ "bittorrent", "python" ]
stackoverflow_0007173616_bittorrent_python.txt
Q: python memory question Say I have a text file of 1 MB. Considering the following the example: class A: def __init__(self, file): self.file = file class B: def __init__(self, file): self.a = A(file) f = open(path, 'r') file = f.read() f.close() x = B(file) Am I creating two files and t...
python memory question
Say I have a text file of 1 MB. Considering the following the example: class A: def __init__(self, file): self.file = file class B: def __init__(self, file): self.a = A(file) f = open(path, 'r') file = f.read() f.close() x = B(file) Am I creating two files and therefore wasting two megabyt...
[ "Python passes arguments by reference, so essentially the 'string' you pass into B() is actually a pointer (a memory address) to the actual string. If you look at the objects at each point in execution of your example script, you'll see that they are all the same.\nFor example, this version prints a repr() of the p...
[ 4, 3, 1, 1, 1, 1 ]
[]
[]
[ "memory", "python" ]
stackoverflow_0007173008_memory_python.txt
Q: Exception binding variables with cx_Oracle in python Okay, so I'm connected to an oracle database in python 2.7 and cx_Oracle 5.1 compiled against the instant client 11.2. I've got a cursor to the database and running SQL is not an issue, except this: cursor.execute('ALTER TRIGGER :schema_trigger_name DISABLE...
Exception binding variables with cx_Oracle in python
Okay, so I'm connected to an oracle database in python 2.7 and cx_Oracle 5.1 compiled against the instant client 11.2. I've got a cursor to the database and running SQL is not an issue, except this: cursor.execute('ALTER TRIGGER :schema_trigger_name DISABLE', schema_trigger_name='test.test_tr...
[ "In your example test.test_trigger is not a variable but an object. You can only bind variables (that can be replaced by a value).\nThe query you are trying to run would be logically equivalent to:\nALTER TRIGGER 'test.test_trigger' DISABLE\n\nBinding in this case won't work, you will have to build the query dynami...
[ 2, 0 ]
[]
[]
[ "cx_oracle", "oracle", "python" ]
stackoverflow_0007174741_cx_oracle_oracle_python.txt
Q: Python Script for converting two columns into a 68 x 150 matrix I am a PhD student with a a data wrangling problem. I have two columns of data in a text file that follow this format: Site Species A01 ACRB A01 TBL A02 TBL A03 GRF ... I need to count how many of each species type (i.e. ACRB) there are ...
Python Script for converting two columns into a 68 x 150 matrix
I am a PhD student with a a data wrangling problem. I have two columns of data in a text file that follow this format: Site Species A01 ACRB A01 TBL A02 TBL A03 GRF ... I need to count how many of each species type (i.e. ACRB) there are for each Site (i.e. A01) and produce a matrix with about 60 sites and...
[ "Here is a way to do it with Python2.7\nfrom collections import Counter\nwith open(\"in.txt\") as f:\n next(f) # do this to skip the first row of the file\n c = Counter(tuple(row.split()) for row in f if not row.isspace())\n\nsites = sorted(set(x[0] for x in c))\nspecies = sorted(set(x[1] for x in c))\n\npri...
[ 4, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007173536_python.txt
Q: Python crashes when trying to perform buffer using OSGEO OGR I'm trying to run a simple script to manually create some geometry and then perform a buffer on said geometry. However, python will completely crash whenever I try to perform a Buffer operation. >>> from osgeo import ogr >>> point = ogr.Geometry(ogr.wkb...
Python crashes when trying to perform buffer using OSGEO OGR
I'm trying to run a simple script to manually create some geometry and then perform a buffer on said geometry. However, python will completely crash whenever I try to perform a Buffer operation. >>> from osgeo import ogr >>> point = ogr.Geometry(ogr.wkbPoint) >>> point.AddPoint(1,1) >>> point.Buffer(1) >>> ==========...
[ "Your code should read\n>>> from osgeo import ogr\n>>> point = ogr.Geometry(ogr.wkbPoint)\n>>> point.SetPoint(0, 1, 1) # index, X, Y\n>>> point.Buffer(1)\n\n", "I think you need a new object to hold the buffer geometry. Like:\nbuffer = point.Buffer(1)\n\nBut it is strange that it crashed completely. No error mess...
[ 1, 0 ]
[]
[]
[ "gdal", "gis", "ogr", "osgeo", "python" ]
stackoverflow_0005860831_gdal_gis_ogr_osgeo_python.txt
Q: Counting successive occurrences of numbers satisfying certain conditions in python I have a specific data set that reads like array([ 2.1, 3. , 179.1, 1.9, 2.6, 425.8, 1.7, 3.1, 4. , 144. , 2.2, 2.3, 5.3, 135.5, 2. , 2.7, .....])] Here I want to count the succe...
Counting successive occurrences of numbers satisfying certain conditions in python
I have a specific data set that reads like array([ 2.1, 3. , 179.1, 1.9, 2.6, 425.8, 1.7, 3.1, 4. , 144. , 2.2, 2.3, 5.3, 135.5, 2. , 2.7, .....])] Here I want to count the successive occurrences of numbers below 6 and save them in specific counters. For example, in...
[ "Here's my solution, based on my understanding of your problem:\nfrom collections import defaultdict\n\ndef countSuccessive(data):\n counters = defaultdict(int)\n count = 0\n\n for i in data:\n if i < 6:\n count += 1\n elif count != 0:\n counters[count] += 1\n ...
[ 3, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007174813_python.txt
Q: Python - Web scraping pages using Comet and HTTP streaming I have to extract the data from fxstreet I extracted the HTML code with firebug and it seems like the webpage is using Comet and HTTP streaming. I would like to fill in a dictionary every second with the data without having to refresh the page. I did it wi...
Python - Web scraping pages using Comet and HTTP streaming
I have to extract the data from fxstreet I extracted the HTML code with firebug and it seems like the webpage is using Comet and HTTP streaming. I would like to fill in a dictionary every second with the data without having to refresh the page. I did it with urllib.urlopen but I am obliged to do a query every second. S...
[ "You'll probably want to use gevent, Tornado, or Twisted to write an asynchronous HTTP client to consume your service. There have been quite a few projects built for working with the Twitter Streaming API that you might look to for inspiration:\n\nhttps://github.com/fiorix/twisted-twitter-stream - twisted\nhttps://...
[ 2, 0, 0 ]
[]
[]
[ "comet", "python", "streaming" ]
stackoverflow_0007175376_comet_python_streaming.txt
Q: problem in python relative import I am running the following project on windows with the following directory structure.. Project\Src\Lib\General\Module_lib.py Project\Src\executables\example.py Now , I want to import Module_lib.py in example.py.. Please help me how to solve this? content of example.py : from ...
problem in python relative import
I am running the following project on windows with the following directory structure.. Project\Src\Lib\General\Module_lib.py Project\Src\executables\example.py Now , I want to import Module_lib.py in example.py.. Please help me how to solve this? content of example.py : from ..lib.general.Module_lib import Module_...
[ "Add Project\\Src\\Lib\\General to your PYTHON_PATH so the runtime can find it. That's the only real convenient solution I can think of. \nYou can find a way of adding your python path here:\nhttps://stackoverflow.com/questions/6318156\nDoing it in script is also possible:\nimport sys\nsys.path.append(os.path.dirna...
[ 0, 0 ]
[]
[]
[ "package", "python" ]
stackoverflow_0007175236_package_python.txt
Q: How do you escape tags in django templates? As I know if I put {{ var_name }} in django template, it will be parsed as an variable. What should I write if I want the string "{{ var_name }}" displayed in HTML file (not {{ var_name }})? I'm not quite sure how to describe this question, so I have no idea what key wo...
How do you escape tags in django templates?
As I know if I put {{ var_name }} in django template, it will be parsed as an variable. What should I write if I want the string "{{ var_name }}" displayed in HTML file (not {{ var_name }})? I'm not quite sure how to describe this question, so I have no idea what key word to search in Google. Thank you.
[ "If I understand you correctly, you want to output text including literal braces.\nThis is done using the templatetag template tag.\nFor example, in your case, you will want to put:\n{% templatetag openvariable %} var_name {% templatetag closevariable %}\n\n", "What you want to do is called escaping.\nYou can sub...
[ 4, 2, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0007175567_django_django_templates_python.txt
Q: Background process in Python I need to create a background process that will wait for incoming commands and perfom them. Here's the code: instance_tuple.popen = subprocess.Popen(['python',\ os.path.join(config['scripts_dir'],\ 'instance_script...
Background process in Python
I need to create a background process that will wait for incoming commands and perfom them. Here's the code: instance_tuple.popen = subprocess.Popen(['python',\ os.path.join(config['scripts_dir'],\ 'instance_script.py')],\ ...
[ "I like to use zeromq for this. I setup a server using the zmq.PULL socket which listens for clients sending messages using the zmq.PUSH socket. Really easy to work with:\nimport zmq\n\ndef client(msg)\n context = zmq.Context()\n client = context.socket(zmq.PUSH)\n client.connect('tcp://127.0.0.1:9999')\n ...
[ 5, 0, 0, 0 ]
[]
[]
[ "multiprocessing", "popen", "python", "subprocess" ]
stackoverflow_0007174478_multiprocessing_popen_python_subprocess.txt
Q: Partial String Formatting in Python Logging Formatters I'm looking for a way to perform partial string formatting in Python logging formatters. When trying to define a formatter the following way: formatter = logging.Formatter('[num-%d] %(levelname)s %(message)s' % (num,)) I will get a TypeError with "format requi...
Partial String Formatting in Python Logging Formatters
I'm looking for a way to perform partial string formatting in Python logging formatters. When trying to define a formatter the following way: formatter = logging.Formatter('[num-%d] %(levelname)s %(message)s' % (num,)) I will get a TypeError with "format requires a mapping" which is reasonable as the interpreter couldn...
[ "Try this:\nformatter = logging.Formatter('[num-%d] %%(levelname)s %%(message)s' % (num,))\n\nYou have to give the Formatter method your string with %(...)s fields. The %% will interpret into % and therefore can be used.\n" ]
[ 5 ]
[]
[]
[ "formatter", "logging", "mapping", "python", "string" ]
stackoverflow_0007175911_formatter_logging_mapping_python_string.txt
Q: Tuples partial match I have a tuple of tuples and a tuple. I'm interested to know which elements of the first tuple match the second tuple (if any), considering partial matches too. This is a filter function to demonstrate what I mean. def f(repo): pattern = (None, None, '1.3') for idx, item in enumerate(p...
Tuples partial match
I have a tuple of tuples and a tuple. I'm interested to know which elements of the first tuple match the second tuple (if any), considering partial matches too. This is a filter function to demonstrate what I mean. def f(repo): pattern = (None, None, '1.3') for idx, item in enumerate(pattern): if item !...
[ "Why don't you use the built-in filter:\n>>> filter(lambda x: x[2] == '1.3', repo)\n<<< (('framework', 'django', '1.3'), ('cms', 'fein', '1.3'))\n\n...or a list comprehension:\n>>> [x for x in repo if x[2] == '1.3']\n<<< [('framework', 'django', '1.3'), ('cms', 'fein', '1.3')]\n\nIf you wanted to wrap it up into a ...
[ 7, 4, 2, 1, 1, 1 ]
[]
[]
[ "algorithm", "matching", "python", "tuples" ]
stackoverflow_0007175736_algorithm_matching_python_tuples.txt
Q: Python - How many Default Modules loaded I need to know, When i run My python over terminal by default how many module are loaded with it which i do not have to import to use, which modules i can directly use ?? My System Env is Ubuntu 11.04 Regards A: Any part of standard library which is not labeled as built-...
Python - How many Default Modules loaded
I need to know, When i run My python over terminal by default how many module are loaded with it which i do not have to import to use, which modules i can directly use ?? My System Env is Ubuntu 11.04 Regards
[ "Any part of standard library which is not labeled as built-in (e.g. file class, set class, locals function, etc.) resides in some external module that should be imported prior to usage. This includes seemingly \"basic\" modules too, such as sys or math.\nIf you are unsure about particular function, look up the bui...
[ 2, 2, 0 ]
[]
[]
[ "linux", "module", "python" ]
stackoverflow_0007175909_linux_module_python.txt
Q: python: permanent execution program date dependant I wrote a script.py collecting data from the web from monday to friday. The script is usually executed from another script in the main function. I want it to close on friday and open monday automatically, and run from monday to friday. At the moment I am obliged t...
python: permanent execution program date dependant
I wrote a script.py collecting data from the web from monday to friday. The script is usually executed from another script in the main function. I want it to close on friday and open monday automatically, and run from monday to friday. At the moment I am obliged to run it manually every monday. I wrote some code to sto...
[ "Do you have any option to automatically schedule the program to start on mondays, with cron or windows task scheduler?\nAlternatley, you could write a separate program that runs permanently and controlls the startup and/or shutdown of the script.py.\n", "For your reformulated question, theres nothing wrong with ...
[ 1, 0 ]
[]
[]
[ "python", "sys" ]
stackoverflow_0007175856_python_sys.txt
Q: python2.6.6 installation problem installing python2.6 after running ./configure it runs with no errors but after running gmake i get this error * WARNING: renaming "_curses" since importing it failed: ld.so.1: python: fatal: relocation error: file build/lib.solaris-2.10-i86pc-2.6/_curses.so: symbol newscr: referen...
python2.6.6 installation problem
installing python2.6 after running ./configure it runs with no errors but after running gmake i get this error * WARNING: renaming "_curses" since importing it failed: ld.so.1: python: fatal: relocation error: file build/lib.solaris-2.10-i86pc-2.6/_curses.so: symbol newscr: referenced symbol not found building '_curses...
[ "First and foremost, make sure you have the newest version of gmake/make. I had a nasty problem using an older version. It was similar to this, which is why I am suggesting it. \nIf you don't have it, install gmake and redo the python installation (./configure, make, make install). Hope that helps! \n" ]
[ 0 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0007176218_python_unix.txt
Q: Django sub-directory views and import all files from __init__.py Technically not a django question, more a python question. In urls.py I've got the following: urlpatterns = patterns('locate.views', url(r'^', 'index.index'), ) And a directory structure like this: locate/ views/ __init__.py index.py ...
Django sub-directory views and import all files from __init__.py
Technically not a django question, more a python question. In urls.py I've got the following: urlpatterns = patterns('locate.views', url(r'^', 'index.index'), ) And a directory structure like this: locate/ views/ __init__.py index.py # where there is "def index(request) : ...." What I would like ...
[ "I believe that importing through other files is somewhat awkward, and that all views should be imported directly - like the way you're doing now.\nHowever, you can create a views.py file and import all relevant view methods from there, the dir structure will remain the same, only you'll add a views.py file under t...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004045016_django_python.txt
Q: ABC for String? I recently discovered abstract base classes (ABCs) in collections and like their clear, systematic approach and Mixins. Now I also want to create customs strings (*), but I couldn't find an ABC for strings. There is UserString, but UserDict was discouraged!? Deriving from str itself would have no M...
ABC for String?
I recently discovered abstract base classes (ABCs) in collections and like their clear, systematic approach and Mixins. Now I also want to create customs strings (*), but I couldn't find an ABC for strings. There is UserString, but UserDict was discouraged!? Deriving from str itself would have no Mixins? How would you ...
[ "Here's a silly, but quick, example of Steven's answer. It's implemented in Python 3 (i.e. Unicode strings, super without arguments, and __getitem__ slices):\nclass MultiStr(str):\n def __new__(cls, string, multiplier=1, **kwds):\n self = super().__new__(cls, string, **kwds)\n self.multiplier = mul...
[ 4, 1 ]
[]
[]
[ "abc", "abstract_class", "python", "string" ]
stackoverflow_0007172772_abc_abstract_class_python_string.txt
Q: Get User to Input range in Python I am trying to ask the user for a range (for an array) i.e variables start, stop and increment. I am having difficulty asking for each variable without breaking up my string. So far I have this code: x=numpy.arange(input('Enter Start:'), input('Enter Stop:'),input ('Enter increme...
Get User to Input range in Python
I am trying to ask the user for a range (for an array) i.e variables start, stop and increment. I am having difficulty asking for each variable without breaking up my string. So far I have this code: x=numpy.arange(input('Enter Start:'), input('Enter Stop:'),input ('Enter increment:')) However I would like it to read...
[ ">>> start, stop, inc = raw_input('Enter start, stop, increment:').split(',')\nEnter start, stop, increment:0, 5, 2\n>>> print start, stop, inc\n0 5 2\n\nKeep in mind that those are strings, use int to convert them\n", "The user has to confirm his entry by hitting the ENTER key. input() automatically outputs th...
[ 2, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007176540_numpy_python.txt
Q: How do I add edges between two subgraphs in pydot? Does anyone know how to add an edge between two subgraphs (clusters) in pydot? callgraph = pydot.Dot(graph_type='digraph',fontname="Verdana") cluster_foo=pydot.Cluster('foo',label='foo') cluster_foo.add_node(pydot.Node('foo_method_1',label='method_1')) callgraph.a...
How do I add edges between two subgraphs in pydot?
Does anyone know how to add an edge between two subgraphs (clusters) in pydot? callgraph = pydot.Dot(graph_type='digraph',fontname="Verdana") cluster_foo=pydot.Cluster('foo',label='foo') cluster_foo.add_node(pydot.Node('foo_method_1',label='method_1')) callgraph.add_subgraph(cluster_foo) cluster_bar=pydot.Cluster('bar...
[ "\nGraphviz demands that an edge be between nodes in the 2 clusters.\nAdd graph parameter compound='true'.\nUse edge parameters lhead= and ltail=.\n\nSo your code would become:\ncallgraph = pydot.Dot(graph_type='digraph', fontname=\"Verdana\", compound='true')\n\n\ncluster_foo=pydot.Cluster('foo',label='foo')\ncall...
[ 6 ]
[]
[]
[ "edges", "graph", "graphviz", "pydot", "python" ]
stackoverflow_0006953957_edges_graph_graphviz_pydot_python.txt
Q: cherrypy jsondecoder not found I tried this example: import cherrypy class Root(object): @cherrypy.expose @cherrypy.tools.json_out() def getrange(self, limit=4): return list(range(int(limit))) cherrypy.quickstart(Root()) when I run this, I get: Traceback (most recent call last): File "D:/D...
cherrypy jsondecoder not found
I tried this example: import cherrypy class Root(object): @cherrypy.expose @cherrypy.tools.json_out() def getrange(self, limit=4): return list(range(int(limit))) cherrypy.quickstart(Root()) when I run this, I get: Traceback (most recent call last): File "D:/Dev/BaronPOS/baronpos/Server/tester.p...
[ "OK, I figured it out.\nI was using SimpleJSONRPCServer previously (http://www.freenet.org.nz/dojo/pyjson/) but decided to move to a more flexible REST compatible architecture.\nApparantly I left an artifact called json.py, which was causing this...\n" ]
[ 1 ]
[]
[]
[ "cherrypy", "python" ]
stackoverflow_0007175425_cherrypy_python.txt
Q: The underlying query of a mapped attribute If I have an sqlalchemy-mapped instance. Can I get an underlying dynamic query object corresponding to an attribute of said instance? For example: e = Employee() e.projects #how do I get a query object loaded with the underlying sql of e.projects A: I think you're desc...
The underlying query of a mapped attribute
If I have an sqlalchemy-mapped instance. Can I get an underlying dynamic query object corresponding to an attribute of said instance? For example: e = Employee() e.projects #how do I get a query object loaded with the underlying sql of e.projects
[ "I think you're describing the lazy=\"dynamic\" property of relationship(). something like\n class Employee(Base):\n __table_name__ = \"employees\"\n ...\n\n projects = relationship(..., lazy=\"dynamic\")\n\nwhich will cause Employee().project to return a sqlalchemy.orm.Query instance instead of a coll...
[ 2, 0 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0007171920_orm_python_sqlalchemy.txt
Q: combining arrays I have three separate 1d arrays of a list of numbers, their squares and cubes (created by a 'for' loop). I would like these arrays to appear in three corresponding columns, however I have tried the column_stack function and python says its not defined. I have read about the vstack and hstack func...
combining arrays
I have three separate 1d arrays of a list of numbers, their squares and cubes (created by a 'for' loop). I would like these arrays to appear in three corresponding columns, however I have tried the column_stack function and python says its not defined. I have read about the vstack and hstack functions but am confused ...
[ "Why don't you define y and z directly?\ny = x**2\nz = x**3\n\nand then simply:\nstacked = np.column_stack((x,y,z))\n\nwhich gives you a 2D array of shape len(x) * 3\n", "import numpy\nmakearange = lambda a: numpy.arange(int(a[0]),int(a[1]),int(a[2]))\nx = makearange(raw_input('Enter start,stop,increment: ').spli...
[ 1, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0007177243_numpy_python.txt
Q: convert string into ASCII code I need to convert string into ASCII code. I'm using python. I did as below: b1=[ord(x) for x in l1[i]] here l1 is a linelist, l1[i] is the ith line of l1 but I got error like: Traceback (most recent call last): File "./fastq_phred_filter.py", line 24, in ? b1=[ord(x) for x in ...
convert string into ASCII code
I need to convert string into ASCII code. I'm using python. I did as below: b1=[ord(x) for x in l1[i]] here l1 is a linelist, l1[i] is the ith line of l1 but I got error like: Traceback (most recent call last): File "./fastq_phred_filter.py", line 24, in ? b1=[ord(x) for x in str(l1[i])] IndexError: string index...
[ "I'm going to guess that l1 is not a list but a string, based on the error message. l1[i] is the only indexing you're doing in the expression.\n", "It would be easier to see what's going on with a bigger code chunk. Is this happening in a loop with i as the loop index? In any case, the only indexing happening i...
[ 1, 1 ]
[]
[]
[ "ascii", "list", "python", "string" ]
stackoverflow_0007177285_ascii_list_python_string.txt
Q: Python Syntax Error Created a views.py method to get the data posted from an html form. As well as getting the data I am trying to validate the check boxes. However am being given a syntax error, but I don't understand why. Code: if request.POST: startdate = request.POST['startdate'] enddate = request.POS...
Python Syntax Error
Created a views.py method to get the data posted from an html form. As well as getting the data I am trying to validate the check boxes. However am being given a syntax error, but I don't understand why. Code: if request.POST: startdate = request.POST['startdate'] enddate = request.POST['enddate'] getlogs ...
[ "You want the equality operator.\nif request.POST['getlogs'] == 'on':\n\n= is not an operator in Python, as the assignment is a statement, not an expression.\n", "replace: \nif request.POST['getlogs'] = 'on':\n\nwith \nif request.POST['getlogs'] == 'on':\n ^^\n\nIn python, one equal sign...
[ 7, 2, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007177820_django_python.txt
Q: How to calculate relative path between 2 directory path? I have 2 directory: subdir1 = live/events/livepkgr/events/_definst_/ subdir2 = live/streams/livepkgr/streams/_definst_/ result must be: diff_subdir = ../../../../streams/livepkgr/streams/_definst_/ A: http://docs.python.org/library/os.path.html os.path....
How to calculate relative path between 2 directory path?
I have 2 directory: subdir1 = live/events/livepkgr/events/_definst_/ subdir2 = live/streams/livepkgr/streams/_definst_/ result must be: diff_subdir = ../../../../streams/livepkgr/streams/_definst_/
[ "http://docs.python.org/library/os.path.html\n\nos.path.relpath(path[, start]) Return a relative filepath to path\n either from the current directory or from an optional start point.\nstart defaults to os.curdir.\nAvailability: Windows, Unix.\nNew in version 2.6.\n\n", ">>> subdir1 = \"live/events/livepkgr/event...
[ 23, 19 ]
[]
[]
[ "python" ]
stackoverflow_0007178001_python.txt
Q: line or string? I've used different ways for INPUT these days using python. f=open('txt','r') for line in f:..... f=open ('txt','r').readlines() for line in f:... samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile], stdout=subprocess.PIPE,bufsize=1)...
line or string?
I've used different ways for INPUT these days using python. f=open('txt','r') for line in f:..... f=open ('txt','r').readlines() for line in f:... samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile], stdout=subprocess.PIPE,bufsize=1) f = samtoolsin.s...
[ "Short Answer:\n\n1 and 3: file object\n2: list\n4: string\n\nLong Answer (mainly links to docs):\nf=open('txt','r')\n\n\nopen() returns a File Object. It is iterable, but is neither a string nor a list.\n\n\nf=open ('txt','r').readlines()\n\n\nfile.readlines() returns a list\n\n\nsamtoolsin = subprocess.Popen(...,...
[ 3, 0 ]
[]
[]
[ "list", "python", "string" ]
stackoverflow_0007177905_list_python_string.txt
Q: sqlalchemy - how to manage this scenario - cyclic dependency I have a database package which contains some modules namely student_table and a db module, in student_table I have definition it's definition like this from sqlalchemy import Table, MetaData, String, Column, Integer metadata = MetaData() class User(obj...
sqlalchemy - how to manage this scenario - cyclic dependency
I have a database package which contains some modules namely student_table and a db module, in student_table I have definition it's definition like this from sqlalchemy import Table, MetaData, String, Column, Integer metadata = MetaData() class User(object): def __init__(self, user_id, name): s...
[ "I have used something equivalent to this.\nholder = [None]\ndef getmetadata():\n if holder[0] is None:\n holder[0] = sqlalchemy.MetaData()\n return holder[0]\n\nuser_tablef = lambda metadata: Table('twitter_user', metadata,\n Column('id', Integer, primary_key=True), \n Column('name', String(100)...
[ 1, 0 ]
[]
[]
[ "database", "python", "sqlalchemy" ]
stackoverflow_0006925481_database_python_sqlalchemy.txt