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: How to add a pagination "go to page" form set to Django admin on a ModelAdmin form? Here's the gist of my desired scenario: I've got the standard Django pagination going in the admin site. What I'd like to do is let a user enter a number into a text input that corresponds to some page number. The user presses ente...
How to add a pagination "go to page" form set to Django admin on a ModelAdmin form?
Here's the gist of my desired scenario: I've got the standard Django pagination going in the admin site. What I'd like to do is let a user enter a number into a text input that corresponds to some page number. The user presses enter or clicks a button. Results for the page number entered are then shown. Note: I'm usin...
[ "Every pagination system I have come across including the standard Django pagination uses GET parameters for rendering a page.\nSo, providing a form to get the page number of the page to be displayed is the simplest thing you can do with html forms.\n<form>\n\n <input type=\"text\" name=\"page\">\n <input typ...
[ 2 ]
[]
[]
[ "admin", "django", "django_forms", "django_pagination", "python" ]
stackoverflow_0004326989_admin_django_django_forms_django_pagination_python.txt
Q: 'bytesize' in PySerial module I want to send messages through the serial port using PySerial. One of the parameters for the serial constructor is 'bytesize'. I have been trying serial.SEVENBITS and serial.EIGHTBITS and haven't noticed a difference. The documentation is a bit vague and I am new to both Python and s...
'bytesize' in PySerial module
I want to send messages through the serial port using PySerial. One of the parameters for the serial constructor is 'bytesize'. I have been trying serial.SEVENBITS and serial.EIGHTBITS and haven't noticed a difference. The documentation is a bit vague and I am new to both Python and serial communication. Does this just...
[ "Historically, it was common to only send ASCII text over a serial connection, which fit into seven bits, and an eighth bit would be used as a parity marker which could indicate if the data was being transmitted correctly. \nSince the parity check doesn't catch errors on an even number of bits, and can't correct th...
[ 3, 1 ]
[]
[]
[ "byte", "pyserial", "python", "size" ]
stackoverflow_0004328223_byte_pyserial_python_size.txt
Q: Python Login Script I know similar questions have been asked, I have read them. I have also read most other related articles I could find. I have tried httplib2, header modifications, and anything else I could find or think of, however I cannot get this login script to work. import cookielib import urllib import ...
Python Login Script
I know similar questions have been asked, I have read them. I have also read most other related articles I could find. I have tried httplib2, header modifications, and anything else I could find or think of, however I cannot get this login script to work. import cookielib import urllib import urllib2 cj = cookielib.C...
[ "I suppose it's again term of service but you should try\nimport cookielib\nimport urllib\nimport urllib2\n\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nresp = opener.open('http://www.biocidecity.com')\n\ntheurl = 'http://www.biocidecity.com/index.php'\nbody={'usernam...
[ 2 ]
[]
[]
[ "authentication", "python" ]
stackoverflow_0004327182_authentication_python.txt
Q: How to retrieve onclick text? In a webpage I have these elements: <a href="#" onClick="window.open('/link.php?webpage=45980a6f91ac0c850745e0500d612172" class="pagelink" >Page 1</a> <a href="#" onClick="window.open('/link.php?webpage=45980a6f91ac0c850745e05676787895" class="pagelink" >Page 2</a> <a href="#" onClick...
How to retrieve onclick text?
In a webpage I have these elements: <a href="#" onClick="window.open('/link.php?webpage=45980a6f91ac0c850745e0500d612172" class="pagelink" >Page 1</a> <a href="#" onClick="window.open('/link.php?webpage=45980a6f91ac0c850745e05676787895" class="pagelink" >Page 2</a> <a href="#" onClick="window.open('/link.php?webpage=45...
[ "from html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n\n def handle_starttag(self, tag, attrs):\n attr = dict(attrs)\n if attrs[\"class\"] == \"pagelink\":\n add_to_result(attrs[\"onclick\"])\n\nReplace add_to_result with your aggregation object (e.g. list) and actual c...
[ 1, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004328299_python_python_3.x.txt
Q: Python: What's the best way to send status bits and timestamps with PySerial I have done a fair bit of searching and reading around but haven't found an exact clear answer. I am making python application which will communicate with another over the serial port. I have been using PySerial to accomplish this. The ty...
Python: What's the best way to send status bits and timestamps with PySerial
I have done a fair bit of searching and reading around but haven't found an exact clear answer. I am making python application which will communicate with another over the serial port. I have been using PySerial to accomplish this. The types of packets I want to send are status information and data readings. I am propo...
[ "Well, obviously it needs one byte per character sent, so if you can encode your data as an ascii string (str in Python 2, bytes in Python 3), that's most efficient.\nThe struct module is definitely a good idea: it packs Python data into a string (and unpacks it at the other end). That'll work for your timestamps; ...
[ 0, 0 ]
[]
[]
[ "pyserial", "python", "serial_port", "status" ]
stackoverflow_0004327878_pyserial_python_serial_port_status.txt
Q: How to expose a dbus method with multiple arguments? Is it possible to create a dbus method that accepts multiple arguments? I wish to make a method like this: def some_method(self, string, list_of_strings): #do something with arguments into a method accessible using dbus. Is there a way to specify multiple a...
How to expose a dbus method with multiple arguments?
Is it possible to create a dbus method that accepts multiple arguments? I wish to make a method like this: def some_method(self, string, list_of_strings): #do something with arguments into a method accessible using dbus. Is there a way to specify multiple arguments in dbus. My only solution so far is to use one bi...
[ "I believe in_signature='sas' would achieve what you want.\n" ]
[ 2 ]
[]
[]
[ "dbus", "python" ]
stackoverflow_0004266459_dbus_python.txt
Q: Python equivalent of continuations with Ruby What is the Python equivalent of the following code in Ruby? def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end > c=loop 1 2 3 4 > c.call 3 4 Reference: Secrets of lightweight development succes...
Python equivalent of continuations with Ruby
What is the Python equivalent of the following code in Ruby? def loop cont=nil for i in 1..4 puts i callcc {|continuation| cont=continuation} if i==2 end return cont end > c=loop 1 2 3 4 > c.call 3 4 Reference: Secrets of lightweight development success, Part 9: Continuations-based frameworks
[ "The article you quoted contains a link to Continuations Made Simple And Illustrated in the Resources section, which talks about continuations in the Python language.\n", "take a look at the yield statement to make generators.\nI don't speak any ruby, but it seems like you're looking for this:\ndef loop():\n f...
[ 5, 2, 2, 2, 0 ]
[]
[]
[ "continuations", "python", "ruby" ]
stackoverflow_0000312794_continuations_python_ruby.txt
Q: Python 2.7 SimlpeQueue Import Error (a bug?) $ python2.6 -c 'from multiprocessing.queues import SimpleQueue' $ python2.7 -c 'from multiprocessing.queues import SimpleQueue' Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.7/multiprocessing/queues.py", line 22, in <...
Python 2.7 SimlpeQueue Import Error (a bug?)
$ python2.6 -c 'from multiprocessing.queues import SimpleQueue' $ python2.7 -c 'from multiprocessing.queues import SimpleQueue' Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.7/multiprocessing/queues.py", line 22, in <module> from multiprocessing.synchronize impor...
[ "They recently fixed this in Ubuntu for Python3: https://bugs.launchpad.net/ubuntu/lucid/+source/python3.1/+bug/630511\nThe report for 2.7 is here: https://bugs.launchpad.net/ubuntu/+source/python2.7/+bug/683027\n" ]
[ 1 ]
[]
[]
[ "multiprocessing", "python", "python_2.7" ]
stackoverflow_0004321998_multiprocessing_python_python_2.7.txt
Q: 'hover over' popup with Tkinter I have implemented an informational popup in a python app using a Tkinter Menu widget. I have a Text widget on a canvas in the root window. I created a Menu widget that has root as its parent. When I detect a mouse hover over the text widget I post the popup menu with menuWidget.p...
'hover over' popup with Tkinter
I have implemented an informational popup in a python app using a Tkinter Menu widget. I have a Text widget on a canvas in the root window. I created a Menu widget that has root as its parent. When I detect a mouse hover over the text widget I post the popup menu with menuWidget.post(). When I get a leave event from ...
[ "This is not the right way to do an informational popup. On the Mac and on windows machines menus are native controls. Because of this the unpost command doesn't work because tk cedes control to the system event loop in order to get platform-specific behavior. \nWhat you want is to use instead is a toplevel window ...
[ 3 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004328603_python_tkinter.txt
Q: python module import question So I have a big project with many modules in it, and I want to run some profiling on it. I have a profile module that basically just provides a decorator that I can add to a function to profile it when it's called. The problem is, I'll have to import that module into the dozens of mod...
python module import question
So I have a big project with many modules in it, and I want to run some profiling on it. I have a profile module that basically just provides a decorator that I can add to a function to profile it when it's called. The problem is, I'll have to import that module into the dozens of modules that I have. This is fine I gu...
[ "You could create your profiling module such that it imports your other modules and annotates their functions:\n# these are the modules you want to profile\nimport foo\nimport huh\n\n# This is a profiling function\n# yours would do something smarter\ndef profile(f):\n def gotcha(*args, **kwds):\n print \"...
[ 2, 0 ]
[]
[]
[ "module", "profiling", "python" ]
stackoverflow_0004328681_module_profiling_python.txt
Q: Extrapolation from data plotted using matplotlib I have 10 values of x and y in my file. Is there any way that I can extrapolate the graph ie make it into a continous function and increasing its range for other x-values in matplotlib ?? I would even be thankful if anyone can tell me if there is any other software ...
Extrapolation from data plotted using matplotlib
I have 10 values of x and y in my file. Is there any way that I can extrapolate the graph ie make it into a continous function and increasing its range for other x-values in matplotlib ?? I would even be thankful if anyone can tell me if there is any other software that I can use. I basically want that these 10 values ...
[ "below i use Scipy, but the same functions (polyval and polyfit) are also in NumPy; NumPy is a Matplotlib dependency so you can import those two functions from there if you don't have SciPy installed.\nimport numpy as NP\nfrom scipy import polyval, polyfit\nfrom matplotlib import pyplot as PLT\n\nn=10 # 10 data p...
[ 16, 5, 0 ]
[]
[]
[ "matplotlib", "numpy", "python" ]
stackoverflow_0004296603_matplotlib_numpy_python.txt
Q: How to get the full path for a local file in Firefox 3 I'm working on an intranet site, and would like to be able to click on a file (I'm not picky on how) and have the server "know" the filenme + path that I just picked. The local path is relevent because the server hosting the application has the same mapped ne...
How to get the full path for a local file in Firefox 3
I'm working on an intranet site, and would like to be able to click on a file (I'm not picky on how) and have the server "know" the filenme + path that I just picked. The local path is relevent because the server hosting the application has the same mapped network drive as all of the clients, so x:\someplace\something...
[ "Do you really want to do this?If the server is supposed to read the file with the path,why not simply upload it? Is it so large that it takes am unaceptable amount of time on an intranet? Anyway, you can probably do this with a java applet embedded.\n" ]
[ 0 ]
[]
[]
[ "html", "jquery", "python" ]
stackoverflow_0004328416_html_jquery_python.txt
Q: Problem with POST request from APE server module I use Ajax Push Engine as push engine and Django for main site. I wrote the server module which must send the request to my Django-based application when new user join the channel by using Http module. My Django-based project runs on the local machine on local.jjjbb...
Problem with POST request from APE server module
I use Ajax Push Engine as push engine and Django for main site. I wrote the server module which must send the request to my Django-based application when new user join the channel by using Http module. My Django-based project runs on the local machine on local.jjjbbb.org. Ape.addEvent("join", function(user, channel) { ...
[ "Sorry, I already found my problem. APE works fine, it was a little trouble with CSRF protection in Django.\n" ]
[ 1 ]
[]
[]
[ "ajax_push", "ape", "django", "python", "server_push" ]
stackoverflow_0004325058_ajax_push_ape_django_python_server_push.txt
Q: how to install a python package to windows? I would like to install a python package to windows. I have tried to run setup.py install on command prompt but it returned an error: could not create 'C:\Program Files\Python...': access is denied. Please, help. Špela A: My first question would be, do you have admin...
how to install a python package to windows?
I would like to install a python package to windows. I have tried to run setup.py install on command prompt but it returned an error: could not create 'C:\Program Files\Python...': access is denied. Please, help. Špela
[ "My first question would be, do you have administration rights when you try to run setup.py?\n" ]
[ 2 ]
[]
[]
[ "installation", "python", "windows" ]
stackoverflow_0004329330_installation_python_windows.txt
Q: Best way to generate java with python? Whats the best way to generate java from python? I want to write a decorator that generates java code to call a json version of a function (I can use existing decorators to export the json api). Whats the best way to generate the java, should I consider stuff like FSMs here? ...
Best way to generate java with python?
Whats the best way to generate java from python? I want to write a decorator that generates java code to call a json version of a function (I can use existing decorators to export the json api). Whats the best way to generate the java, should I consider stuff like FSMs here? Ideally I can write my code once, for the se...
[ "You can always create java code the same way webapps create HTML: with a template. Then you can have the java source code compiled into bytecode using a regular Java compiler ( see: \nPackage javax.tools )\nNot necessarily the best option, but definitely an option ( and quite simple btw )\n", "Reuse is good. Com...
[ 2, 1 ]
[ "My advice? Have it generate JavaScript code instead of Java code. Android can execute JavaScript code using a WebView.\n" ]
[ -2 ]
[ "abstract_syntax_tree", "fsm", "java", "python" ]
stackoverflow_0004329091_abstract_syntax_tree_fsm_java_python.txt
Q: How to use map function on nested lists and converting strings to integers? I would need to use the map function in Python(2.4.4) to add 1 to each item in the list, so I tried converting the strings into integers. line=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']] map(lambda X:(X+1),int(line)) Is thi...
How to use map function on nested lists and converting strings to integers?
I would need to use the map function in Python(2.4.4) to add 1 to each item in the list, so I tried converting the strings into integers. line=[['10', '13\n'], ['3', '4\n'], ['5', '3\n'], ['1', '13']] map(lambda X:(X+1),int(line)) Is this not working because of \n and the nests?
[ "I would use a list comprehension but if you want map\nmap(lambda line: map(lambda s: int(s) + 1, line), lines)\n\nThe list comprehension would be\n[[int(x) + 1 for x in line] for line in lines]\n\n\n\n>>> lines=[['10', '13\\n'], ['3', '4\\n'], ['5', '3\\n'], ['1', '13']]\n\n>>> map(lambda line: map(lambda s: int(s...
[ 6, 5, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004328286_python.txt
Q: Handle specific exception type in python I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example: try: stuff() except Exception as e: if _debug and e is KeyboardInterrupt: sys.exit() logging.except...
Handle specific exception type in python
I have some code that handles an exception, and I want to do something specific only if it's a specific exception, and only in debug mode. So for example: try: stuff() except Exception as e: if _debug and e is KeyboardInterrupt: sys.exit() logging.exception("Normal handling") As such, I don't want ...
[ "Well, really, you probably should keep the handler for KeyboardInterrupt separated. Why would you only want to handle keyboard interrupts in debug mode, but swallow them otherwise?\nThat said, you can use isinstance to check the type of an object:\ntry:\n stuff()\nexcept Exception as e:\n if _debug and isins...
[ 35, 20, 1, 0, 0, 0, 0 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0004329453_exception_exception_handling_python.txt
Q: Split a list into nested lists on a value Say I have a list like so: [1, 4, None, 6, 9, None, 3, 9, 4] I decide to split this into nested lists on None, to get this: [[1, 4], [6, 9], [3, 9, 4]] Of course, I could have wanted to do this on (9, None) in which case, we would have got: [[1, 4], [6], [3], [4]] This ...
Split a list into nested lists on a value
Say I have a list like so: [1, 4, None, 6, 9, None, 3, 9, 4] I decide to split this into nested lists on None, to get this: [[1, 4], [6, 9], [3, 9, 4]] Of course, I could have wanted to do this on (9, None) in which case, we would have got: [[1, 4], [6], [3], [4]] This is trivial to do using list append through iter...
[ ">>> def isplit(iterable,splitters):\n return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k]\n\n>>> isplit(L,(None,))\n[[1, 4], [6, 9], [3, 9, 4]]\n>>> isplit(L,(None,9))\n[[1, 4], [6], [3], [4]]\n\nbenchmark code:\nimport timeit \n\nkabie=(\"isplit_kabie\",\n\"\"\"\nimport ...
[ 38, 5, 2, 1, 1 ]
[]
[]
[ "list_comprehension", "nested_lists", "python" ]
stackoverflow_0004322705_list_comprehension_nested_lists_python.txt
Q: Mako template encoding urls I have a variable whose value is html: c.url = '<a href=""></a>' When I display this in my mako template, the output is: &lt;a href=&quot;&quot;&gt;&lt;/a&gt; What's going on? Thanks. A: Your variable's content is being filtered so that it's safe to present. markupsafe.escape() is b...
Mako template encoding urls
I have a variable whose value is html: c.url = '<a href=""></a>' When I display this in my mako template, the output is: &lt;a href=&quot;&quot;&gt;&lt;/a&gt; What's going on? Thanks.
[ "Your variable's content is being filtered so that it's safe to present. markupsafe.escape() is being run on it.\n" ]
[ 0 ]
[]
[]
[ "mako", "python" ]
stackoverflow_0004329656_mako_python.txt
Q: What's the fastest way to loop through a list and create a single string? For example: list = [{"title_url": "joe_white", "id": 1, "title": "Joe White"}, {"title_url": "peter_black", "id": 2, "title": "Peter Black"}] How can I efficiently loop through this to create: Joe White, Peter Black <a href="/u/joe...
What's the fastest way to loop through a list and create a single string?
For example: list = [{"title_url": "joe_white", "id": 1, "title": "Joe White"}, {"title_url": "peter_black", "id": 2, "title": "Peter Black"}] How can I efficiently loop through this to create: Joe White, Peter Black <a href="/u/joe_white">Joe White</a>,<a href="/u/peter_black">Peter Black</a> Thank you.
[ "The first is pretty simple:\n', '.join(item['title'] for item in list)\n\nThe second requires something more complicated, but is essentially the same:\n','.join('<a href=\"/u/%(title_url)s\">%(title)s</a>' % item for item in list)\n\nBoth use generator expressions, which are similar to list comprehensions without ...
[ 8, 5, 1 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0004329022_nested_lists_python.txt
Q: Python library for dealing with time associated data? I've got some data (NOAA-provided weather forecasts) I'm trying to work with. There are various data series (temperature, humidity, etc), each of which contains a series of data points, and indexes into an array of datetimes, on various time scales (Some series...
Python library for dealing with time associated data?
I've got some data (NOAA-provided weather forecasts) I'm trying to work with. There are various data series (temperature, humidity, etc), each of which contains a series of data points, and indexes into an array of datetimes, on various time scales (Some series are hourly, others 3-hourly, some daily). Is there any sor...
[ "If your data is sorted you can use the bisect module to quickly get the entry with the greatest time less than or equal to the specified time.\nSomething like:\ni = bisect_right(times, time)\n# times[j] <= time for j<i\n# times[j] > time for j>=i\nif times[i-1] == time:\n # exact match\n value = values[i...
[ 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004329572_python.txt
Q: How can I use a diagonal line as a boundary? Maybe I'm having a brainfart, it seems like this should be really simple. I've drawn a line in python using pygame: pygame.draw.line(screen, color, e.start, e.stop, 3) This draws a line on the object screen in the color color, from the tuple coordinates e.start to the ...
How can I use a diagonal line as a boundary?
Maybe I'm having a brainfart, it seems like this should be really simple. I've drawn a line in python using pygame: pygame.draw.line(screen, color, e.start, e.stop, 3) This draws a line on the object screen in the color color, from the tuple coordinates e.start to the tuple coordinates e.stop. Anyway, I'm trying to cr...
[ "Oh duh! The equation of a line. y=mx+b can be derived from 2 points. My goodness. Then I can just use the size of the object I want to stop on the line to check it it's hitting the line.\n" ]
[ 1 ]
[]
[]
[ "computational_geometry", "lines", "pygame", "python" ]
stackoverflow_0004330062_computational_geometry_lines_pygame_python.txt
Q: Comparing Value of one list inside Gigantic Two Dimen list in python, Fastest way? I want to compare if value of one list exist in value of other list.They are huge (50k + items, from database). EDIT: I also want to mark the record which is duplicated as duplicate=True and keep them in the table for later refrence...
Comparing Value of one list inside Gigantic Two Dimen list in python, Fastest way?
I want to compare if value of one list exist in value of other list.They are huge (50k + items, from database). EDIT: I also want to mark the record which is duplicated as duplicate=True and keep them in the table for later refrence. here how the lists are: n_emails=[db_id,checksum for id,checksum in search_results] #I...
[ "You'd be better off looking for duplicates with SQL. For example, see this page describing how to find duplicates.\nPulling all of those results into Python and processing them is never going to be very fast, but if you must, your best bet is to have a dictionary of checksums to IDs:\ngot_checksums = {}\nfor id, c...
[ 2, 2, 2, 1 ]
[]
[]
[ "comparison", "list", "list_comprehension", "performance", "python" ]
stackoverflow_0004319962_comparison_list_list_comprehension_performance_python.txt
Q: Skip a letter in dictionary I need to assign the uppercase to numbers in a dictionary but with one letter S not there. ie. in this alphadict = dict((x, i) for i, x in enumerate(string.ascii_uppercase)) I have currently all the alphabets of the dictionary. What is the simplest way to delete the entry for S and shi...
Skip a letter in dictionary
I need to assign the uppercase to numbers in a dictionary but with one letter S not there. ie. in this alphadict = dict((x, i) for i, x in enumerate(string.ascii_uppercase)) I have currently all the alphabets of the dictionary. What is the simplest way to delete the entry for S and shift rest of the values to the left...
[ "The simplest way is to remove the letter 'S' before you create the dictionary.\nUse string.ascii_uppercase.replace('S', '') instead of string.ascii_uppercase.\n", "alphadict = dict((x, i) for i, x in enumerate(string.ascii_uppercase) if x != 'S')\n", "for Q2\ndef makealphabet(i):\n a=list(string.ascii_upper...
[ 3, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004330026_python.txt
Q: Error when re-sizing data in numpy array I have two arrays that I want to re-size, but I also want to retain the original values. The code below re-sizes the arrays, but the problem is that it over-writes the original values, as you can see when you look at the output from the print(x) print(y) commands at the...
Error when re-sizing data in numpy array
I have two arrays that I want to re-size, but I also want to retain the original values. The code below re-sizes the arrays, but the problem is that it over-writes the original values, as you can see when you look at the output from the print(x) print(y) commands at the end of the script. However, if we comment ou...
[ "NewX = x.copy()\nNewY = y.copy()\n\nnumpy arrays also support the __copy__ interface, and can be copied with the copy module, so this would also work:\nNewX = copy.copy(x)\nNewY = copy.copy(y)\n\nIf you want to retain the current behaviour of the function as-is, you'd need to replace all occurences of x and y with...
[ 3, 1, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004329977_numpy_python.txt
Q: Another sigmoidal regression equation question I posted an earlier version of this yesterday, but I cannot seem to add this version to that posting because someone seems to have closed that posting for editing, so here is the new version in a new posting. I have the script below that does the following things: 1.)...
Another sigmoidal regression equation question
I posted an earlier version of this yesterday, but I cannot seem to add this version to that posting because someone seems to have closed that posting for editing, so here is the new version in a new posting. I have the script below that does the following things: 1.) plot a best fit curve to sigmoidal data. 2.) re-siz...
[ "Try this:\nimport numpy as np \nimport matplotlib.pyplot as plt \nimport scipy.optimize \n\ndef GetMinRR(age):\n MaxHR = 208-(0.7*age)\n MinRR = (60/MaxHR)*1000\n return MinRR\n\ndef sigmoid(p,x):\n x0,y0,c,k=p \n y = c / (1 + np.exp(-k*(x-x0))) + y0 \n return y \n\ndef residuals(p,x,y): \n re...
[ 2 ]
[]
[]
[ "numpy", "python", "scientific_computing", "scipy", "statistics" ]
stackoverflow_0004330438_numpy_python_scientific_computing_scipy_statistics.txt
Q: Executable path to Mac App In a py2app/Mac Application Bundle, is there a way to spawn another instance of same app from within the app, by passing different command line arguments? or given a mac app bundle, how can I run it from command line and pass some arguments too? Edit1:forking is a limited option, which m...
Executable path to Mac App
In a py2app/Mac Application Bundle, is there a way to spawn another instance of same app from within the app, by passing different command line arguments? or given a mac app bundle, how can I run it from command line and pass some arguments too? Edit1:forking is a limited option, which may not work with 3rd party execu...
[ "Howto find cwd and execute an arbitrary supplied binary\nFirst place the binary in AppName.app/Contents/Resources then run this code from the python script: \nimport subprocess\nprocess=subprocess.Popen((os.getcwd() + \"/3rd_party_binary\",\"--subprocess\")) \nprocess.poll() # is running?\n\nHowto properly spawn t...
[ 1, 0, 0 ]
[]
[]
[ "macos", "py2app", "python" ]
stackoverflow_0004291880_macos_py2app_python.txt
Q: In Python, how do I make a temp file that persists until the next run? I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. Currently, I'm do...
In Python, how do I make a temp file that persists until the next run?
I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp_file module in the standard library, but I'm not sure how to get the behavior that I want. Currently, I'm doing the following to create the directory: randName = "temp" + str(random....
[ "Creating the folder with a 4-digit random number is insecure, and you also need to worry about collisions with other instances of your program. \nA much better way is to create the folder using tempfile.mkdtemp, which does exactly what you want (i.e. the folder is not deleted when your script exits). You would the...
[ 18, 8, 4, 3, 2, 1, 1 ]
[]
[]
[ "python", "temporary_files" ]
stackoverflow_0000581851_python_temporary_files.txt
Q: python read output Write a program that outputs the first number within a file specified by the user. It should behave like: Enter a file name: l11-1.txt The first number is 20. You will need to use the file object method .read(1) to read 1 character at a time, and a string object method to check if it is a number...
python read output
Write a program that outputs the first number within a file specified by the user. It should behave like: Enter a file name: l11-1.txt The first number is 20. You will need to use the file object method .read(1) to read 1 character at a time, and a string object method to check if it is a number. If there is no number,...
[ "OK, you've been given some instructions:\n\nread a string input from the user\nopen the file given by that string\n.read(1) a character at a time until you get the first number or EOF\nprint the number\n\nYou've got the first and second parts here (although you should use open instead of file to open a file), what...
[ 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004328721_python.txt
Q: Python shared libraries - Cheetah namemapper.so not found I'm using Python Cheetah for template generation and I can't get it to use the compiled _namemapper.so library that is installed. I am running on CentOS 5.4 with Python 2.4 installed, using Cheetah 2.4.3. I cannot for the life of me get Cheetah to use the _...
Python shared libraries - Cheetah namemapper.so not found
I'm using Python Cheetah for template generation and I can't get it to use the compiled _namemapper.so library that is installed. I am running on CentOS 5.4 with Python 2.4 installed, using Cheetah 2.4.3. I cannot for the life of me get Cheetah to use the _namemapper.so file that I built during install: Filling conf/as...
[ "Sometimes it's useful to use strace to print out open calls to trace the search path used by Python.\neg. If the name of the module you're trying to import is namemapper, the following will show the paths searched for the namemapper module.\nstrace -e open python -c 'import namemapper'\n\nThis may give you some c...
[ 2, 2 ]
[]
[]
[ "cheetah", "python" ]
stackoverflow_0004328046_cheetah_python.txt
Q: google app engine blob store creation In order to save precious bandwidth, the image serving app (a minor, but important part of the total app) tries to serve only thumbnails or reduced size previews of possibly large photos or illustrations. Storing the original image in the BlobStore is simple enough, and gener...
google app engine blob store creation
In order to save precious bandwidth, the image serving app (a minor, but important part of the total app) tries to serve only thumbnails or reduced size previews of possibly large photos or illustrations. Storing the original image in the BlobStore is simple enough, and generating the thumbnails is also simple using t...
[ "You don't need to create thumbnails from images in BlobStore at all - use get_serving_url function instead (see http://code.google.com/appengine/docs/python/images/functions.html). \nThis function generates and caches thumbnails from large images in the fly and doesn't even cost you any CPU (see this post)\n", "...
[ 7, 0 ]
[]
[]
[ "blobstore", "google_app_engine", "image", "python" ]
stackoverflow_0003776208_blobstore_google_app_engine_image_python.txt
Q: Python - how to get class instance reference from an attribute class? class A() att = B() class B() ... a = A() b = B() a.att = b How can b get reference of a ? I need to get an attribute of a here. Thanks! A: Easiest way would be to just add an extra function parameter to the method in ...
Python - how to get class instance reference from an attribute class?
class A() att = B() class B() ... a = A() b = B() a.att = b How can b get reference of a ? I need to get an attribute of a here. Thanks!
[ "Easiest way would be to just add an extra function parameter to the method in B that needs A, and pass it through when called. Or, just make B's init take an A as argument, and change the bit in A's init to be att = B(self)\n", "class A(object):\n def __init__(self):\n self.att = B(self)\n\nclass B(obj...
[ 0, 0, 0, 0, 0 ]
[]
[]
[ "attributes", "class", "python", "reference" ]
stackoverflow_0004330723_attributes_class_python_reference.txt
Q: Python CGI script - redirect doesn't always work I'm writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then displays one or another version of its own page depending on what it just did. E.g. if you add a comment, it reloads the "item" version of the ...
Python CGI script - redirect doesn't always work
I'm writing a small CGI script for an assignment (Python 2.4) that takes form data, runs a shell command with it, and then displays one or another version of its own page depending on what it just did. E.g. if you add a comment, it reloads the "item" version of the page rather than the "list of all items" view, incorpo...
[ "Check and make sure you're really not outputting anything before the location header. If there's anything at all output before that, you're not going actually get the location header to do anything.\n", "If your command os.system print anything, your Location header could be invalid.\n\nEnsure that your os.syste...
[ 0, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0004330525_cgi_python.txt
Q: Problem with function in python I am a newbie in python. I am trying to code a very basic function but getting errors. I dont know the reason behind it. Example code: def printme( str ): print str; return; printme("My string"); This should execute logically but it gives me the following error: Traceback ...
Problem with function in python
I am a newbie in python. I am trying to code a very basic function but getting errors. I dont know the reason behind it. Example code: def printme( str ): print str; return; printme("My string"); This should execute logically but it gives me the following error: Traceback (most recent call last): File "stdi...
[ "The semicolons shouldn't be there as well as the return statement (the execution of the function ends at the last statement indented within it).\nNot entirely sure how you formated the indent but python relies on that to determine scope\ndef printme(str):\n print str #This line is indented, \n #tha...
[ 4, 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004330848_python.txt
Q: Persistent objects in recursive python functions I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to modify or inherit the class of the parameter of the function so that it can keep this...
Persistent objects in recursive python functions
I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to modify or inherit the class of the parameter of the function so that it can keep this persistent object but I don't find it elegant. I coul...
[ "Just pass through your persistent object through the recursive method.\ndef recursivemethod(obj_to_act_on, persistent_obj=None):\n\n if persistent_obj == None:\n persistent_obj = set()\n\n # Act on your object\n\n return recursivemethod(newobj, persistent_obj)\n\n", "Objects are passed by referen...
[ 9, 4, 2, 1, 0, 0 ]
[]
[]
[ "persistent", "python", "recursion" ]
stackoverflow_0004331006_persistent_python_recursion.txt
Q: fixed point iteration algorithm I am asked to write a program to solve this equation ( x^3 + x -1 = 0 ) using fixed point iteration. What is the algorithm for fixed point iteration? Is there any fixed point iteration code sample in Python? (not a function from any modules, but the code with algorithms) Thank You ...
fixed point iteration algorithm
I am asked to write a program to solve this equation ( x^3 + x -1 = 0 ) using fixed point iteration. What is the algorithm for fixed point iteration? Is there any fixed point iteration code sample in Python? (not a function from any modules, but the code with algorithms) Thank You
[ "First, read this:\nFixed point iteration:Applications\nI chose Newton's Method.\nNow if you'd like to learn about generator functions, you could define a generator function, and instance a generator object as follows\ndef newtons_method(n):\n n = float(n) #Force float arithmetic\n nPlusOne = n - (pow(n,3) +...
[ 1, 0 ]
[]
[]
[ "algorithm", "fixed_point_iteration", "numerical_analysis", "python" ]
stackoverflow_0004330947_algorithm_fixed_point_iteration_numerical_analysis_python.txt
Q: Syntax for ghostscript in python I have installed python-ghostscript on Linux. I can run gs from the command line and it will create a jpg from a pdf. Here is the code that works: ~$ gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -sOutputFile=/home/user/output.jpg /home/user/downloads/test.pdf I am trying to run that...
Syntax for ghostscript in python
I have installed python-ghostscript on Linux. I can run gs from the command line and it will create a jpg from a pdf. Here is the code that works: ~$ gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg -sOutputFile=/home/user/output.jpg /home/user/downloads/test.pdf I am trying to run that process in Python but I cannot get th...
[ "Your last two parameters are joined, so it can't work; it's effectively the same as running in your terminal gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=jpeg '-sOutputFile=/home/user/output.jpg /home/user/downloads/test.pdf', which you wouldn't expect to work.\nSeparate those last two and it should work:\noutput = Popen...
[ 3, 1, 1 ]
[]
[]
[ "ghostscript", "popen", "python" ]
stackoverflow_0004201326_ghostscript_popen_python.txt
Q: Transform invalid nested json to valid one and change to list Under this link : http://dev1.gecoloco.com/rte/done_json.php I have a json-like object, that I'm operating on. I cannot load it with simplejson, because it is wrongly formatted. And thus this code fails : conn = httplib.HTTPConnection("dev1.gecoloco.co...
Transform invalid nested json to valid one and change to list
Under this link : http://dev1.gecoloco.com/rte/done_json.php I have a json-like object, that I'm operating on. I cannot load it with simplejson, because it is wrongly formatted. And thus this code fails : conn = httplib.HTTPConnection("dev1.gecoloco.com") conn.request("GET", "/rte/done_json.php") r = conn.getresponse(...
[ "The nice thing about JSON is that it's so, so very close to Python literal syntax. Use ast.literal_eval() to parse it.\n" ]
[ 2 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0004331429_json_python_simplejson.txt
Q: Can from import * not work sometimes? If I have a python module that has a bunch of functions, say like this: #funcs.py def foo() : print "foo!" def bar() : print "bar!" And I have another module that is designed to parse a list of functions from a string and run those functions: #parser.py from funcs i...
Can from import * not work sometimes?
If I have a python module that has a bunch of functions, say like this: #funcs.py def foo() : print "foo!" def bar() : print "bar!" And I have another module that is designed to parse a list of functions from a string and run those functions: #parser.py from funcs import * def execute(command): command =...
[ "import module_name does something fundamentally different from what from module_name import * does.\nThe former creates a global named module_name, which is of type module and which contains the module's names, accessed as attributes. The latter creates a global for each of those names within module_name, but not ...
[ 2, 0, 0 ]
[]
[]
[ "global", "import", "python" ]
stackoverflow_0004331348_global_import_python.txt
Q: Python List Error I was writing a simple genetic program to test out the process, but got the following error: Traceback (most recent call last): File "evolution.py", line 43, in <module> nextgen += test[operator.indexOf(list(fits), m+chance)] TypeError: iteration over non-sequence on the code: #!/usr/bin/e...
Python List Error
I was writing a simple genetic program to test out the process, but got the following error: Traceback (most recent call last): File "evolution.py", line 43, in <module> nextgen += test[operator.indexOf(list(fits), m+chance)] TypeError: iteration over non-sequence on the code: #!/usr/bin/env python import rando...
[ "To add an element into nextgen, use nextgen.append(...) instead. += is the wrong operator.\nSpecifically, += on a list concatenates it with another iterable, not element.\n", "I'm not sure exactly what's going on here, but to add items to a list you should use \"append\". You can also probably simplifiy your co...
[ 4, 0, 0, 0 ]
[]
[]
[ "genetic_algorithm", "python" ]
stackoverflow_0004331416_genetic_algorithm_python.txt
Q: Is it possible to get the color of a particular pixel on the screen with it's X and Y coordinates? I would like to get the color of a particular pixel in Python using its X Y coordinates, is this possible? This is in Windows, if it makes a difference. A: See http://rosettacode.org/wiki/Color_of_a_screen_pixel ...
Is it possible to get the color of a particular pixel on the screen with it's X and Y coordinates?
I would like to get the color of a particular pixel in Python using its X Y coordinates, is this possible? This is in Windows, if it makes a difference.
[ "See http://rosettacode.org/wiki/Color_of_a_screen_pixel under the heading for python\nthey give:\ndef get_pixel_colour(i_x, i_y):\n import win32gui\n i_desktop_window_id = win32gui.GetDesktopWindow()\n i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)\n long_colour = win32gui.GetPixel(i_d...
[ 7 ]
[]
[]
[ "pixel", "python", "windows" ]
stackoverflow_0004331573_pixel_python_windows.txt
Q: updating values of class attributes I have a class like the following: class MyClass(object): def __init__(self, input1, input2): self.attribute1 = [(a1_d1, a1_p1), (a1_d2, a1_p2)] self.attribute2 = [(a2_d1, a2_p1), (a2_d2, a2_p2), ..., (a2_d10, a2_p10)] ...some other attributes her...
updating values of class attributes
I have a class like the following: class MyClass(object): def __init__(self, input1, input2): self.attribute1 = [(a1_d1, a1_p1), (a1_d2, a1_p2)] self.attribute2 = [(a2_d1, a2_p1), (a2_d2, a2_p2), ..., (a2_d10, a2_p10)] ...some other attributes here... The first coordinate in every pair ...
[ "self.attribute = function_name(previous_attribute_value)\n\nThen to get a value: \ndef function_name(attribute):\n #Compute the new value\n return new_attribute_value\n\nI guess you could use a lambda too, instead of calling a function, but it's probably not so reusable.\n", "You could use getattr and rela...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004331458_python.txt
Q: sqlalchemy mysql server has gone away I've read through a number of similar problems, but none seem to fix my issue. I'm running a pylons app and using SQLAlchemy to connect to 2 databases. The primary, configured through the config file works perfectly without issue. I'm trying to connect to a second database ...
sqlalchemy mysql server has gone away
I've read through a number of similar problems, but none seem to fix my issue. I'm running a pylons app and using SQLAlchemy to connect to 2 databases. The primary, configured through the config file works perfectly without issue. I'm trying to connect to a second database by initializing a class defined in model li...
[ "I've had same problem recently, and solved it by ensuring that it always closes transaction, even after SELECTs. Just add DB2.session.commit() to each place you do something with it, and it should start cycling connections.\n" ]
[ 2 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0004326387_mysql_python_sqlalchemy.txt
Q: Get comma-separated values three at a time So I have a text file with comma separated numbers, I'm trying to write Python to get me the numbers three at a time - they're 3D co-ordinates and I want to analyse them 3 at a time. The text file is of the form x1,y1,z1,x2,y2,..., and is just one line. A: You don't ne...
Get comma-separated values three at a time
So I have a text file with comma separated numbers, I'm trying to write Python to get me the numbers three at a time - they're 3D co-ordinates and I want to analyse them 3 at a time. The text file is of the form x1,y1,z1,x2,y2,..., and is just one line.
[ "You don't need regex for this. Check out the CSV module. \n", "def coords(line):\n parts = line.split(',')\n for i in range(0, len(parts), 3):\n yield map(int, parts[i:i+3])\n\nNo need to resort to regexes, really.\n", "Yeah, Any comma separated data evinces the need for CSV but you could do with ...
[ 2, 2, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0004332628_csv_python.txt
Q: How to make class or function to create log file and write in Python? I am new learner to Python, so I am not getting how to make common function for creating log file to record each and every details during testing... A: Try the logging module. If that's overkill for you, why not insert print statements/functio...
How to make class or function to create log file and write in Python?
I am new learner to Python, so I am not getting how to make common function for creating log file to record each and every details during testing...
[ "Try the logging module. If that's overkill for you, why not insert print statements/functions in relevant places of your code and print the variables you're interested in? \n" ]
[ 2 ]
[]
[]
[ "code_generation", "file", "logging", "python" ]
stackoverflow_0004332712_code_generation_file_logging_python.txt
Q: get data from querystring with python I have a querystring like a=2&b=3 created by serialize() jQuery. How to get a and b with a Python function? A: python2: urlparse.parse_qs() python3: urllib.parse.parse_qs
get data from querystring with python
I have a querystring like a=2&b=3 created by serialize() jQuery. How to get a and b with a Python function?
[ "python2: urlparse.parse_qs()\npython3: urllib.parse.parse_qs\n" ]
[ 5 ]
[]
[]
[ "python", "query_string" ]
stackoverflow_0004332729_python_query_string.txt
Q: How to integrate Redis with SQLAlchemy I'm learning to use SQLAlchemy connected to a SQL database for 12 standard relational tables (e.g. SQLite or PostgreSQL). But then I'd like to use Redis with Python for a couple of tables, particularly for Redis's fast set manipulation. I realise that Redis is NoSQL, but can ...
How to integrate Redis with SQLAlchemy
I'm learning to use SQLAlchemy connected to a SQL database for 12 standard relational tables (e.g. SQLite or PostgreSQL). But then I'd like to use Redis with Python for a couple of tables, particularly for Redis's fast set manipulation. I realise that Redis is NoSQL, but can I integrate this with SQLAlchemy for the ben...
[ "While it is possible to set up an ORM that puts data in redis, it isn't a particularly good idea. ORMs are designed to expose standard SQL features. Many things that are standard in SQL such as querying on arbitrary columns are not available in redis unless you do a lot of extra work. At the same time redis has fe...
[ 17, 15 ]
[]
[]
[ "nosql", "python", "redis", "sqlalchemy" ]
stackoverflow_0004324407_nosql_python_redis_sqlalchemy.txt
Q: Should I use Python for a small CRM ? If not, then is there any other platform? We have a new client who would like us to develop a custom CRM for their employees. The main features they would like are: Ability to save forms Send reminders to employees by email and text messages Basic charting capabilities Automa...
Should I use Python for a small CRM ? If not, then is there any other platform?
We have a new client who would like us to develop a custom CRM for their employees. The main features they would like are: Ability to save forms Send reminders to employees by email and text messages Basic charting capabilities Automatic backup online So as we see, saving data, and then reminding the employees are th...
[ "I wouldn't re-invent the wheel, if I were you. Instead I will aim to leverage one of the existing open source CRMs to build the system. A well known open source CRM is SugarCRM. There are more available, most of them built with PHP, so your PHP experience will be useful.\n" ]
[ 3 ]
[]
[]
[ "crm", "development_environment", "platform", "python" ]
stackoverflow_0004332762_crm_development_environment_platform_python.txt
Q: ValidationError giving me exception My admin: from django.core.exceptions import ValidationError def save_model(self, request, obj, form, change): if obj.foo == True and obj.bar == '': raise ValidationError('Please enter the password.') My model is: foo = models.BooleanField(default=False) ...
ValidationError giving me exception
My admin: from django.core.exceptions import ValidationError def save_model(self, request, obj, form, change): if obj.foo == True and obj.bar == '': raise ValidationError('Please enter the password.') My model is: foo = models.BooleanField(default=False) bar = models.CharField(max_length=50, nu...
[ "You're supposed to do your validation in the ModelForm, not the ModelAdmin.\n" ]
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004332781_django_python.txt
Q: Python Optimized Comparison Between List of Dict I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it. I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y':...
Python Optimized Comparison Between List of Dict
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it. I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x':...
[ "(This answer deals with simple optimisations and Python style; it works with the existing algorithm, teaching some points of optimisation, rather than replacing it with a more efficient one.)\nHere are some points to start with to make the code easier to read and understand:\n\nIterate over sList, not over range(l...
[ 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "comparison", "optimization", "python" ]
stackoverflow_0004311082_comparison_optimization_python.txt
Q: python sort list of lists with casting I know tat similar questions has been asked already several times. And i do now how to use the search function, but it still does not work. So here is the problem setup. I have a list of lists containing strings. One column contains strings which actually represent float val...
python sort list of lists with casting
I know tat similar questions has been asked already several times. And i do now how to use the search function, but it still does not work. So here is the problem setup. I have a list of lists containing strings. One column contains strings which actually represent float values. And it is also the column i want to sor...
[ "l = [[\"blaa\", \"0.3\", \"bli\"], [\"bla\", \"0.1\", \"blub\"], [\"bla\", \"-0.2\", \"blub\"]]\n\nl.sort(key=lambda x: float(x[1]))\n\n>>> [['bla', '-0.2', 'blub'], ['bla', '0.1', 'blub'], ['blaa', '0.3', 'bli']]\n\n", "Mine works fine, Python 3.1.2:\n>>> l=[['', '0.3', ''], ['', '0.1', ''], ['', '-0.2', '']]\n...
[ 19, 2 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0004333373_python_sorting.txt
Q: R as a general purpose programming language I liked Python before because Python has rich built-in types like sets, dicts, lists, tuples. These structures help write short scripts to process data. On the other side, R is like Matlab, and has scalar, vector, data frame, array and list as its data types. But it lac...
R as a general purpose programming language
I liked Python before because Python has rich built-in types like sets, dicts, lists, tuples. These structures help write short scripts to process data. On the other side, R is like Matlab, and has scalar, vector, data frame, array and list as its data types. But it lacks sets, dicts, tuples, etc. I know that list typ...
[ "I think that R's data pre-processing capability--i.e., everything from extracting data from its source and just before the analytics steps--has improved substantially in the past three years (the length of time i have been using R). I use python daily and have for the past seven years or so--its text-processing ca...
[ 24, 4, 3 ]
[]
[]
[ "language_features", "python", "r", "wiki" ]
stackoverflow_0004333094_language_features_python_r_wiki.txt
Q: Django: translate in a different language than current language I would like to notify the user in case he's viewing the site in a language that doesn't correspond to his first preference in the ACCEPT_LANGUAGE header. For this reason I would like to present the message to the user in his first prefered language r...
Django: translate in a different language than current language
I would like to notify the user in case he's viewing the site in a language that doesn't correspond to his first preference in the ACCEPT_LANGUAGE header. For this reason I would like to present the message to the user in his first prefered language rather than the one he's currently viewing the web-site. Is it possibl...
[ "You might find some use in the functions activate(language) and deactivate(language) located in django.utils.translation. I'm not sure about the efficiency of this, I imagine it is slow, but it might do the job :)\n", "You can find your answers here:\nhttp://docs.djangoproject.com/en/1.2/howto/i18n/#using-transl...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004312995_django_python.txt
Q: Iterate over large collection in django - cache problem I need to iterate over large collection (3 * 10^6 elements) in Django to do some kind of analysis that can't be done using single SQL statement. Is it possible to turn off collection caching in django? (Caching all the data is not to be acceptable data has a...
Iterate over large collection in django - cache problem
I need to iterate over large collection (3 * 10^6 elements) in Django to do some kind of analysis that can't be done using single SQL statement. Is it possible to turn off collection caching in django? (Caching all the data is not to be acceptable data has around 0.5GB) Is it possible to make django fetch collection i...
[ "Use QuerySet.iterator() to walk over the results instead of loading them all first.\n", "It seams that the problem was caused by the database backend (sqlite) that doesn't support reading in chunks. \nI've used sqlite as the database will be trashed after I do all the computations but it seems that sqlite isn't ...
[ 1, 1 ]
[]
[]
[ "django_models", "python" ]
stackoverflow_0004333588_django_models_python.txt
Q: What is the best practice for registering a new user in my case? I am going to let new users register on my service. Here is the way I think it should go: 1. User enters his email in a field and clicks Register button. 2. User receives a confirmation email with a link containing a verification code. 3. User goes b...
What is the best practice for registering a new user in my case?
I am going to let new users register on my service. Here is the way I think it should go: 1. User enters his email in a field and clicks Register button. 2. User receives a confirmation email with a link containing a verification code. 3. User goes by that link from the email message where he sees a message that his ac...
[ "There is already a project that does exactly what you want. It's called django-registration. I suggest using this project instead of rolling your own. \nIf you still want to do it yourself, then look at the code for django-registration. It has really good comments and is really a perfect app to learn from.\n", "...
[ 2, 2 ]
[]
[]
[ "python", "registration" ]
stackoverflow_0004333711_python_registration.txt
Q: redirecting output of pexpect to a file I tried to capture the output of pexpect in a file. Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pexpect >>> child = pexpect.spawn('iostat 3') >>> fout = file('mylogfi...
redirecting output of pexpect to a file
I tried to capture the output of pexpect in a file. Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pexpect >>> child = pexpect.spawn('iostat 3') >>> fout = file('mylogfile.txt','w') >>> child.logfile = fout tazi...
[ "You have forgotten to expect something from the child :)\nAdd this, for instance:\nchild.expect(pexpect.EOF)\n\n" ]
[ 2 ]
[]
[]
[ "io_redirection", "pexpect", "python" ]
stackoverflow_0004333745_io_redirection_pexpect_python.txt
Q: may i know how can we compare lists ok i m making a game poker card evaluator and i am storing its values in list of list and each list is containing the values like the [rate,rank,max] or just [1,2,3] so my question is if i want to know which players has good hand mean good list for example by comapring list to l...
may i know how can we compare lists
ok i m making a game poker card evaluator and i am storing its values in list of list and each list is containing the values like the [rate,rank,max] or just [1,2,3] so my question is if i want to know which players has good hand mean good list for example by comapring list to list, if rate1==rate2(list2 in the list o...
[ "Sequences are already compared element-wise; there is nothing you need to do in order to invoke the desired behavior.\n", "Perhaps you mean something like this\n>>> from operator import itemgetter\n>>> L = [[1,2],[1,2],[1,4]]\n>>> max(L, key=itemgetter(1))\n[1, 4]\n\n" ]
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004334183_python.txt
Q: Django: Best way for simple hierarchy? I have this model: class Category(models.Model): name = models.CharField() description = models.CharField(blank=True) parent = models.ForeignKey('self', blank=True, null=True) I want Django to sort the categories with respect to their hierarchy, for example: Par...
Django: Best way for simple hierarchy?
I have this model: class Category(models.Model): name = models.CharField() description = models.CharField(blank=True) parent = models.ForeignKey('self', blank=True, null=True) I want Django to sort the categories with respect to their hierarchy, for example: Parent 1 Child 1 Parent 2 Child 1 I did so...
[ "I do not see any disadvantes using an app like django-mptt. In fact the methods provided by it are optimized to give you a maximum in performance when doing queries with hierarchical structures. No reason for me to worry about maintainability and/or performance and it is quite easy to use!\n", "MPTT or treebeard...
[ 4, 4, 2 ]
[]
[]
[ "django", "django_mptt", "hierarchy", "python" ]
stackoverflow_0004334302_django_django_mptt_hierarchy_python.txt
Q: comparing lists with lists Possible Duplicate: may i know how can we compare lists ok i m making a game poker card evaluator and i am storing its values in list of list and each list is containing the values like the [rate,rank,max] or just [1,2,3] so my question is if i want to know which players has good hand...
comparing lists with lists
Possible Duplicate: may i know how can we compare lists ok i m making a game poker card evaluator and i am storing its values in list of list and each list is containing the values like the [rate,rank,max] or just [1,2,3] so my question is if i want to know which players has good hand mean good list for example by ...
[ "list1 == list2 will return True, if every element in list1 equals the corresponding element in list2.\nFor example:\n>>> a = [1, 2, 3]\n>>> b = [1, 2, 3]\n>>> a == b\nTrue\n>>> a = [1, 4, 3]\n>>> b = [1, 2, 3]\n>>> a == b\nFalse\n\nlist1 > list2 will return True if, in the first pair of unequal corresponding eleme...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004334397_python.txt
Q: How to not specify default parameters in python? I'm working with a python package (MySQLdb). The connect method has lots of positional parameters, most of which have defaults, but some aren't easy to deduce. How can I only specify the parameters I want? i.e. if a connect method has the following signature: connec...
How to not specify default parameters in python?
I'm working with a python package (MySQLdb). The connect method has lots of positional parameters, most of which have defaults, but some aren't easy to deduce. How can I only specify the parameters I want? i.e. if a connect method has the following signature: connect(username, password, socket, timeout) and socket has...
[ "Try this:\nconnect(username='tom', password='passwd12', timeout=3)\n\nFor more information please see Using Optional and Named Arguments.\n", "It's better to use keyword arguments rather than positional parameters in this case. \nAs is obvious\nconnect ('tom', 'passwd12, None, 3)\n\nis a lot less understandable ...
[ 5, 2, 1 ]
[]
[]
[ "function", "python", "syntax" ]
stackoverflow_0004334678_function_python_syntax.txt
Q: Python/Tkinter: Customize horizontal padding between image and text in Label widget? Is there a way to customize the horizontal padding between an image and text in a Label widget when compound=left or right? The 2 ways I can think of are: Use PIL to dynamically add columns of pixels to an image Insert or append ...
Python/Tkinter: Customize horizontal padding between image and text in Label widget?
Is there a way to customize the horizontal padding between an image and text in a Label widget when compound=left or right? The 2 ways I can think of are: Use PIL to dynamically add columns of pixels to an image Insert or append spaces to the text= option of the label to force the separation of image and text What I'...
[ "There is no built-in way to do what you want. Your own suggestions are good. Another option is to create a frame, and place separate image and label widgets in the frame. You then have complete control of the placement of the widgets\n" ]
[ 0 ]
[]
[]
[ "image", "label", "python", "tkinter" ]
stackoverflow_0004333359_image_label_python_tkinter.txt
Q: error 00865! ArcMap geoprocessing. Raster to Polygon I am trying to write a python script to process image files into shapefiles and then to buffer these files with a 5 meter buffer. I first made the script in model builder in arcmap but I am trying to run it for multiple image files, all beginning with the letter...
error 00865! ArcMap geoprocessing. Raster to Polygon
I am trying to write a python script to process image files into shapefiles and then to buffer these files with a 5 meter buffer. I first made the script in model builder in arcmap but I am trying to run it for multiple image files, all beginning with the letters LG. I keep getting the error 00865, which states that th...
[ "I don't know where you're running the script from, but when you call gp.RasterToPolygon_conversion, you're only giving it the file name, not the full path. If the file's not in the working directory, it won't find it. Try replacing the line:\nInRaster = filename_zero + \".png\"\n\nWith:\nInRaster = os.path.join(ro...
[ 0 ]
[]
[]
[ "arcmap", "python" ]
stackoverflow_0004333981_arcmap_python.txt
Q: csv module python3.1 Im using the following in Python2.x ; import csv f = open('test.csv', 'wb') writer = csv.writer(f) writer.writerow((fpath, md5sum, size)) # <str>, <str>, <int> This works without any problems. However, when I run this in Python3, I get a TypeError. writer.writerow((fpath, md5sum, size)) Type...
csv module python3.1
Im using the following in Python2.x ; import csv f = open('test.csv', 'wb') writer = csv.writer(f) writer.writerow((fpath, md5sum, size)) # <str>, <str>, <int> This works without any problems. However, when I run this in Python3, I get a TypeError. writer.writerow((fpath, md5sum, size)) TypeError: write() argument 1 ...
[ "f = open('test.csv', 'w', encoding='utf-8', newline='')\n\n" ]
[ 6 ]
[]
[]
[ "csv", "python", "python_3.x" ]
stackoverflow_0004334907_csv_python_python_3.x.txt
Q: Regex pattern with subpattern exceptions (Python) I am using BeautifulSoup to extract tabledata tags from a table. The TD's have a class of either 'a','u','e','available-unavailable' or 'unavailable-available'. (Yes, I know quirky class names but hey...) Here's an example: <tr> <td class="u">4</td> <td class="...
Regex pattern with subpattern exceptions (Python)
I am using BeautifulSoup to extract tabledata tags from a table. The TD's have a class of either 'a','u','e','available-unavailable' or 'unavailable-available'. (Yes, I know quirky class names but hey...) Here's an example: <tr> <td class="u">4</td> <td class="unavailable-available">5</td> <td class="a'>6</td> ...
[ "table.findAll('td', attrs = {\"class\":re.compile(r'(^|\\s)(a|unavailable-available)($|\\s)')})\n\nThis matches start of string or whitespace followed by \"a\" or \"unavailable-available\" followed by whitespace or end of string. So it'll match all these sorts of things\nclass=\"a\"\nclass=\"a ui-xxx\"\nclass=\"ui...
[ 2, 0, 0 ]
[]
[]
[ "python", "regex", "web_scraping" ]
stackoverflow_0004331383_python_regex_web_scraping.txt
Q: Wrap subprocess' stdout/stderr I'd like to both capture and display the output of a process that I invoke through Python's subprocess. I thought I could just pass my file-like object as named parameter stdout and stderr I can see that it accesses the filenoattribute - so it is doing something with the object. Howe...
Wrap subprocess' stdout/stderr
I'd like to both capture and display the output of a process that I invoke through Python's subprocess. I thought I could just pass my file-like object as named parameter stdout and stderr I can see that it accesses the filenoattribute - so it is doing something with the object. However, the write() method is never inv...
[ "Stdin, stdout and stderr of a process need to be real file descriptors. (That is actually not a restriction imposed by Python, but rather how pipes work on the OS level.) So you will need a different solution.\nIf you want to track both stdout an stderr in real time, you will need asynchronous I/O or threads.\n\...
[ 12, 0, 0 ]
[ "Is there a reason you have a class inside a class? And stdout and stderr can take any file like line for example try. So simply passing an open file type or stringIO should be enough to modify the stream\nimport sys\nsys.stdout = open('test.txt','w')\nprint \"Testing!\"\nsys.stdout.write('\\nhehehe')\nsys.stdout =...
[ -2 ]
[ "iostream", "python", "stderr", "stdout", "subprocess" ]
stackoverflow_0004335587_iostream_python_stderr_stdout_subprocess.txt
Q: Implementing and Designing a protocol for client server application I'm just investigating about implementing and designing a protocol, but I'm stucked on how to start! Let's take an example the LDAP protocol, I have the rfc and I have the asn1 grammar specification. Now How can I start developing a server in a s...
Implementing and Designing a protocol for client server application
I'm just investigating about implementing and designing a protocol, but I'm stucked on how to start! Let's take an example the LDAP protocol, I have the rfc and I have the asn1 grammar specification. Now How can I start developing a server in a such a way that a client compliant to the RFC LDAp can communicate with me...
[ "Start with an asn.1 library. Then make a server that does what the RFC says to do. Protocols are like APIs, only you have to implement the guts instead of the wrapper. You communicate LDAP (or FTP) messages over a transport protocol like TCP. If you need help making a server, you might want to look into twisted.\...
[ 2 ]
[]
[]
[ "asn.1", "protocols", "python" ]
stackoverflow_0004335845_asn.1_protocols_python.txt
Q: How to serialize/deserialized pybrain networks? PyBrain is a python library that provides (among other things) easy to use Artificial Neural Networks. I fail to properly serialize/deserialize PyBrain networks using either pickle or cPickle. See the following example: from pybrain.datasets import Superv...
How to serialize/deserialized pybrain networks?
PyBrain is a python library that provides (among other things) easy to use Artificial Neural Networks. I fail to properly serialize/deserialize PyBrain networks using either pickle or cPickle. See the following example: from pybrain.datasets import SupervisedDataSet from pybrain.tools.shortcuts import b...
[ "Cause\nThe mechanism that causes this behavior is the handling of parameters (.params) and derivatives (.derivs) in PyBrain modules: in fact, all network parameters are stored in one array, but the individual Module or Connection objects have access to \"their own\" .params, which, however are just a view on a sli...
[ 11 ]
[]
[]
[ "neural_network", "pickle", "python", "serialization" ]
stackoverflow_0004334941_neural_network_pickle_python_serialization.txt
Q: ForeignKey returns id when editing the form This is my model class Category(models.Model): title = models.ForeignKey(Title, verbose_name="Title") class Meta: ordering = ['title'] def __unicode__(self): return self.title.title I'm using a form to replace the ForegnKey field by a CharFiel...
ForeignKey returns id when editing the form
This is my model class Category(models.Model): title = models.ForeignKey(Title, verbose_name="Title") class Meta: ordering = ['title'] def __unicode__(self): return self.title.title I'm using a form to replace the ForegnKey field by a CharField class CategoryForm(forms.ModelForm): title ...
[ "I hadn't check this solution (i can't create test application now) and i don't sure that it works.\nTry to add exclude = (\"title\", ) as CategoryForm member. Also maybe you'll need to override save() (and maybe other) method of CategoryForm.\n", "I have fixed that by making the title unique and adding to_field ...
[ 0, 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0004335454_django_django_forms_django_models_python.txt
Q: Python logging redirecting stdout from multiple processes I am trying to capture the stderr and stdout of a number of processes and write their outputs to a log file using the python logging module. The code below seems to acheive this. Presently I poll each processes stdout and write to the logger if there is any...
Python logging redirecting stdout from multiple processes
I am trying to capture the stderr and stdout of a number of processes and write their outputs to a log file using the python logging module. The code below seems to acheive this. Presently I poll each processes stdout and write to the logger if there is any data. Is there a better way of doing this. Also I would also l...
[ "Your options here are\n\nNon-blocking I/O: This is what you have done :)\nThe select module: You can use either poll() or select() to dispatch reads for the different inputs.\nThreads: Create a thread for each file descriptor you want to monitor and use blocking I/O. Not advisable for large numbers of file descri...
[ 1 ]
[]
[]
[ "logging", "pipe", "python", "redirect", "stdout" ]
stackoverflow_0004335705_logging_pipe_python_redirect_stdout.txt
Q: django feeds has wrong pub date I have following problem. handlers.py of project's django-piston api: .... # "need" to set this for datetime.strftime() locale.setlocale(locale.LC_TIME,'de_AT.UTF-8') class ItemOverviewHandler(BaseHandler): ... @classmethod def date(self, item): # because of the...
django feeds has wrong pub date
I have following problem. handlers.py of project's django-piston api: .... # "need" to set this for datetime.strftime() locale.setlocale(locale.LC_TIME,'de_AT.UTF-8') class ItemOverviewHandler(BaseHandler): ... @classmethod def date(self, item): # because of the setlocale() call the datestring is i...
[ "this did the trick. but im still open for other suggestions :)\nclass ItemOverviewHandler(BaseHandler):\n ...\n @classmethod\n def date(self, item):\n locale.setlocale(locale.LC_TIME,'de_AT.UTF-8')\n date_string = item.somedatefield.date.strftime(\"%d. %B %Y\")\n locale.setlocale(loca...
[ 0, 0 ]
[]
[]
[ "datetime", "django", "django_piston", "localization", "python" ]
stackoverflow_0004335810_datetime_django_django_piston_localization_python.txt
Q: A unique URLError: Error I am getting I am running my application on my production server and it is giving me this error: File "/usr/lib/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2...
A unique URLError: Error I am getting
I am running my application on my production server and it is giving me this error: File "/usr/lib/python2.6/urllib2.py", line 391, in open response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py", line 409, in _open '_open', req) File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain ...
[ "Can you retrieve the URL in question with wget at your production server? This could be a firewall problem rather than a Python bug.\n", "It seems reasonable that the production machine may be taking significantly longer than your test or local machines perhaps due to under-provisioning or excess load on the pro...
[ 1, 0 ]
[]
[]
[ "apache", "firewall", "production", "python" ]
stackoverflow_0004236916_apache_firewall_production_python.txt
Q: Power spectral density of a signal with gaps? Does anyone know if it is possible to find a power spectral density of a signal with gaps in it. For example (in matlab syntax cause that is what I'm familiar with) ta=1:1000; tb=1200:3000; t=[ta tb]; % this is the timebase signal=randn(size(t)); this is a signa...
Power spectral density of a signal with gaps?
Does anyone know if it is possible to find a power spectral density of a signal with gaps in it. For example (in matlab syntax cause that is what I'm familiar with) ta=1:1000; tb=1200:3000; t=[ta tb]; % this is the timebase signal=randn(size(t)); this is a signal figure(101) plot(t,signal,'.') I'd like to be ...
[ "The Lomb-Scargle periodogram algorithm is usually used to perform analysis on unevenly spaced data (sampled at arbitrary time points) or when a proportion of the data is missing.\nHere's a couple of MATLAB implementations:\n\nlombscargle.m (FEX)\nLomb (Lomb-Scargle) Periodogram (FEX)\nlomb.m - ECG tools by Gari Cl...
[ 6, 0, 0 ]
[]
[]
[ "math", "matlab", "python", "signal_processing" ]
stackoverflow_0004333299_math_matlab_python_signal_processing.txt
Q: how to save a value from cgi.parse_multipart here is my code. query = cgi.parse_multipart(rfile, pdict) upfilecontent = query.get('file') here, I want to save upfilecontent[0] to a file in binary mode. TIA A: Since the value is already a str, all you have to do is open the file in binary mode and .write() it: w...
how to save a value from cgi.parse_multipart
here is my code. query = cgi.parse_multipart(rfile, pdict) upfilecontent = query.get('file') here, I want to save upfilecontent[0] to a file in binary mode. TIA
[ "Since the value is already a str, all you have to do is open the file in binary mode and .write() it:\nwith file('name.bin', 'wb') as f: # 'w' for writing, 'b' for binary\n f.write(d['key_1'])\n\nIf you wanted to re-interpret the text as actually being some kind of hex dump, or something else, then you'll have ...
[ 2, 0, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0004336290_cgi_python.txt
Q: Matplotlib in Python - Drawing shapes and animating them So I'm representing a token ring network (doing the simulation in SimPy), I'm a totally newbie to matplotlib, but I was told that it'd be really good for representing my simulation visually. So I googled around and found out how to draw shapes and lines - us...
Matplotlib in Python - Drawing shapes and animating them
So I'm representing a token ring network (doing the simulation in SimPy), I'm a totally newbie to matplotlib, but I was told that it'd be really good for representing my simulation visually. So I googled around and found out how to draw shapes and lines - using add_patch and add_line respectively to the axes (I believe...
[ "Replicating your image using the plot method:\nfrom pylab import *\n\npoints = []\npoints.append((-0.25, -1.0))\npoints.append((0.7, -0.7))\npoints.append((1,0))\npoints.append((0.7,1))\npoints.append((-0.25,1.2))\npoints.append((-1,0.5))\npoints.append((-1,-0.5))\npoints.append((-0.25, -1.0))\n\na_line = plot(*zi...
[ 4, 2, 1 ]
[]
[]
[ "matplotlib", "networking", "python", "simulation" ]
stackoverflow_0002109265_matplotlib_networking_python_simulation.txt
Q: Python modifying wrong list? I'm trying to generate a list of primes using the this method. I need to loop through every number 2...n and check it for multiples of 2...n. For some reason, the wrong list seems to be getting modified. import sys import argparse import math parser = argparse.ArgumentParser(descripti...
Python modifying wrong list?
I'm trying to generate a list of primes using the this method. I need to loop through every number 2...n and check it for multiples of 2...n. For some reason, the wrong list seems to be getting modified. import sys import argparse import math parser = argparse.ArgumentParser(description='find the largest prime factor ...
[ "You're not making copies. You're using references, so copy1, copy2, and copy3 all refer to the same list -- sieve. If you want to copy, use:\ncopy1 = sieve[:]\n\nwhich will create a copy of sieve and assign it to copy1.\n", "You need to use\ncopy1 = sieve[:] # tried making extra copies. . .\ncopy2 = sieve[:]\nco...
[ 7, 2, 2, 2, 1 ]
[]
[]
[ "list", "nested_loops", "primes", "python" ]
stackoverflow_0004337106_list_nested_loops_primes_python.txt
Q: How do I turn this into a one line generator? My best attempts have failed: for s in self.services: for m in s.messages: yield m A: (m for s in self.services for m in s.messages) ... as counter-intuitive as it seems. A: itertools.chain.from_iterable(s.messages for s in self.services)
How do I turn this into a one line generator?
My best attempts have failed: for s in self.services: for m in s.messages: yield m
[ "(m for s in self.services for m in s.messages)\n... as counter-intuitive as it seems.\n", "itertools.chain.from_iterable(s.messages for s in self.services)\n" ]
[ 7, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004337520_python.txt
Q: Boost::Python bindings for classes with inheritance I'm trying to figure whats wrong with some autogenerated (with Pyste) boost::python code, but have no luck so far. There is C++ library, Magick++, which provides two classes, Magick::Drawable and Magick::DrawableRectangle: https://www.imagemagick.org/subversion/I...
Boost::Python bindings for classes with inheritance
I'm trying to figure whats wrong with some autogenerated (with Pyste) boost::python code, but have no luck so far. There is C++ library, Magick++, which provides two classes, Magick::Drawable and Magick::DrawableRectangle: https://www.imagemagick.org/subversion/ImageMagick/trunk/Magick++/lib/Magick++/Drawable.h class M...
[ "If you want BP to implicitly convert objects foy you , you must tell BP that thay are implicitly convertable. put something like this in your bp::code:\nboost::python::implicitly_convertible<SourceType,DestType>();\n\nI do not know how to induce Pyste to do this.\n" ]
[ 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0004332398_boost_boost_python_c++_python.txt
Q: Using facebook graph api, fetching users tagged in photo and realted photos We have got a requirement for facebook based application, wherein We need to fetch a given photo. Identify all the users tagged in that photo and then... Fetch all the photos in which any of the tagged user is appearing. Can anyone ple...
Using facebook graph api, fetching users tagged in photo and realted photos
We have got a requirement for facebook based application, wherein We need to fetch a given photo. Identify all the users tagged in that photo and then... Fetch all the photos in which any of the tagged user is appearing. Can anyone please suggest how to achieve this using facebook's graph api? Thanks and Regards
[ "You can access photo properties, including tags, as per the Graph API documentation (http://developers.facebook.com/docs/reference/api/photo).\nTo fetch all the photos of a given user, you will need to request the user_photo_video_tags extended permission from them when they authorize your application.\nIf all pho...
[ 3 ]
[]
[]
[ "facebook", "facebook_graph_api", "php", "python" ]
stackoverflow_0004324337_facebook_facebook_graph_api_php_python.txt
Q: What is the best way to use python to serve web pages in IIS 6.0 I have an IIS 6.0 web server that I currently use to serve some vanilla ASP pages, and I'm finding ASP somewhat limited. I use python quite a bit for automation tasks, and various other things, and would like to begin using it with IIS to serve web p...
What is the best way to use python to serve web pages in IIS 6.0
I have an IIS 6.0 web server that I currently use to serve some vanilla ASP pages, and I'm finding ASP somewhat limited. I use python quite a bit for automation tasks, and various other things, and would like to begin using it with IIS to serve web pages. My question is this: What is the best way to do this? I define b...
[ "\"Using Python Scripts with IIS\"\n" ]
[ 1 ]
[]
[]
[ "iis", "isapi", "python", "wsgi" ]
stackoverflow_0004338317_iis_isapi_python_wsgi.txt
Q: Regular expression to match all words ending with and containing three 'e's I am trying to write a regular expression that matches all words so that the only vowel is e and there are exactly three e's in the word, am writing this in python. I tried writing (?= e){3}[^aiou]* but it didn't work. A: You want thre...
Regular expression to match all words ending with and containing three 'e's
I am trying to write a regular expression that matches all words so that the only vowel is e and there are exactly three e's in the word, am writing this in python. I tried writing (?= e){3}[^aiou]* but it didn't work.
[ "You want three e's, such that the stuff in between consists of non-vowels. You want a word, i.e. stuff that has a word boundary on either side.\nThus: a word boundary, zero or more non-vowels, an e, zero or more non-vowels, an e, zero or more non-vowels, an e, zero or more non-vowels, and a word boundary. But we c...
[ 6, 2, 0, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004338181_python_regex.txt
Q: replacing all regex matches in single line I have dynamic regexp in which I don't know in advance how many groups it has I would like to replace all matches with xml tags example re.sub("(this).*(string)","this is my string",'<markup>\anygroup</markup>') >> "<markup>this</markup> is my <markup>string</markup>" is...
replacing all regex matches in single line
I have dynamic regexp in which I don't know in advance how many groups it has I would like to replace all matches with xml tags example re.sub("(this).*(string)","this is my string",'<markup>\anygroup</markup>') >> "<markup>this</markup> is my <markup>string</markup>" is that even possible in single line?
[ "For a constant regexp like in your example, do\nre.sub(\"(this)(.*)(string)\",\n r'<markup>\\1</markup>\\2<markup>\\3</markup>',\n text)\n\nNote that you need to enclose .* in parentheses as well if you don't want do lose it.\nNow if you don't know what the regexp looks like, it's more difficult, but s...
[ 39, 9, 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0004338032_python_regex.txt
Q: Declaring types for complex data structures in python I am quite new to python programming (C/C++ background). I'm writing code where I need to use complex data structures like dictionaries of dictionaries of lists. The issue is that when I must use these objects I barely remember their structure and so how to acc...
Declaring types for complex data structures in python
I am quite new to python programming (C/C++ background). I'm writing code where I need to use complex data structures like dictionaries of dictionaries of lists. The issue is that when I must use these objects I barely remember their structure and so how to access them. This makes it difficult to resume working on code...
[ "If you use docstrings in your classes then you can use help(vargoeshere) to see how to use it.\n", "Whatever you do, do NOT, I repeat, do NOT use Hungarian Notation! It causes severe brain & bit rot.\nSo, what can you do? Python and C/C++ are quite different. In C++ you typically handle polymorphic calls like so...
[ 3, 2, 1, 0 ]
[]
[]
[ "data_structures", "python", "types" ]
stackoverflow_0004337736_data_structures_python_types.txt
Q: In emacs python-mode customize multi-line statement indentation I am using the python-mode shipped with emacs 23. I want to customize the auto-indentation of mult-line statements. For example currently emacs prefers the following my_var = [ 'val1', 'val2', 'val3', ] I would prefer my_var = [ '...
In emacs python-mode customize multi-line statement indentation
I am using the python-mode shipped with emacs 23. I want to customize the auto-indentation of mult-line statements. For example currently emacs prefers the following my_var = [ 'val1', 'val2', 'val3', ] I would prefer my_var = [ 'val1', 'val2', 'val3', ] Also, when creating functions with ...
[ "Something like this, perhaps?\n(defadvice python-calculate-indentation (around outdent-closing-brackets)\n \"Handle lines beginning with a closing bracket and indent them so that\nthey line up with the line containing the corresponding opening bracket.\"\n (save-excursion\n (beginning-of-line)\n (let ((syn...
[ 11, 1 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0004293074_emacs_python.txt
Q: How Awful is My Decorator? I recently created a @sequenceable decorator, that can be applied to any function that takes one argument, and causes it to automatically be applicable to any sequence. This is the code (Python 2.5): def sequenceable(func): def newfunc(arg): if hasattr(arg, '__iter__'): ...
How Awful is My Decorator?
I recently created a @sequenceable decorator, that can be applied to any function that takes one argument, and causes it to automatically be applicable to any sequence. This is the code (Python 2.5): def sequenceable(func): def newfunc(arg): if hasattr(arg, '__iter__'): if isinstance(arg, dict):...
[ "This is a terrible idea. This is essentially loose typing. Duck-typing is as far as this \nstuff should be taken, IMO.\nConsider this:\ndef pluralize(f):\n def on_seq(seq):\n return [f(x) for x in seq]\n def on_dict(d):\n return dict((k, f(v)) for k, v in d.iteritems())\n f.on_dict = on_dic...
[ 8, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004339099_python.txt
Q: Deserialize list of nested dictionaries to a simpler form How I can deserialize this : [{'fields': {'active': 1, 'image': 'http://img.rasset.ie/0003db75-150.jpg', 'name': 'Bad Fellas', 'position': 0, 'url': 'http://www.rte.ie/tv/programmes/bad_fellas.html'}, ...
Deserialize list of nested dictionaries to a simpler form
How I can deserialize this : [{'fields': {'active': 1, 'image': 'http://img.rasset.ie/0003db75-150.jpg', 'name': 'Bad Fellas', 'position': 0, 'url': 'http://www.rte.ie/tv/programmes/bad_fellas.html'}, 'model': 'rte_site.show', 'pk': 1}, {'fields': {'active': ...
[ ">>> l = [{\"pk\": d[\"pk\"], \"url\": d[\"fields\"][\"url\"], \"image\": d[\"fields\"][\"image\"], \"name\": d[\"fields\"][\"name\"]} for d in l]\n>>> new_data = dict((d[\"pk\"], d) for d in l)\n>>> new_data \n{1: {'url': 'http://www.rte.ie/tv/programmes/bad_fellas.html', 'pk': 1, 'image': 'http://img.rasset.ie/00...
[ 1, 0 ]
[]
[]
[ "dictionary", "django", "parsing", "python", "serialization" ]
stackoverflow_0004339168_dictionary_django_parsing_python_serialization.txt
Q: Can I cleanse a numpy array without a loop? Perhaps not such a big deal, but it breaks my heart to follow this: deltas = data[1:] - data[:-1] with this: for i in range(len(deltas)): if deltas[i] < 0: deltas[i] = 0 if deltas[i] > 100: deltas[i] = 0 For this particular example...is there a better wa...
Can I cleanse a numpy array without a loop?
Perhaps not such a big deal, but it breaks my heart to follow this: deltas = data[1:] - data[:-1] with this: for i in range(len(deltas)): if deltas[i] < 0: deltas[i] = 0 if deltas[i] > 100: deltas[i] = 0 For this particular example...is there a better way to do the cleansing part? Question part two: ...
[ "import numpy as np\ndeltas=np.diff(data)\ndeltas[deltas<0]=0\ndeltas[deltas>100]=0\n\nAlso possible, and a bit quicker is \ndeltas[(deltas<0) | (deltas>100)]=0\n\n", "Try using numpy.vectorize to apply a function to each element of the numpy array.\n" ]
[ 9, 1 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0004339273_numpy_python.txt
Q: Python Object awareness of being in an array? Is there a way in Python for an object to 'know' what its array element id is? I.e 6 in an array, and the object itself prints out its own array element number, so '0,1,2,3,4,5' A: In a word, no... A: No. The object could be inside everything and multiple objects ...
Python Object awareness of being in an array?
Is there a way in Python for an object to 'know' what its array element id is? I.e 6 in an array, and the object itself prints out its own array element number, so '0,1,2,3,4,5'
[ "In a word, no...\n", "No. The object could be inside everything and multiple objects at the same time, so it can't know unless you tell it.\n", "Just to be pedantic: in general, no...\nbut technically it is possible for some (specific) objects, which are part of some arrays to \"know their position\"...\nclass...
[ 2, 2, 0, 0, 0 ]
[ "If the object knows the list it is part of, it could find out by doing the_list.index(self). Otherwise, no.\n" ]
[ -1 ]
[ "arrays", "object", "oop", "python" ]
stackoverflow_0004338474_arrays_object_oop_python.txt
Q: Python: have urllib skip failed connection Using a Nokia N900 , I have a urllib.urlopen statement that I want to be skipped if the server is offline. (If it fails to connect > proceed to next line of code ) . How should / could this be done in Python? A: try: urllib.urlopen("http://fgsfds.fgsfds") except IOE...
Python: have urllib skip failed connection
Using a Nokia N900 , I have a urllib.urlopen statement that I want to be skipped if the server is offline. (If it fails to connect > proceed to next line of code ) . How should / could this be done in Python?
[ "try:\n urllib.urlopen(\"http://fgsfds.fgsfds\")\nexcept IOError:\n pass\n\n", "According to the urllib documentation, it will raise IOError if the connection can't be made.\ntry:\n urllib.urlopen(url)\nexcept IOError:\n # exception handling goes here if you want it\n pass\nelse:\n DoSomethingUs...
[ 3, 3, 3 ]
[]
[]
[ "python", "urllib" ]
stackoverflow_0004339439_python_urllib.txt
Q: Remove unicode strings in rendered template I'm trying to return a json like object under this address: http://ntt.vipserv.org/data/shows but as a result I'm getting : {'1': {'url': u'http://www.rte.ie/tv/crimecall/', 'image': u'http://img.rasset.ie/0002c8d0-250.jpg', 'id': u'2', 'name': u'Crimecall'}} How to get ...
Remove unicode strings in rendered template
I'm trying to return a json like object under this address: http://ntt.vipserv.org/data/shows but as a result I'm getting : {'1': {'url': u'http://www.rte.ie/tv/crimecall/', 'image': u'http://img.rasset.ie/0002c8d0-250.jpg', 'id': u'2', 'name': u'Crimecall'}} How to get rid fo the unicode strings ? My code: objects = S...
[ "I'd suggest using the json module instead of trying to write a JSON encoder yourself. This will correctly format the strings in double quotes and without the u in front of the string.\n" ]
[ 3 ]
[]
[]
[ "django", "python", "unicode", "unicode_string" ]
stackoverflow_0004339689_django_python_unicode_unicode_string.txt
Q: How can I see if a child exists in Python? I have an lxml object called item and it may have a child called item.brand, however it's possible that there is none as this is returned from an API. How can I check this in Python? A: Try hasattr().
How can I see if a child exists in Python?
I have an lxml object called item and it may have a child called item.brand, however it's possible that there is none as this is returned from an API. How can I check this in Python?
[ "Try hasattr().\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0004339708_python.txt
Q: Serious instability with pygtk 2.22 and python 2.6 Has anybody come across this? I've taken the GTK HelloWorld sample. It runs fine. However, if i import win32ui, then it does not shutdown properly (as explained in this question ). There are other problems. In the process of narrowing down my application to see w...
Serious instability with pygtk 2.22 and python 2.6
Has anybody come across this? I've taken the GTK HelloWorld sample. It runs fine. However, if i import win32ui, then it does not shutdown properly (as explained in this question ). There are other problems. In the process of narrowing down my application to see what caused it to not shutdown, I came upon a point where...
[ "I've tried this on a different install of Win7 64-bit on a different computer, and it worked fine. So it's some strange thing with the hardware/other software on a particular computer. Probably nothing gtk or win32 related.\n" ]
[ 0 ]
[]
[]
[ "crash", "debugging", "gtk", "pygtk", "python" ]
stackoverflow_0004326710_crash_debugging_gtk_pygtk_python.txt
Q: Create a dovecot SHA1 digest using bash or python or some other linux command-line tool Our dovecot and email server authenticate users using SHA1 digests. We can't really change the current digest because we have so many users and don't want to have to have them re-create all their passwords. We would like an eas...
Create a dovecot SHA1 digest using bash or python or some other linux command-line tool
Our dovecot and email server authenticate users using SHA1 digests. We can't really change the current digest because we have so many users and don't want to have to have them re-create all their passwords. We would like an easier way to create a digest to put into the database for our users (and eventually create a we...
[ "You need to base64 encode the binary digest to get it into their format.\n>>> import hashlib\n>>> import base64\n\n>>> p = hashlib.sha1('password')\n>>> base64.b64encode(p.digest())\n'W6ph5Mm5Pz8GgiULbPgzG37mj9g='\n\nEDIT: By the way if you'd prefer to do this from a terminal/bash script, you can do \n$ echo -n '...
[ 7, 1 ]
[]
[]
[ "bash", "python", "sha1" ]
stackoverflow_0004339736_bash_python_sha1.txt
Q: ARP missing from the module scapy i am trying to use scapy in python while i try to import the scapy import scapy its just fine but the line scapy.ARP() causes a Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'ARP' a dir(scapy) produces '['__builti...
ARP missing from the module scapy
i am trying to use scapy in python while i try to import the scapy import scapy its just fine but the line scapy.ARP() causes a Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'ARP' a dir(scapy) produces '['__builtins__', '__doc__', '__file__', '__name__...
[ "got it , from the version v.2 onward the it should be used as from scapy.all import *\n" ]
[ 2 ]
[]
[]
[ "python", "scapy" ]
stackoverflow_0004339745_python_scapy.txt
Q: How to slice a list in Python Suppose I have a list with X elements [4,76,2,8,6,4,3,7,2,1...] I'd like the first 5 elements. Unless it has less than 5 elements. [4,76,2,8,6] How to do that? A: You just subindex it with [:5] indicating that you want (up to) the first 5 elements. >>> [1,2,3,4,5,6,7,8][:5] [1, 2...
How to slice a list in Python
Suppose I have a list with X elements [4,76,2,8,6,4,3,7,2,1...] I'd like the first 5 elements. Unless it has less than 5 elements. [4,76,2,8,6] How to do that?
[ "You just subindex it with [:5] indicating that you want (up to) the first 5 elements.\n>>> [1,2,3,4,5,6,7,8][:5]\n[1, 2, 3, 4, 5]\n>>> [1,2,3][:5]\n[1, 2, 3]\n>>> x = [6,7,8,9,10,11,12]\n>>> x[:5]\n[6, 7, 8, 9, 10]\n\nAlso, putting the colon on the right of the number means count from the nth element onwards -- do...
[ 116, 46, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001534939_list_python.txt
Q: Can't return appended value from within a Python process I am running Python 2.6.5 on Ubuntu 8.10. For a project I am working on, I need to run several processes concurrently and save each of their outputs into their own respective lists. Since I can't return the output value directly from the process, I am passin...
Can't return appended value from within a Python process
I am running Python 2.6.5 on Ubuntu 8.10. For a project I am working on, I need to run several processes concurrently and save each of their outputs into their own respective lists. Since I can't return the output value directly from the process, I am passing the output list as an argument to my target function and app...
[ "When you use separate processes, each process gets its own copy of everything in memory. That's why the parent process never sees anything in its outputs: each child process is appending to its own copy of outputs.\nYou need to use some form of interprocess communication. Python's multiprocessing library supplies ...
[ 3, 0 ]
[]
[]
[ "append", "list", "process", "python" ]
stackoverflow_0004338732_append_list_process_python.txt
Q: Fastest Way to Round to the Nearest 5/100ths I have numbers that I want to go from: 1.215145156155 => 1.2 1.368161685161 => 1.35 1.578414616868 => 1.6 (*Note: the hundredths place should not be marked if it is zero.) What's the fastest way to do this? This is what I have right now, and it is not fast enough: def ...
Fastest Way to Round to the Nearest 5/100ths
I have numbers that I want to go from: 1.215145156155 => 1.2 1.368161685161 => 1.35 1.578414616868 => 1.6 (*Note: the hundredths place should not be marked if it is zero.) What's the fastest way to do this? This is what I have right now, and it is not fast enough: def rounder(v): v = str(round(float(v),2)) if ...
[ "Scale, round, unscale.\nround(20*v)/20\n\nI should warn you that the behaviour might surprise you:\n>>> round(20*1.368161685161)/20\n1.3500000000000001\n\nThe rounding is working correctly, but IEEE numbers can't represent 1.35 exactly. Python 2.7 is smarter about this and will choose the simplest representation, ...
[ 11, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004340322_python.txt
Q: How to encapsulate JSON in parentheses? I have this code : objects = Event.objects.all() i = 0 dict = {} small_dict = {} for o in objects: small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image} dict[str(i+1)] = small_dict small_dict = {} return HttpResponse( simplejson.dumps(dic...
How to encapsulate JSON in parentheses?
I have this code : objects = Event.objects.all() i = 0 dict = {} small_dict = {} for o in objects: small_dict = {'id': o.id, 'url': o.url, 'name': o.name, 'image': o.image} dict[str(i+1)] = small_dict small_dict = {} return HttpResponse( simplejson.dumps(dict), content_type = 'application/javascrip...
[ "\nThe MIME type of JSON is \"application/json\".\nIf you have problems parsing it in PHP, then it's a PHP problem. Don't add parens on the server side, but rather add them before parsing the string in PHP. I guess you know how to concatenate in PHP, right? Anyway, I don't understand what your problem is - don't yo...
[ 2, 0 ]
[]
[]
[ "django", "eval", "json", "python", "simplejson" ]
stackoverflow_0004340112_django_eval_json_python_simplejson.txt
Q: Generating a default value with the Google App Engine Bulkloader I have successfully used the bulkloader with my project before, but I recently added a new field to timestamp when the record was modified. This new field is giving me trouble, though, because it's defaulting to null. Short of manually inserting th...
Generating a default value with the Google App Engine Bulkloader
I have successfully used the bulkloader with my project before, but I recently added a new field to timestamp when the record was modified. This new field is giving me trouble, though, because it's defaulting to null. Short of manually inserting the timestamp in the csv before importing it, is there a way I can inser...
[ "Defining a custom conversion function, as you did, is the correct method. You don't have to modify transform.py, though - put the function in a file in your own app, and import it in the yaml file's python_preamble.\n" ]
[ 1 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0004339325_bulkloader_google_app_engine_python.txt
Q: Django model form not producing expected HTML I have a modelform that doesn't produce (some of) the HTML that (should) represent the model fields. As you can see from the output at the bottom, it's just outputting a blank line where it should be outputting the title and presumably a browse button (or something--r...
Django model form not producing expected HTML
I have a modelform that doesn't produce (some of) the HTML that (should) represent the model fields. As you can see from the output at the bottom, it's just outputting a blank line where it should be outputting the title and presumably a browse button (or something--right?) for the filefield. #views.py def upload_file...
[ "Actually on second thought your mistake is in declaring your model UploadFile (after doublechecking due to lack of a response). You are supposed to use models.CharField not forms.CharField. Thus your model doesn't have any content; hence the ModelForm doesn't have any fields (it didn't arise as an error just in ...
[ 5 ]
[]
[]
[ "django", "file", "forms", "python", "upload" ]
stackoverflow_0004340202_django_file_forms_python_upload.txt
Q: Setting values of an array to -inf in Python with scipy/numpy I have an array that looks like this: a = [ -22 347 4448 294 835 4439 587 326] I want to set its 0 or smaller values to -inf. I tried the following: a[where(a <= 0)] = -inf when I do this, I get the error: OverflowError: cannot convert float infi...
Setting values of an array to -inf in Python with scipy/numpy
I have an array that looks like this: a = [ -22 347 4448 294 835 4439 587 326] I want to set its 0 or smaller values to -inf. I tried the following: a[where(a <= 0)] = -inf when I do this, I get the error: OverflowError: cannot convert float infinity to integer Any idea why this is and how I can fix it? the "wh...
[ "Your array a is an array of integers. Integers can't represent infinity -- only floating point numbers can. So there are to fixes:\n\nUse an array of floating point numbers instead.\nUse a large negative integer value, e.g. -2147483648 if you are using 32-bit integers. Of course that's not the same as -infinity...
[ 10, 2 ]
[]
[]
[ "numpy", "python", "scipy" ]
stackoverflow_0004340787_numpy_python_scipy.txt