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: Logging Handlers: How do I make sure I am not making two? Edit: I ended up answering the beef of my question so that I can have a working logging module. However, I still have a related question. See my answer below. I am trying to implement logging by always logging to the temporary directory of whatever os I a...
Logging Handlers: How do I make sure I am not making two?
Edit: I ended up answering the beef of my question so that I can have a working logging module. However, I still have a related question. See my answer below. I am trying to implement logging by always logging to the temporary directory of whatever os I am in. To do this I have written the following function. import...
[ "I ended up answering my own question. Here is the code\nglobal IS_SETUP \nIS_SETUP = False\ndef setuplogger(filename = 'python.log', directory = None, format = 'L:%(name)s M:%(module)s T:%(asctime)s > %(levelname)s: %(message)s'):\n global IS_SETUP\n if directory == None:\n fd, fname = tempfile.mkstemp()...
[ 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0005627219_logging_python.txt
Q: Apparent time-travelling via python's multiprocessing module: surely I've done something wrong I use python for video-game-like experiments in cognitive science. I'm testing out a device that detects eye movements via EOG, and this device talks to the computer via USB. To ensure that data is being continuously rea...
Apparent time-travelling via python's multiprocessing module: surely I've done something wrong
I use python for video-game-like experiments in cognitive science. I'm testing out a device that detects eye movements via EOG, and this device talks to the computer via USB. To ensure that data is being continuously read from the USB while the experiment does other things (like changing the display, etc), I thought I'...
[ "Despite working with multiprocessing, your queue still uses synchronization objects (two locks and a semaphore) and the put method spawns another thread (based on the 2.7 source). So GIL contention (and other fun stuff) may come into play, as suggested by BlueRaja. You can try playing with sys.checkinterval and se...
[ 1, 0 ]
[]
[]
[ "multiprocessing", "python", "r" ]
stackoverflow_0005626341_multiprocessing_python_r.txt
Q: Invalid mode: wb when trying to upload file using Django and AJAX So I'm trying to use an ajax file upload form with Django and running into an issue with FileIO. Specifically, with BufferedWriter( FileIO( filename, "wb" ) ) as dest: results in ValueError: invalid mode: wb I'm running Python 2.6/Django 1.3 loca...
Invalid mode: wb when trying to upload file using Django and AJAX
So I'm trying to use an ajax file upload form with Django and running into an issue with FileIO. Specifically, with BufferedWriter( FileIO( filename, "wb" ) ) as dest: results in ValueError: invalid mode: wb I'm running Python 2.6/Django 1.3 locally on OSX 10.6.7. I tried chmod +X to the directory I'm targeting with...
[ "http://docs.python.org/release/2.6.6/library/io.html#raw-file-i-o\n\nFileIO represents a file containing bytes data. It implements the RawIOBase interface (and therefore the IOBase interface, too).\nThe mode can be 'r', 'w' or 'a' for reading (default), writing, or appending. The file will be created if it doesn’t...
[ 1 ]
[]
[]
[ "django", "macos", "python" ]
stackoverflow_0005628575_django_macos_python.txt
Q: KeyboardHookProc in DLL doesn't do anything when called from python I've been trying to write a DLL in C. Install hook sets up the KeyboardProc. Calling the InstallHook() and UninstallHook() functions from Python always returns a 0, which I guess is because my callback function KeyboardProc isn't working. The foll...
KeyboardHookProc in DLL doesn't do anything when called from python
I've been trying to write a DLL in C. Install hook sets up the KeyboardProc. Calling the InstallHook() and UninstallHook() functions from Python always returns a 0, which I guess is because my callback function KeyboardProc isn't working. The following is my C code for the DLL: #include "stdafx.h" #include <windows.h> ...
[ "hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, 0);\n\nSetWindowsHookEx requires a hModule - save the hModule from DllMain and pass it here. (You can pass NULL only if the thread id is your own thread.)\nOne exception to this is for the _LL hook types; these don't need a hmodule param since these...
[ 1 ]
[]
[]
[ "c", "dll", "hook", "python", "winapi" ]
stackoverflow_0005628614_c_dll_hook_python_winapi.txt
Q: Sending file via email to MMS for ATT One can send messages to an AT&T customer via [10-digit-cell-numer]@txt.att.net from their email client. I tried to send a file to my iPhone using this method (specifically an audio file) to no avail. The message came through but the file attachment was not present. A: It se...
Sending file via email to MMS for ATT
One can send messages to an AT&T customer via [10-digit-cell-numer]@txt.att.net from their email client. I tried to send a file to my iPhone using this method (specifically an audio file) to no avail. The message came through but the file attachment was not present.
[ "It seems you can send MMS messages to @mms.att.net\nThat was easy.\n" ]
[ 2 ]
[]
[]
[ "email", "mms", "python", "scripting" ]
stackoverflow_0005628715_email_mms_python_scripting.txt
Q: wxPython: Making something expand How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window? A: The short answer: use a sizer with a proportion of 1 and the wx.Expand tag. So here I am in the init of a panel sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canv...
wxPython: Making something expand
How do I make any wxPython widget (like wx.Panel or wx.Button) automatically expand to fill its parent window?
[ "The short answer: use a sizer with a proportion of 1 and the wx.Expand tag.\nSo here I am in the init of a panel\nsizer = wx.BoxSizer(wx.VERTICAL)\nsizer.Add(self.canvas, 1, wx.EXPAND)\nself.SetSizer(sizer)\n\n", "this shows how you can expand child panel with frame resize\nit also show how you can switch two p...
[ 7, 1, 0 ]
[]
[]
[ "python", "user_interface", "wxpython" ]
stackoverflow_0001034399_python_user_interface_wxpython.txt
Q: How to click a javascripted' radio button and fetch next page using Python (urllib2)? [WebScrape, selenium] I am struggling with this. I have a fully tested python script. I have to make a small change wherein I have to first click on a radio button which in turn automatically executes a javascript function forwar...
How to click a javascripted' radio button and fetch next page using Python (urllib2)? [WebScrape, selenium]
I am struggling with this. I have a fully tested python script. I have to make a small change wherein I have to first click on a radio button which in turn automatically executes a javascript function forwarding the page to a search form. My working platform : Linux Language : Python Radio button code : <input type="...
[ "Instead of trying to automate clicking the JavaScript button, which is difficult in Python, try monitoring what request is sent and then replicate this. There are various firefox extensions that will help you do this, such as TamperData, Firebug, and LiveHttp.\n" ]
[ 0 ]
[]
[]
[ "javascript", "python", "screen_scraping", "selenium" ]
stackoverflow_0003251380_javascript_python_screen_scraping_selenium.txt
Q: sleep() function (python) if data.find('!google') != -1: nick = data.split('!')[ 0 ].replace(':','') try: gs = GoogleSearch(args) gs.results_per_page = 1 results = gs.get_results() for res in results: sck.send('PRIVMSG ' + chan + " " + res.title.encode("utf8") + '\r...
sleep() function (python)
if data.find('!google') != -1: nick = data.split('!')[ 0 ].replace(':','') try: gs = GoogleSearch(args) gs.results_per_page = 1 results = gs.get_results() for res in results: sck.send('PRIVMSG ' + chan + " " + res.title.encode("utf8") + '\r\n') sck.send('PRIVMSG...
[ "There is a sleep function inside the time module.\nHowever, to make your script not block, you can call the time function in the time module and store that. If the current time is less than that plus, say, five seconds, don't allow them to use it.\nFor example:\nlast_google = 0\n# somewhere later in the script whe...
[ 2 ]
[]
[]
[ "function", "irc", "python", "sleep", "sockets" ]
stackoverflow_0005628976_function_irc_python_sleep_sockets.txt
Q: How to modify lxml autolink to be more liberal? I am using the autolink function of the great lxml library as documented here: http://lxml.de/api/lxml.html.clean-module.html My problem is that it only detects urls that start with http://. I would like to use a broader url detection regex like this one: http://dar...
How to modify lxml autolink to be more liberal?
I am using the autolink function of the great lxml library as documented here: http://lxml.de/api/lxml.html.clean-module.html My problem is that it only detects urls that start with http://. I would like to use a broader url detection regex like this one: http://daringfireball.net/2010/07/improved_regex_for_matching_u...
[ "There are two things to do in order to adapt the regexp to lxml's autolink. First wrap the entire url pattern match in a group (?P<body> .. ) - this lets lxml know what goes inside the href=\"\" attribute. \nNext, wrap the host part in a (?<host> .. ) group and pass avoid_hosts=[] parameter when you call the auto...
[ 2, 0 ]
[]
[]
[ "hyperlink", "lxml", "python", "regex" ]
stackoverflow_0005628622_hyperlink_lxml_python_regex.txt
Q: Execute Django fixtures on table creation Is there a way to execute a Django fixture just once - when the appropriate table is created? I have some initial data that should be put in the app tables, but once the tables are there, I don't want every ./manage.py syncdb to refresh the data. According to Django docs i...
Execute Django fixtures on table creation
Is there a way to execute a Django fixture just once - when the appropriate table is created? I have some initial data that should be put in the app tables, but once the tables are there, I don't want every ./manage.py syncdb to refresh the data. According to Django docs it seems this can only be done for fixtures in S...
[ "You're going to want to use the post_syncdb signal, and filter/manually load the fixture via the underlying methods when specific apps or models are created.\n" ]
[ 1 ]
[]
[]
[ "django", "fixtures", "initialization", "json", "python" ]
stackoverflow_0005625831_django_fixtures_initialization_json_python.txt
Q: Any way to lower Python memory footprint? i'm developing a python 2.6 (tested both on 2.6.5 and 2.6.6) application which is going to run as a daemon on my VPS. During some tests, i've found out that the app itself it's consuming (during its sleep time, so no activities or allocations whatsoever) about 37.53MB of m...
Any way to lower Python memory footprint?
i'm developing a python 2.6 (tested both on 2.6.5 and 2.6.6) application which is going to run as a daemon on my VPS. During some tests, i've found out that the app itself it's consuming (during its sleep time, so no activities or allocations whatsoever) about 37.53MB of memory. I i've spent the last few hours optimizi...
[ "Are you sure you are not reading the Python virtual memory?\nPython here consumes 3.4MB of private memory.\n" ]
[ 1 ]
[]
[]
[ "garbage_collection", "memory", "python" ]
stackoverflow_0005629140_garbage_collection_memory_python.txt
Q: How to scrape HTTPS javascript web pages I am trying to monitor day-to-day prices from an online catalogue. The site uses HTTPS and generates the catalogue pages with javascript. How can i interface with the site and make it generate the pages I need? I have done this with other sites where the HTML can easily be...
How to scrape HTTPS javascript web pages
I am trying to monitor day-to-day prices from an online catalogue. The site uses HTTPS and generates the catalogue pages with javascript. How can i interface with the site and make it generate the pages I need? I have done this with other sites where the HTML can easily be accessed, I have no problem parseing the HTML...
[ "Take a look at HTMLUnit - a headless Java browser that can be fully controlled by your code. A simple example can be seen here: http://htmlunit.sourceforge.net/gettingStarted.html\n(obligatory warning: by screen-scraping the site, you may be breaking its ToS, and possibly open yourself to lawsuits; check whether y...
[ 11, 1, 1 ]
[]
[]
[ "https", "java", "javascript", "python", "web_scraping" ]
stackoverflow_0005561950_https_java_javascript_python_web_scraping.txt
Q: Scraping a web page with java script in Python i'm working in python 3.2 (newb) on windows machine (though i have ubuntu 10.04 on virtual box if needed, but i prefer to work on the windows machine). Basically i'm able to work with the http module and urlib module to scrape web pages, but only those that don't have...
Scraping a web page with java script in Python
i'm working in python 3.2 (newb) on windows machine (though i have ubuntu 10.04 on virtual box if needed, but i prefer to work on the windows machine). Basically i'm able to work with the http module and urlib module to scrape web pages, but only those that don't have java script document.write("<div....") and the like...
[ "I recommend python's bindings to the webkit library - here is an example. Webkit is cross platform and is used to render webpages in Chrome and Safari. An excellent library.\n", "Use Firebug to see exactly what is being called to get the data to display (a POST or GET url?). I suspect there's an AJAX call that's...
[ 2, 1, 0 ]
[]
[]
[ "javascript", "python", "python_3.x", "web_scraping" ]
stackoverflow_0005338979_javascript_python_python_3.x_web_scraping.txt
Q: nosetests, python I am trying to learn python, the guide I am following is asking me to write a simple 'game', utilizing tuples, lists, and classes. When running the 'nosetests' command, I get the following error: E. ====================================================================== ERROR: tests.LEXICON_tests....
nosetests, python
I am trying to learn python, the guide I am following is asking me to write a simple 'game', utilizing tuples, lists, and classes. When running the 'nosetests' command, I get the following error: E. ====================================================================== ERROR: tests.LEXICON_tests.test_directions -------...
[ "The way methods are called in python is that the object it is called on is passed as the first argument, and the arguments supplied are each pushed down 1. When you call like its a static method (lexicon.scan) instead of an instance method (lex.scan) this first argument is not supplied.\nThe method lexicon.scan r...
[ 2 ]
[]
[]
[ "nosetests", "python" ]
stackoverflow_0005627528_nosetests_python.txt
Q: AJAX in Django with jQuery quite confusing I'm a jQuery noob here, please help! Much much appreciated! my urls.py: url('^xhr_test/$','posts.views.xhr_test'), my views.py: def xhr_test(request): if request.is_ajax(): message = "Hello AJAX" else: message = "Hello" return HttpResponse(message) So, very simpl...
AJAX in Django with jQuery quite confusing
I'm a jQuery noob here, please help! Much much appreciated! my urls.py: url('^xhr_test/$','posts.views.xhr_test'), my views.py: def xhr_test(request): if request.is_ajax(): message = "Hello AJAX" else: message = "Hello" return HttpResponse(message) So, very simple. This setup works if one of two versions of my...
[ "Try adding an event.preventDefault(); to your code; e.g.:\n$(document).ready(function() {\n $(\"a\").click(function() {\n event.preventDefault();\n alert(\"hi\");\n $.get(\"xhr_test\", function(data) {\n alert(data);\n });\n });\n});\n<a href=\"\">Click here</a>\n\n" ]
[ 1 ]
[]
[]
[ "ajax", "django", "jquery", "python" ]
stackoverflow_0005629330_ajax_django_jquery_python.txt
Q: Subtracting "variable[#]" with two digits in python? I'm building a script in python to calculate the amount of time in between hours entered by a user Lets say for example I did the following time = input("Enter times:") and the user entered 3,11 to show that the start time was three, and the end time was 11. Th...
Subtracting "variable[#]" with two digits in python?
I'm building a script in python to calculate the amount of time in between hours entered by a user Lets say for example I did the following time = input("Enter times:") and the user entered 3,11 to show that the start time was three, and the end time was 11. Therefore, time would equal 3,11. I want to be able to subtr...
[ "time_input = raw_input(\"Enter times:\")\ntime_parts = time.split(',')\ntime_diff = int(time_parts[1]) - int(time_parts[0])\n\n", "You can use the split method to split a string and assign the individual values to separate variables:\nstart, end = time.split(',')\ntimesub = int(end) - int(start)\n\nIf you want t...
[ 0, 0 ]
[]
[]
[ "python", "subtraction", "time" ]
stackoverflow_0005629452_python_subtraction_time.txt
Q: Validate form A's data by usuing form B's data So I have these two forms. I would like to be able to access the data in form env_form when I am checking add_uRG for my other form. Is it possible to do this? My env form is a very common form through out my app so I would like to keep it separate instead of includin...
Validate form A's data by usuing form B's data
So I have these two forms. I would like to be able to access the data in form env_form when I am checking add_uRG for my other form. Is it possible to do this? My env form is a very common form through out my app so I would like to keep it separate instead of including it on every form. class env_form(forms.Form): ...
[ "You could assign a property on your add_uRG form after you validate the env_form, or you could pass the value to the add_uRG form as a parameter.\n#forms.py\nclass AdduRGForm(forms.Form):\n def __init__(self, *args, **kwargs):\n super(AdduRGForm, self).__init__(*args, **kwargs)\n self.env = None\n...
[ 0, 0 ]
[]
[]
[ "django", "forms", "python" ]
stackoverflow_0005626702_django_forms_python.txt
Q: the time() function (python) if data.find('!google') != -1: nick = data.split('!')[ 0 ].replace(':','') if last_google + 5 > time.time(): sck.send('PRIVMSG ' + chan + " :" + ' Wait a few seconds' + "\r\n") else: last_google = time.time() try: gs = Go...
the time() function (python)
if data.find('!google') != -1: nick = data.split('!')[ 0 ].replace(':','') if last_google + 5 > time.time(): sck.send('PRIVMSG ' + chan + " :" + ' Wait a few seconds' + "\r\n") else: last_google = time.time() try: gs = GoogleSearch(args) g...
[ "Is this all in a loop?\nOne issue is that you set last_google to time.time() at the beginning of your request. If the request is slow, some of that time may already be gone by the time you get to the if statement again.\nA typical 'waiting' block might look something like this:\nwhile time.time() < last_google + ...
[ 0 ]
[]
[]
[ "irc", "python", "sockets", "time" ]
stackoverflow_0005629468_irc_python_sockets_time.txt
Q: How to restart a guess number game I am using python 2.7.1 I would like to be able to restart the game based on user input, so would get the option of restarting, instead of just exit the game and open again. Can someone help me figure out??Thanks import random the_number = random.randrange(10)+1 tries = 0 valid...
How to restart a guess number game
I am using python 2.7.1 I would like to be able to restart the game based on user input, so would get the option of restarting, instead of just exit the game and open again. Can someone help me figure out??Thanks import random the_number = random.randrange(10)+1 tries = 0 valid = False while valid == False: guess...
[ "Put your current code in a function, such as play_game or whatever. Then write a loop that invokes the function until the user has had enough. For example:\ndef global_thermonuclear_war():\n print \"Boom!\"\n\nwhile raw_input(\"Shall we play a game? [y|n] \") == 'y':\n global_thermonuclear_war()\n\n", "Add...
[ 3, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005629389_python.txt
Q: Python script to generate words I'm looking to write a short script that will allow me to generate all possible letter combinations with the parameters I set. For example: __ _ _ n o Parameters: word = 5 letters 4th, 5th letter = n, o 1st letter = any vowel (aeiouy) 2nd, 3rd letter = any letter (abcde...)...
Python script to generate words
I'm looking to write a short script that will allow me to generate all possible letter combinations with the parameters I set. For example: __ _ _ n o Parameters: word = 5 letters 4th, 5th letter = n, o 1st letter = any vowel (aeiouy) 2nd, 3rd letter = any letter (abcde...) in other words, I'm looking to write...
[ "import itertools\nimport string\n\nletter = string.lowercase\nvowel = \"aeiouy\"\n\ndef all_words(*args):\n return (''.join(letters) for letters in itertools.product(*args))\n\nwordlist = list(all_words(vowel, letter, letter, \"n\", \"o\"))\n\nreturns 4056 entries:\n['aaano', 'aabno', 'aacno', 'aadno', 'aaeno'...
[ 5, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005629395_python.txt
Q: pythonic way to filter a dictionary of arrays I have a dictionary that looks something like this: d = { 'a':['a','b','c','d'], 'b':['a','b','c','d'], 'c':['a','b','c','d'], 'd':['a','b','c','d'], } I would like to reduce this dictionary into a new one that contains 2 keys randomly selected f...
pythonic way to filter a dictionary of arrays
I have a dictionary that looks something like this: d = { 'a':['a','b','c','d'], 'b':['a','b','c','d'], 'c':['a','b','c','d'], 'd':['a','b','c','d'], } I would like to reduce this dictionary into a new one that contains 2 keys randomly selected from the full set of keys, and also only contains ...
[ "ks = set(random.sample(d.keys(), 2))\nnd = dict( (k, list(v for v in d[k] if v in ks)) for k in ks )\n\n", "How about the following:\nimport random\nrk = random.sample(d.keys(),2)\nnew_d = {}\nfor k in rk:\n new_d[k] = list(set(d[k]).intersection(rk))\n\n", "Building on FM's, with the underused set type:\n>...
[ 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005629716_python.txt
Q: Python HTML parsing with beautiful soup and filtering stop words I am parsing out specific information from a website into a file. Right now the program I have looks at a webpage, and find the right HTML tag and parses out the right contents. Now I want to further filter these "results". For example, on the site ...
Python HTML parsing with beautiful soup and filtering stop words
I am parsing out specific information from a website into a file. Right now the program I have looks at a webpage, and find the right HTML tag and parses out the right contents. Now I want to further filter these "results". For example, on the site : http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx I...
[ "import urllib2\nimport BeautifulSoup\nimport string\n\nbadwords = set([\n 'cup','cups',\n 'clove','cloves',\n 'tsp','teaspoon','teaspoons',\n 'tbsp','tablespoon','tablespoons',\n 'minced'\n])\n\ndef cleanIngred(s):\n # remove leading and trailing whitespace\n s = s.strip()\n # remove number...
[ 3 ]
[]
[]
[ "beautifulsoup", "html", "parsing", "python" ]
stackoverflow_0005629773_beautifulsoup_html_parsing_python.txt
Q: Loading DLL from embedded python code in c The crux of my problem is this: I am developing code on Windows XP in C with MS Visual Studio 10.0, and I need to embed Python to do some plotting, file management, and some other things. I had problems with sys.path finding my Pure-Python modules, but I have fixed the p...
Loading DLL from embedded python code in c
The crux of my problem is this: I am developing code on Windows XP in C with MS Visual Studio 10.0, and I need to embed Python to do some plotting, file management, and some other things. I had problems with sys.path finding my Pure-Python modules, but I have fixed the problem by modifying PYTHONPATH. Now, my problem ...
[ "Try this, it works on my machine. \nCreate a simple Windows console application in Visual Studio 2010 (remove precompiled headers option in the wizard). Replace the generated code with this one :\n#include <Python.h>\n\nint main(int argc, char *argv[]) {\n Py_Initialize();\n\n PyRun_SimpleString(\"import ssl...
[ 2, 0, 0 ]
[]
[]
[ "c", "embedding", "python" ]
stackoverflow_0005589056_c_embedding_python.txt
Q: Embedding Windows Python in Cygwin/GCC C++ program I am currently working on a Cygwin/GCC application written in C++. The application requires embedding of python to run plug-ins, I've successfully embedded using the Cygwin python libraries and was able to run simple python files as part of the program. However, t...
Embedding Windows Python in Cygwin/GCC C++ program
I am currently working on a Cygwin/GCC application written in C++. The application requires embedding of python to run plug-ins, I've successfully embedded using the Cygwin python libraries and was able to run simple python files as part of the program. However, the python files now require the use of a windows GUI fra...
[ "Not a direct answer, but you could split the system into 2 processes - the Cygwin one (Python & C++, no wxPython) and the win32 one (Python & wxPython) and communicate between them with RPyC, XML-RPC, etc.\n", "It looks like you have a 32 bit / 64 bit mismatch. \nYou are running code on a 64bit machine (because ...
[ 0, 0 ]
[]
[]
[ "c++", "cygwin", "embedding", "python", "windows" ]
stackoverflow_0001308558_c++_cygwin_embedding_python_windows.txt
Q: how to run python script to display webpage for auto login on one click I have my python script which I guess is fine. I want to keep the script on the desktop and upon one click I want the script to run and open a browser(IE or firefox or chrome) and perform the script i.e. to log-in to a website. import urllib,...
how to run python script to display webpage for auto login on one click
I have my python script which I guess is fine. I want to keep the script on the desktop and upon one click I want the script to run and open a browser(IE or firefox or chrome) and perform the script i.e. to log-in to a website. import urllib, urllib2, cookielib username = 'xyzusername' password = 'xyzpassword' cj...
[ "Hmmmm, your script is logging into a web site, but it's not opening a browser.\nIf you want to open a browser, you might be better off looking at Selenium:\n\nhttp://coreygoldberg.blogspot.com/2009/09/selenium-rc-with-python-in-30-seconds.html\nhttp://jimmyg.org/blog/2009/getting-started-with-selenium-and-python.h...
[ 0 ]
[]
[]
[ "authentication", "browser", "python" ]
stackoverflow_0005629740_authentication_browser_python.txt
Q: Python: Find item in multidimensional list I have a list of lists, a snippet of which is below: x_attrib = [] self.x_attrib.append(["Is_virtual", False, 'virtual', 'flag']) self.x_attrib.append(["X_pos", None, 'pos/x', 'attrib']) self.x_attrib.append(["Y_pos", None, 'pos/y', 'attrib']) I want make a functional th...
Python: Find item in multidimensional list
I have a list of lists, a snippet of which is below: x_attrib = [] self.x_attrib.append(["Is_virtual", False, 'virtual', 'flag']) self.x_attrib.append(["X_pos", None, 'pos/x', 'attrib']) self.x_attrib.append(["Y_pos", None, 'pos/y', 'attrib']) I want make a functional that returns the index of the item at the first po...
[ "If I understand correctly, you need to something like this:\ndef find_it(key):\n for index, sublist in enumerate(lists):\n if sublist[0] == key:\n return index\n\nHaving said that your code looks like you are solving the more general problem incorrectly. i.e. that list look like a bad idea. With...
[ 4 ]
[]
[]
[ "find", "list", "multidimensional_array", "python" ]
stackoverflow_0005630186_find_list_multidimensional_array_python.txt
Q: Can't run monkeyrunner script - java.lang.IllegalArgumentException: Bad level I tried this but it shows me the middle finger: ~/Software/android-sdk-linux_x86-1.6_r1/tools$ sudo ./monkeyrunner -v help.py Exception in thread "main" java.lang.IllegalArgumentException: Bad level "help.py" at java.util.logg...
Can't run monkeyrunner script - java.lang.IllegalArgumentException: Bad level
I tried this but it shows me the middle finger: ~/Software/android-sdk-linux_x86-1.6_r1/tools$ sudo ./monkeyrunner -v help.py Exception in thread "main" java.lang.IllegalArgumentException: Bad level "help.py" at java.util.logging.Level.parse(Level.java:336) at com.android.monkeyrunner.MonkeyRunnerOptio...
[ "Why sudo ?\nYou shouldn't use it.\nThe other problem is that you are missing the log level for -v:\nUsage: monkeyrunner [options] SCRIPT_FILE\n\n -s MonkeyServer IP Address.\n -p MonkeyServer TCP Port.\n -v MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE,...
[ 1 ]
[]
[]
[ "android", "monkeyrunner", "python" ]
stackoverflow_0005621591_android_monkeyrunner_python.txt
Q: Secure Options for storing Openssl password on a server (Linux, Python, CherryPy) I've implemented a HTTP server (CherryPy and Python) that receives an encrypted file from a client (Android). I'm using OpenSSL to decrypt the uploaded file. Currently I'm using openssl -enc -pass file:password.txt -in encryptedfile...
Secure Options for storing Openssl password on a server (Linux, Python, CherryPy)
I've implemented a HTTP server (CherryPy and Python) that receives an encrypted file from a client (Android). I'm using OpenSSL to decrypt the uploaded file. Currently I'm using openssl -enc -pass file:password.txt -in encryptedfile -out decryptedfile to perform to decryption on the server side. As you can see the pass...
[ "Pass it through a higher FD, and use that FD in the command line. Note that you'll need to use the preexec_fn argument to set up the FD before the process gets run.\nsubprocess.Popen(['openssl', ..., 'file:/dev/fd/12', ...], ...,\n preexec_fn=passtofd12(password), ...)\n\n", "For the sake of privacy for a user ...
[ 0, 0 ]
[]
[]
[ "linux", "openssl", "passwords", "python", "security" ]
stackoverflow_0005630152_linux_openssl_passwords_python_security.txt
Q: UnboundLocalError: Decorator with default parameters Here is my decorator code. I'm getting UnboundLocalError for some reason but I couldn't find it. >>> def validate(schema=None): def wrap(f): def _f(*args, **kwargs): if not schema: schema = f.__name__ ...
UnboundLocalError: Decorator with default parameters
Here is my decorator code. I'm getting UnboundLocalError for some reason but I couldn't find it. >>> def validate(schema=None): def wrap(f): def _f(*args, **kwargs): if not schema: schema = f.__name__ print schema return f() return ...
[ "The compiler can't determine schema's proper scope. Either use nonlocal schema (3.x) within _f() or change the definition of _f() slightly:\ndef _f(self, schema=schema, *args, **kwargs):\n\n" ]
[ 11 ]
[]
[]
[ "decorator", "python" ]
stackoverflow_0005630409_decorator_python.txt
Q: Join two for loops, separated by a print statement into one In the following code, everything is working as expected. It gets a 4 character long user input that ends with 0. And simply adds stores in a dictonary the occurances of vowels and consonants. input ="" #get input from user while 4 < len(input) or 4 > ...
Join two for loops, separated by a print statement into one
In the following code, everything is working as expected. It gets a 4 character long user input that ends with 0. And simply adds stores in a dictonary the occurances of vowels and consonants. input ="" #get input from user while 4 < len(input) or 4 > len(input) or input[-1] != "0": #string has to be 4 char long and...
[ "Another way to write your code might be something like this:\nprint \", \".join(k for k, v in occurrences.items() if k != \"consonants\" and v > 0),\nprint \"were inserted\"\nprint \", \".join(str(v) for k, v in occurrences.items() if k != \"consonants\" and v > 0),\nprint \"times respectively\"\n\nYou can shorten...
[ 2, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0005630392_for_loop_python.txt
Q: Is it possible to pass a python string by reference through ctypes? I'm sorry, but I generally have a hard time reading the current ctypes docs... If I have a C function that takes a const char * pointer, and I know it will neither modify the passed in string, nor keep a reference to it beyond the function call, i...
Is it possible to pass a python string by reference through ctypes?
I'm sorry, but I generally have a hard time reading the current ctypes docs... If I have a C function that takes a const char * pointer, and I know it will neither modify the passed in string, nor keep a reference to it beyond the function call, it really makes sense to pass in a pointer directly to the bytes of a pyth...
[ "\nAssigning a new value to instances of the pointer types c_char_p, c_wchar_p, and c_void_p changes the memory location they point to, not the contents of the memory block (of course not, because Python strings are immutable):\n>>> s = \"Hello, World\"\n>>> c_s = c_char_p(s)\n>>> print c_s\nc_char_p('Hello, World'...
[ 17, 6 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0005576925_ctypes_python.txt
Q: Python grabbing JSON from POST method I have an Android appthat originally posted some strings in json format to a python cgi script, which all worked fine. The problem is when the json object contains lists, then python (Using simplejson) when it gets them is still treating them as a big string Here is a text dum...
Python grabbing JSON from POST method
I have an Android appthat originally posted some strings in json format to a python cgi script, which all worked fine. The problem is when the json object contains lists, then python (Using simplejson) when it gets them is still treating them as a big string Here is a text dump of the json once it reaches python before...
[ "Tasks is just a big string. To be a valid list, it would have to be [\"1 task\", \"2 task\", \"3 task\"]\n\nSame goes for Prob1 and Prob2. To be a valid list, the brackets should not be enclosed in quotes.\n" ]
[ 1 ]
[]
[]
[ "android", "json", "python" ]
stackoverflow_0005630870_android_json_python.txt
Q: Implementing Load Balancing Using Python I am doing some research this summer and working on parallelizing pre-existing code. The main focus right now is a way to load balance the code so that it will run more efficient on the cluster. The current task is to make a proof of concept that creates several processes w...
Implementing Load Balancing Using Python
I am doing some research this summer and working on parallelizing pre-existing code. The main focus right now is a way to load balance the code so that it will run more efficient on the cluster. The current task is to make a proof of concept that creates several processes with each one having their own stack available ...
[ "Here's a simple way to do this.\n\nCreate a single common shared queue of work to do. This application\nwill fill this queue with work to do.\nCreate an application which gets one item from the queue, and does the work.\n\nThis is the single-producer-multiple-consumer design. It works well and can swamp your mac...
[ 13 ]
[ "use multiprocessing module \n" ]
[ -2 ]
[ "module", "parallel_processing", "python" ]
stackoverflow_0003321722_module_parallel_processing_python.txt
Q: Unicode and UTF-8 encoding issue with Scrapy XPath selector text I'm using Scrapy and Python (as part of a Django project) to scrape a site with German content. I have libxml2 installed as the backend for Scrapy selectors. If I extract the word 'Hüftsitz' (this is how it is displayed on the site) through selector...
Unicode and UTF-8 encoding issue with Scrapy XPath selector text
I'm using Scrapy and Python (as part of a Django project) to scrape a site with German content. I have libxml2 installed as the backend for Scrapy selectors. If I extract the word 'Hüftsitz' (this is how it is displayed on the site) through selectors, I get: u'H\ufffd\ufffdftsitz' (Scrapy XPath selectors return Unicod...
[ "u'\\ufffd' is the \"unicode replacement character\", which is usually printed as a question mark inside a black triangle. NOT a u umlaut. So the problem must be somewhere upstream. Check what encoding the web page headers say are being returned and verify that it is in fact, what it says it is. \nThe unicode rep...
[ 3, 3, 1 ]
[]
[]
[ "django", "python", "scrapy", "unicode", "utf_8" ]
stackoverflow_0005627868_django_python_scrapy_unicode_utf_8.txt
Q: Different behavior due to different "looping styles" I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently. 1) with open(file, "a+b", 1) as f: #Navigate to the MARKER w...
Different behavior due to different "looping styles"
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently. 1) with open(file, "a+b", 1) as f: #Navigate to the MARKER while True: line = f.readline() if MARKER in line: ...
[ "The clue seems to be in this bit of Python's C source -- Python 2.7 seems to use a 8 KB readahead buffer for for line in file:.\n", "Generally, a for x in y type of statement expects y not to change within the loop. You are breaking that contract.\n", "From Python documentation, 5. Built-in Types / 5.9. File O...
[ 3, 2, 2, 0 ]
[]
[]
[ "file", "io", "python" ]
stackoverflow_0005631463_file_io_python.txt
Q: image upload in django Could someone point me towards an example on image uploading in django. I have tried the documentation and the djangobook, but all I found were examples with file uploads. I am new to Django and I would like to first try to see how an example works before writing my own form. Thanks a lot. ...
image upload in django
Could someone point me towards an example on image uploading in django. I have tried the documentation and the djangobook, but all I found were examples with file uploads. I am new to Django and I would like to first try to see how an example works before writing my own form. Thanks a lot.
[ "You can check out these links. just see this meets your requirements.\nUsing ajax and django\nDjango Photologue\n", "Maybe this will help a little:\nforms.py\nclass SomeForm(forms.Form):\n picture = forms.ImageField(required=False)\n\nviews.py\nif request.method == 'POST':\n form = SomeForm(request.POST, r...
[ 1, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005627375_django_python.txt
Q: Sending an Email via Python I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way? import smtplib import string SUBJECT = "Test email from Python" TO = "python@mydomain.com"...
Sending an Email via Python
I'm attempting to send an email with Python. From what I can tell, all the following code needs is a valid recipient and a host HOST. I'm unsure on how to get the host. What is the simplest way? import smtplib import string SUBJECT = "Test email from Python" TO = "python@mydomain.com" FROM = "python@mydomain.com" tex...
[ "The HOST is the SMTP relay provided by your ISP (typically related to the domain name of your from address). If you use a desktop mail client, you'll be able to see the SMTP server listed in your mail settings. If you're hosting using shared hosting, your hosting provider should be able to provide an SMTP server...
[ 1 ]
[ "We are not in the position to tell you a valid mail host aka smtp server. You should know where to send your mail to: either ask your organization IT or ask your mail provider.\n" ]
[ -1 ]
[ "email", "python", "smtplib" ]
stackoverflow_0005631771_email_python_smtplib.txt
Q: limiting a search (python) from shodan import WebAPI SHODAN_API_KEY = "MY API KEY" api = WebAPI(SHODAN_API_KEY) results = api.exploitdb.search('PHP') print 'Results found: %s' % results['total'] for exploit in results['matches']: print '%s:' % (exploit['description']) How can I limit the search to only...
limiting a search (python)
from shodan import WebAPI SHODAN_API_KEY = "MY API KEY" api = WebAPI(SHODAN_API_KEY) results = api.exploitdb.search('PHP') print 'Results found: %s' % results['total'] for exploit in results['matches']: print '%s:' % (exploit['description']) How can I limit the search to only print the first 5 results?
[ "for exploit in results['matches'][:5]:\n print '%s:' % (exploit['description'])\n\n", "Take your time and learn the Python basics about lists and \"slicing\" in particular:\nhttp://diveintopython.ep.io/native-datatypes.html\n" ]
[ 5, 0 ]
[]
[]
[ "asp.net_web_api", "python", "search", "string" ]
stackoverflow_0005631891_asp.net_web_api_python_search_string.txt
Q: python file was renamed, how to get 'rename time' lets say that some files were renamed by Python script, is it possible to get this 'rename time' using Python (It can be seen in Far Manager)? (Windows) It seems it is not possible through STAT, etc Any ideas ? A: If you're asking how to get the modification date...
python file was renamed, how to get 'rename time'
lets say that some files were renamed by Python script, is it possible to get this 'rename time' using Python (It can be seen in Far Manager)? (Windows) It seems it is not possible through STAT, etc Any ideas ?
[ "If you're asking how to get the modification date of the file, it's this:\n>>> import os\n>>> import datetime\n>>> stat = os.stat('/tmp/bacon')\n>>> print datetime.datetime.fromtimestamp(stat.st_mtime)\n2011-03-31 08:02:52.953873\n\n", "It is impossible, OS does not store such info about files. Answered by 'atzz...
[ 0, 0 ]
[]
[]
[ "file_management", "python" ]
stackoverflow_0005498704_file_management_python.txt
Q: OpenCV for ARM (Beagleboard) using YUYV instead of JPEG compression? I am running OpenCV on a Beagleboard xM with a webcam under Ubuntu. The webcam runs fine, but only in YUYV mode. I.e., luvcview using jpeg compression has many frames which are half cut-off, incorrect colors etc. But luvcview -f YuYV works perfec...
OpenCV for ARM (Beagleboard) using YUYV instead of JPEG compression?
I am running OpenCV on a Beagleboard xM with a webcam under Ubuntu. The webcam runs fine, but only in YUYV mode. I.e., luvcview using jpeg compression has many frames which are half cut-off, incorrect colors etc. But luvcview -f YuYV works perfectly. Is it possible to disable jpeg compression for OpenCV? I've tried bui...
[ "I am having the same issue. This might help: http://tech.groups.yahoo.com/group/OpenCV/message/77273\nyou can enable SIFT in modules/features2d/src/sift.cpp. you can search for #ifdef arm in the file. commenting the line 51-53 in sift.cpp e.g.: //#define ARM_NO_SIFT\nAlso if you are using a beagle you'll need to r...
[ 2 ]
[]
[]
[ "arm", "beagleboard", "cross_compiling", "opencv", "python" ]
stackoverflow_0004419012_arm_beagleboard_cross_compiling_opencv_python.txt
Q: Python JSON Google Translator extraction problem I am trying to extract the JSON object in python using Simplejson. But I am getting the following error. Traceback (most recent call last): File "Translator.py", line 42, in <module> main() File "Translator.py", line 38, in main parse_json(trans_text) ...
Python JSON Google Translator extraction problem
I am trying to extract the JSON object in python using Simplejson. But I am getting the following error. Traceback (most recent call last): File "Translator.py", line 42, in <module> main() File "Translator.py", line 38, in main parse_json(trans_text) File "Translator.py", line 27, in parse_json resul...
[ "json['translations'] is a list by your definition, so its indices must be integers\nto get a list of translations:\ntranslations = [x['translatedText'] for x in json['translations']]\n\nanother way:\ntranslations = map(lambda x: x['translatedText'], json['translations'])\n\n", "json['translations'] is a list of...
[ 1, 0 ]
[]
[]
[ "json", "python", "simplejson" ]
stackoverflow_0005631958_json_python_simplejson.txt
Q: Tix ComboBox causes python2.7 to crash I've been using Tix to create a comboBox and it causes an intermittent crash if the entry box is left empty. I'm new to Python and very new to GUI programming so I've been using example to teach myself stuff. When using the following example code, you should be able to ente...
Tix ComboBox causes python2.7 to crash
I've been using Tix to create a comboBox and it causes an intermittent crash if the entry box is left empty. I'm new to Python and very new to GUI programming so I've been using example to teach myself stuff. When using the following example code, you should be able to enter a value into the entry box or select form ...
[ "I am not Tix expert, but this should fix the problem:\ntkMessageBox.showinfo('info', self.combo.entry.get())\n\nIn between the lines, I would recommend using wxPython for learning GUI programming. It was great for me as a learning environment.\nimport wx\n\nclass MainWin(wx.Frame):\n def __init__(self, *args, *...
[ 1 ]
[]
[]
[ "python", "tix" ]
stackoverflow_0005044572_python_tix.txt
Q: How do I bring a PyGTK Button to the front? I have a gtk.Table to which I've attached a number of gtk.Buttons, some of which overlap others. I can't figure out how to bring a specific button to the front, however. How do I do it? A: I've struggled with an issue similar to this, and came to the conclusion that ...
How do I bring a PyGTK Button to the front?
I have a gtk.Table to which I've attached a number of gtk.Buttons, some of which overlap others. I can't figure out how to bring a specific button to the front, however. How do I do it?
[ "I've struggled with an issue similar to this, and came to the conclusion that it wasn't possible in an officially documented manner... gtk.Table doesn't seem to have been designed to deal with the idea that things might overlap. Widgets seemed to be rendered in an order related to (but not exactly) the order they ...
[ 1, 0 ]
[]
[]
[ "pygtk", "python" ]
stackoverflow_0005584398_pygtk_python.txt
Q: Materialized Key in SQLAlchemy often when you have a table with selfrefernece, say in a tree, you have an attribute as a foreign key, which is pointing to the primary key of the table. (like in the Adjacency List Relationships example from the docs) However, I have a natural key, which works like this: "" is the r...
Materialized Key in SQLAlchemy
often when you have a table with selfrefernece, say in a tree, you have an attribute as a foreign key, which is pointing to the primary key of the table. (like in the Adjacency List Relationships example from the docs) However, I have a natural key, which works like this: "" is the root "a", "b", "c" etc. are the chil...
[ "I do understand the constraint of the question, but why are you trying to avoid having an extra key? Sure, it is redundant information, but depending you your data (number of row, average length of the keys), having additional keys might actually improve your performance on SELECTs and you would be able to use eag...
[ 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0005471687_python_sqlalchemy.txt
Q: What is the difference between sqlite3 and sqlalchemy? Beginner question- what is the difference between sqlite and sqlalchemy? A: They're apples and oranges. Sqlite is a database storage engine, which can be better compared with things such as MySQL, PostgreSQL, Oracle, MSSQL, etc. It is used to store and retr...
What is the difference between sqlite3 and sqlalchemy?
Beginner question- what is the difference between sqlite and sqlalchemy?
[ "They're apples and oranges.\nSqlite is a database storage engine, which can be better compared with things such as MySQL, PostgreSQL, Oracle, MSSQL, etc. It is used to store and retrieve structured data from files.\nSQLAlchemy is a Python library that provides an object relational mapper (ORM). It does what it sug...
[ 74, 21 ]
[]
[]
[ "python", "sqlalchemy", "sqlite" ]
stackoverflow_0005632677_python_sqlalchemy_sqlite.txt
Q: Help creating exam grading program in Python I am trying to create a program that reads multiple choice answers from a txt file and compares them to a set answer key. This is what I have so far but the problem is that that when I run it, the answer key gets stuck on a single letter throughout the life of the prog...
Help creating exam grading program in Python
I am trying to create a program that reads multiple choice answers from a txt file and compares them to a set answer key. This is what I have so far but the problem is that that when I run it, the answer key gets stuck on a single letter throughout the life of the program. I have put a print statement right after the...
[ "The problem is that you're not nesting the loops properly. \nThis loop runs first, and ends up setting answer to the last line of the answerKey.\nfor line in answerKey:\n answer = line.split()\n\nThe for line in studentExam: loop runs afterwards, but answer doesn't change in this loop and will stay the same.\nT...
[ 3, 2, 0 ]
[]
[]
[ "line", "list", "python", "split" ]
stackoverflow_0005632704_line_list_python_split.txt
Q: How to Convert Tuple to Dictionary? i'm using Python 2.5 and Win XP. i have a tuple as below: >>> a (None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}') >>> a[1] '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}' >>> i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq A:...
How to Convert Tuple to Dictionary?
i'm using Python 2.5 and Win XP. i have a tuple as below: >>> a (None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}') >>> a[1] '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}' >>> i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq
[ ">>> import ast\n>>> ast.literal_eval(a[1])\n{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}\n\n", "First split the string on comma.\nIterate over all parts.\nSplit each part on colon.\nConvert the strings into integers.\nAdd the second integer as value for the first integer as key.\n", "If you trust the source of a[1] ...
[ 5, 3, 1, 1, 0 ]
[]
[]
[ "dictionary", "python", "tuples" ]
stackoverflow_0005633095_dictionary_python_tuples.txt
Q: How can I update a source file (with classes) in interactive python Simple python question. When in interactive mode, I'm test an imported file, let's say I use: from foo import foo But in the same time I edit the code. How can I update the script which is once loaded into interactive python? When I try to reimpo...
How can I update a source file (with classes) in interactive python
Simple python question. When in interactive mode, I'm test an imported file, let's say I use: from foo import foo But in the same time I edit the code. How can I update the script which is once loaded into interactive python? When I try to reimport it, nothing happens and I'm still on my old files. Thanks for any help...
[ "Did you take a look at this question? \nReloading a changed python file in emacs python shell\nLibraries in your python path can be easily updated with reload(modulename).\n" ]
[ 2 ]
[]
[]
[ "interactive", "python" ]
stackoverflow_0005633567_interactive_python.txt
Q: Is it possible to inject shell/python commands from a configuration file? Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated: var1,data1 var2,data2 var3,data3 So if the user can manipulate this meta data...
Is it possible to inject shell/python commands from a configuration file?
Say you have a some meta data for a custom file format that your python app reads. Something like a csv with variables that can change as the file is manipulated: var1,data1 var2,data2 var3,data3 So if the user can manipulate this meta data, do you have to worry about someone crafting a malformed meta data file that w...
[ "If you are doing what you say there (plain text, just reading and parsing a simple format), you will be safe. As you indicate, Python is generally safe from the more mundane memory corruption errors that C developers can create if they are not careful. The SQL injection scenario you note is not a concern when simp...
[ 4, 0 ]
[]
[]
[ "python", "security" ]
stackoverflow_0005632770_python_security.txt
Q: Python: truncate a file to 100 lines or less I'm pretty new to Python - just wondering if there was a library function or easy way to truncate a file to the first 100 lines or less? A: with open("my.file", "r+") as f: [f.readline() for x in range(100)] f.truncate() EDIT A 5 % speed increase can be had ...
Python: truncate a file to 100 lines or less
I'm pretty new to Python - just wondering if there was a library function or easy way to truncate a file to the first 100 lines or less?
[ "with open(\"my.file\", \"r+\") as f:\n [f.readline() for x in range(100)]\n f.truncate()\n\nEDIT A 5 % speed increase can be had by instead using the xrange iterator and not storing the entire list:\nwith open(\"my.file\", \"r+\") as f:\n for x in xrange(100):\n f.readline()\n f.truncate()\n\n",...
[ 12, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005633988_python.txt
Q: Google App Engine Datastore multiline entries not displayed as multiline in HTML Using the Google App Store guestbook demo as an example, when entering a entry over multiple lines and storing it, when read back and displayed it appears on one single line. How can we make it appear excactly as it was originally ent...
Google App Engine Datastore multiline entries not displayed as multiline in HTML
Using the Google App Store guestbook demo as an example, when entering a entry over multiple lines and storing it, when read back and displayed it appears on one single line. How can we make it appear excactly as it was originally entered, over multiple lines? The databasemodel is like this: class Greeting(db.Model): ...
[ "Html ignores EOL special characters like \\r\\n or \\n.\nHere are some options:\n\nReplace the special characters with the proper html <br> tag\nWrap the multiline text inside a <pre> tag\nIn case you are using webapp templating, try with {{greeting.content|linebreaks}} as suggested by @wooble \nSet white-space:pr...
[ 8 ]
[]
[]
[ "google_app_engine", "multiline", "python" ]
stackoverflow_0005633265_google_app_engine_multiline_python.txt
Q: Topic prediction using Latent Dirichlet Allocation I have used LDA on a corpus of documents and found some Topics. The output of my code is two matrices containing probabilities. one doc-topic probabilities and the other word-topic probabilities. But I actually don't know how to use these results to predict the to...
Topic prediction using Latent Dirichlet Allocation
I have used LDA on a corpus of documents and found some Topics. The output of my code is two matrices containing probabilities. one doc-topic probabilities and the other word-topic probabilities. But I actually don't know how to use these results to predict the topic of a new document. I am using Gibbs sampling. Does a...
[ "The Java implementation http://www.arbylon.net/projects/lda-j/lda-j-src-20050325.zip has an short example program in src\\org\\knowceans\\lda\\SearchEnglet.java. I hope you are a bit familiar with java and the code helps you.\nThe original paper http://jmlr.csail.mit.edu/papers/volume3/blei03a/blei03a.pdf describe...
[ 3 ]
[]
[]
[ "prediction", "python", "topic_modeling" ]
stackoverflow_0005582867_prediction_python_topic_modeling.txt
Q: In python, super() is always called first in a method. Are there situations where it should be called later? Are there situations where you want to do some processing before you call super()? This is a contrived example. Are there better examples? Is this considered pythonic? class Base(object): def __init__...
In python, super() is always called first in a method. Are there situations where it should be called later?
Are there situations where you want to do some processing before you call super()? This is a contrived example. Are there better examples? Is this considered pythonic? class Base(object): def __init__(self, name): print "Base %s created" % name self._name = name class UpperBase(A): """ Simila...
[ "Sometimes you need to validate the arguments before calling super():\nclass UpperBase(Base):\n def __init__(self, name):\n if not name_valid(name):\n raise ValueError()\n super(UpperBase, self).__init__(name)\n\nI don't see why this wouldn't be pythonic, because it's the easiest way to ...
[ 51 ]
[]
[]
[ "python", "super" ]
stackoverflow_0005634221_python_super.txt
Q: Django code only works in debug Very confused about this one. This code in views.py works, but only when I'm debugging using Pycharm. If I just do runserver I get a 500 error. views.py: def add_post(request): if request.method == 'POST': form = PostForm(request.POST) cd = form.cleaned_data if form.is_...
Django code only works in debug
Very confused about this one. This code in views.py works, but only when I'm debugging using Pycharm. If I just do runserver I get a 500 error. views.py: def add_post(request): if request.method == 'POST': form = PostForm(request.POST) cd = form.cleaned_data if form.is_valid(): print "valid" ...
[ "The cleaned_data attribute becomes available after calling is_valid() on a form. You should move cd = form.cleaned_data to below the if.\n", "A Django form's cleaned_data attribute isn't accessible until you call is_valid() on the form.\nform = PostForm(request.POST)\n\nif form.is_valid():\n cd = form.cleaned...
[ 4, 0 ]
[]
[]
[ "debugging", "django", "python" ]
stackoverflow_0005634291_debugging_django_python.txt
Q: django msg.send() not working as it should when i send mail through django view (code below): subject = "Audit report for all staff " email_msg = "Hello Everyone," + '\n \n' + subject + '\n \n' + 'Thanks \n-Admin' report_name = response['Content-Disposition'].split('=')[1] msg = EmailMessage( sub...
django msg.send() not working as it should
when i send mail through django view (code below): subject = "Audit report for all staff " email_msg = "Hello Everyone," + '\n \n' + subject + '\n \n' + 'Thanks \n-Admin' report_name = response['Content-Disposition'].split('=')[1] msg = EmailMessage( subject = subject, body = email_msg, ...
[ "Django does not automatically send to remote servers. It does it through SMTP backend. You need to configure it. \nhttp://docs.djangoproject.com/en/1.3/topics/email/#e-mail-backends\n", "For configuring SMTP server, u have to give something like this in your settings.py [provided SMTP is installed]\nEMAIL_HOST =...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005634140_django_python.txt
Q: The list with most elements I have a list with dictionary as elements. Each dictionary has an entry called type. The type field represents a list. What is the simplest/pythonic way of obtaining the list with the most elements? programmes_by_type = [] programmes_by_type.append({'type' : [1, 2, 3]}) programmes_by_t...
The list with most elements
I have a list with dictionary as elements. Each dictionary has an entry called type. The type field represents a list. What is the simplest/pythonic way of obtaining the list with the most elements? programmes_by_type = [] programmes_by_type.append({'type' : [1, 2, 3]}) programmes_by_type.append({'type' : [2, 5]}) pro...
[ "max([option['type'] for option in programmes_by_type], key=len)\n\n", "max_length = 0\ntype_list = None\n\nfor el in programmes_by_type:\n if len(el) > max_length:\n max_length = len(el)\n type_list = el['type']\n\ntype_list now contains the biggest list.\n" ]
[ 10, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0005634321_dictionary_list_python.txt
Q: Why can't Bouncycastle's PEMReader read this M2Crypto-generated PEM? I use the following Python code, using M2Crypto, to generate an RSA key pair in PEM format: bio = BIO.MemoryBuffer() key_pair = RSA.gen_key(1024, 65537) key_pair.save_key_bio(bio, cipher=None) return bio.read() And the following Java code, using...
Why can't Bouncycastle's PEMReader read this M2Crypto-generated PEM?
I use the following Python code, using M2Crypto, to generate an RSA key pair in PEM format: bio = BIO.MemoryBuffer() key_pair = RSA.gen_key(1024, 65537) key_pair.save_key_bio(bio, cipher=None) return bio.read() And the following Java code, using Bouncycastle, to try to read it: String signPem = ...; PEMReader pemReade...
[ "After taking a debugger to Bouncycastle, I have discovered the \"cause\", but it only puzzles me more; the cast is failing even though all types seem to be correct.\nIf A extends B extends C, why can I cast to A but get a ClassCastException casting to C?\n" ]
[ 1 ]
[]
[]
[ "bouncycastle", "encryption", "java", "m2crypto", "python" ]
stackoverflow_0005623205_bouncycastle_encryption_java_m2crypto_python.txt
Q: Problems in scraping and saving file by eventlet I can use evenlet to scrap img from website but failed to save them into domestic directory. Following is the code. Any one is familiar with the I/O operation in tasklets model? Thanks import pyquery import eventlet from eventlet.green import urllib2 #fetch img url...
Problems in scraping and saving file by eventlet
I can use evenlet to scrap img from website but failed to save them into domestic directory. Following is the code. Any one is familiar with the I/O operation in tasklets model? Thanks import pyquery import eventlet from eventlet.green import urllib2 #fetch img urls............ works fine print "loading page..." html...
[ "Make sure that url is suitable as a filename e.g.:\nimport hashlib\nimport os\n\ndef url2filename(url, ext=''):\n return hashlib.md5(url).hexdigest() + ext # anything that removes '\\/'\n\n# ...\nwith open(os.path.join(\"/head2\", url2filename(url, '.jpg')), 'wb') as f:\n f.write(body)\nprint \"file saved\"...
[ 0 ]
[]
[]
[ "download", "eventlet", "greenlets", "multithreading", "python" ]
stackoverflow_0005632598_download_eventlet_greenlets_multithreading_python.txt
Q: python : Replacing a HTML element depending on its content I have an html document, in which some elements contains stuff that I want to hide (like the Chinese government is doing, except that I just want to hide confidential information). For example say I have : <div> <span> bkhiu jknd o so so so yui iou 78...
python : Replacing a HTML element depending on its content
I have an html document, in which some elements contains stuff that I want to hide (like the Chinese government is doing, except that I just want to hide confidential information). For example say I have : <div> <span> bkhiu jknd o so so so yui iou 789 </span> <span> bkhiu <div> 56 898tr SECRET...
[ "Ok ... I have found a very simple way, using BeautifulSoup :\nimport re\nfrom BeautifulSoup import BeautifulSoup\n\nsoup = BeautifulSoup(my_html)\nnodes_to_censor = soup.findAll(text=re.compile('.*SECRET.*'))\nfor node in nodes_to_censor:\n node.replaceWith('###')\n\n" ]
[ 3 ]
[]
[]
[ "html", "minidom", "python" ]
stackoverflow_0005634522_html_minidom_python.txt
Q: Python get least significant digits from a float (without using string operations) Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6). How do I do that? Thanks PS I do not want to use string operatio...
Python get least significant digits from a float (without using string operations)
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6). How do I do that? Thanks PS I do not want to use string operations even if it would be rather easy to: for any float f: int(str(int(f * 1000))[-10:]) ...
[ ">>> a = 12345.6789\n>>> b = int(a*10000)\n>>> b\n123456789\n>>> c = b % 1000000\n>>> c\n456789\n\nBut - WHY??\n", "Relevant for your string solution is that the float display algorithm changed in python 2.7:\nPython 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \n>>> 12345.6789\n12345.678900000001\n\nPython 2.7.0+ (...
[ 6, 3, 2 ]
[]
[]
[ "bit_manipulation", "floating_point", "int", "python" ]
stackoverflow_0005634714_bit_manipulation_floating_point_int_python.txt
Q: how can I convert a char to variable? In detail: I need this formula to work. string = str(z)+":1.0 "+str(z+1)+":0.0" where z is a variable with a value. will I be able to input this formula into a dictionary value with a specific key. Like dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'} so that when i see...
how can I convert a char to variable?
In detail: I need this formula to work. string = str(z)+":1.0 "+str(z+1)+":0.0" where z is a variable with a value. will I be able to input this formula into a dictionary value with a specific key. Like dicto={'A': 'str(z)+":1.0 "+str(z+1)+":0.0"'} so that when i see a key value 'A' I should be able to use th...
[ "Use lambda function:\nd = { 'A': lambda z: str(z)+\":1.0 \"+str(z+1)+\":0.0\" }\n\nd['A'](5)\n\n# returns: '5:1.0 6:0.0'\n\n", "As I read your question, you wanted something like this:\ndicto = {'A': lambda x: \"{0!s}:1.0 {1!s}:0.0\".format(x, x + 1)}\ndicto['A'](2) # '2:1.0 3:0.0'\n\n" ]
[ 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005635343_python.txt
Q: Django 1.2.3 - Internationalization - makemessages does not detect all strings One more question about Django concerning localization of javascript files. Django provides a small and convenient javascript library which is used like gettext to internationalize strings in javascript files. I set it up successfully (...
Django 1.2.3 - Internationalization - makemessages does not detect all strings
One more question about Django concerning localization of javascript files. Django provides a small and convenient javascript library which is used like gettext to internationalize strings in javascript files. I set it up successfully (at least the interpolate function works) and I could generate the po file for the Fr...
[ "I've just solved the problem of strings not translated at runtime. It came from the fact that my \"locale\" directory was under the project root. I had to add \"my_project_root_dir\" to settings.INSTALLED_APPS to receive a correct javascript catalog.\nFor the problem of not detected strings, I still have no idea a...
[ 1, 1, 0 ]
[]
[]
[ "django", "gettext", "internationalization", "javascript", "python" ]
stackoverflow_0003879177_django_gettext_internationalization_javascript_python.txt
Q: A help in concept and a database query question (Django/Python) I am trying to build a kind of news website for learning purposes. class NewsCategory(models.Model): category = models.CharField(max_length=50) Note: A category can be Soccer, Tennis, business ... User can register to different news category. Th...
A help in concept and a database query question (Django/Python)
I am trying to build a kind of news website for learning purposes. class NewsCategory(models.Model): category = models.CharField(max_length=50) Note: A category can be Soccer, Tennis, business ... User can register to different news category. This choice will be saved in their preferences. class Profile(models.Mo...
[ "You'll need to pass the complete list of categories and also an index of user-selected categories to your template. You don't need to convert the NewsCategory queryset into a list in your view, by the way:\nView\ncategories = NewsCategory.objects.all()\nuser_preferences = [item.id for item in Profile.preference.al...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005635320_django_python.txt
Q: python re.sub with an integer operation I currently have a pattern substitution that does the following: x = re.sub('(\d+)','\g<1>','100') => x = 100 I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is the...
python re.sub with an integer operation
I currently have a pattern substitution that does the following: x = re.sub('(\d+)','\g<1>','100') => x = 100 I need to be able to divide the integer by 10 in the substitution as the pattern and substitution are inputs from database text fields (so I can't use code). Is there a way to do this so that => x = 10 Thanks,...
[ "import re\n\nt = 'a b c 100 200'\n\nf = lambda x: str(int(x.group(0)) / 10)\nre.sub('\\d+', f, t)\n\n# returns 'a b c 10 20'\n\n", "you can do this by passing a function as 2nd argument to re.sub. That function will be called with a MatchObject :\n>>> def repl(mo):\n... return mo.group(0)[:-1]\n... \n>>> impo...
[ 6, 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005635673_python_regex.txt
Q: Calling ActionScript from Python. Is that possible? If swf file is embedded in html it is easy to call ActionScript methods via ExternalInterface using JavaScript. Now I want to use the swf file outside of a browser and still be able to access its methods, but now I want to use Python to call ActionScript. Is it p...
Calling ActionScript from Python. Is that possible?
If swf file is embedded in html it is easy to call ActionScript methods via ExternalInterface using JavaScript. Now I want to use the swf file outside of a browser and still be able to access its methods, but now I want to use Python to call ActionScript. Is it possible? There is so little information about it in the I...
[ "If you want to use the swf in such a manner outside the browser investigate AIR or localconnection.\n[Edit] You can use Python to listen for ExternalInterface events. osflash.org has something you could look into, albeit a little outdate:\nhttp://osflash.org/ext_howto\nor some example Python:\ndef ExternalCall(sel...
[ 1, 0 ]
[]
[]
[ "actionscript_3", "flash", "python" ]
stackoverflow_0005631252_actionscript_3_flash_python.txt
Q: Scraping with Python? I'd like to grab all the index words and its definitions from here. Is it possible to scrape web content with Python? Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'. http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&a...
Scraping with Python?
I'd like to grab all the index words and its definitions from here. Is it possible to scrape web content with Python? Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'. http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&arid=14179&sphra=undefined ...
[ "You should use urllib2 for gettting the URL contents and BeautifulSoup for parsing the HTML/XML.\nExample - retrieving all questions from the StackOverflow.com main page:\nimport urllib2\nfrom BeautifulSoup import BeautifulSoup\n\npage = urllib2.urlopen(\"http://stackoverflow.com\")\nsoup = BeautifulSoup(page)\n\n...
[ 6, 3 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0005635400_python_screen_scraping.txt
Q: how to read an lxml.objectify.ObjectifiedElement object with django-piston? I am trying to make a django-piston API which reads another API and presents it in a different format (reads an XML-only API and presents it in JSON). But I am having trouble, because the way I am doing it I just an empty string. Here is m...
how to read an lxml.objectify.ObjectifiedElement object with django-piston?
I am trying to make a django-piston API which reads another API and presents it in a different format (reads an XML-only API and presents it in JSON). But I am having trouble, because the way I am doing it I just an empty string. Here is my handler: class MyHandler(BaseHandler): methods_allowed = ('GET') def read(self...
[ "It depends on what you need from that lxml.objectify.ObjectifiedElement. If you want to get the text content from that element you can access it via\nmy_node.text\n\nIf you want an attribute value you can access it via:\nmy_node.attrib['nameofattribute']\n\n" ]
[ 1 ]
[]
[]
[ "api", "django", "django_piston", "lxml", "python" ]
stackoverflow_0005502014_api_django_django_piston_lxml_python.txt
Q: Transfer Ipython namespace to ipdb I am in the middle of an ipython session. I've loaded a module foo which contains a function foo.bar. While working, I notice that foo.bar gives some weird output when I feed it some input x, where x is a variable in my local ipython scope. I would like to investigate the behavio...
Transfer Ipython namespace to ipdb
I am in the middle of an ipython session. I've loaded a module foo which contains a function foo.bar. While working, I notice that foo.bar gives some weird output when I feed it some input x, where x is a variable in my local ipython scope. I would like to investigate the behavior in a debugger. How would I set a break...
[ "I believe you can use pdb.runcall in this case:\nimport pdb\npdb.runcall(foo.bar, x)\n\n" ]
[ 5 ]
[]
[]
[ "debugging", "ipython", "python" ]
stackoverflow_0005634700_debugging_ipython_python.txt
Q: inheritance from xmlrpclib.ServerProxy in python Why this code doesn't work ? #!/usr/bin/python2 from xmlrpclib import ServerProxy class ServerProxy1(ServerProxy): def __str__(self): return str(self.__host) proxy = ServerProxy1("http://workshop:58846/") print proxy Original_str_: def __repr__(s...
inheritance from xmlrpclib.ServerProxy in python
Why this code doesn't work ? #!/usr/bin/python2 from xmlrpclib import ServerProxy class ServerProxy1(ServerProxy): def __str__(self): return str(self.__host) proxy = ServerProxy1("http://workshop:58846/") print proxy Original_str_: def __repr__(self): return ( "" % (...
[ "The answer is hiding in this SO post\nThe member self.__host in class ServerProxy was declared using the double-underscore naming that's meant to indicate that it shouldn't be accessed by derived classes. To do this, the interpreter mangles its name internally in the form _className__memberName -- Python isn't C++...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0005636286_python.txt
Q: pysvn on a webserver Are there any web hosting providers who have pysvn (http://pysvn.tigris.org/) included in their python modules, or who allow you to add additional modules such that I can install it myself? Many thanks. A: If you have shell access you can install pretty much anything to your home directory. ...
pysvn on a webserver
Are there any web hosting providers who have pysvn (http://pysvn.tigris.org/) included in their python modules, or who allow you to add additional modules such that I can install it myself? Many thanks.
[ "If you have shell access you can install pretty much anything to your home directory. Just make sure the path you install the module to is added to your PYTHONPATH environment variable.\nsay /home/harry is your home directory, you install pysvn to /home/harry/lib in your .bash_profile add:\nPYTHONPATH=/home/harry...
[ 1 ]
[]
[]
[ "pysvn", "python", "svn", "web_hosting" ]
stackoverflow_0005635658_pysvn_python_svn_web_hosting.txt
Q: Efficient large dicts of dicts to represent M:M relationships in Python I have a very large dataset - millions of records - that I want to store in Python. I might be running on 32-bit machines so I want to keep the dataset down in the hundreds-of-MB range and not ballooning much larger than that. These records -...
Efficient large dicts of dicts to represent M:M relationships in Python
I have a very large dataset - millions of records - that I want to store in Python. I might be running on 32-bit machines so I want to keep the dataset down in the hundreds-of-MB range and not ballooning much larger than that. These records - represent a M:M relationship - two IDs (foo and bar) and some simple metadat...
[ "Have you considered using a NoSQL database that runs in memory such at Redis? Redis supports a decent amount of familiar data structures.\nI realize you don't want to move outside of the application, but not reinventing the wheel can save time and quite frankly it may be more efficient.\n", "If you need to query...
[ 2, 2, 2, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0005302816_data_structures_python.txt
Q: Collaboration of command line and UI widgets Could I assume that every powerful application would provide a command line/script input? Even there are many many fancy widgets in current software, but I still think command line input mode in UI is still necessary nowadays, since command line/script input is more str...
Collaboration of command line and UI widgets
Could I assume that every powerful application would provide a command line/script input? Even there are many many fancy widgets in current software, but I still think command line input mode in UI is still necessary nowadays, since command line/script input is more straight forward and neat. If application could provi...
[ "You ask about books related to the theory of this. The theory is one of separating presentation logic from business logic, or separation of concerns. This goes by many names such as model/view/controller, model/view/presenter, and many others, and there are plenty of books on the subject. \nIf you design an applic...
[ 1 ]
[]
[]
[ "command_line", "python", "user_input", "user_interface", "wxpython" ]
stackoverflow_0005631240_command_line_python_user_input_user_interface_wxpython.txt
Q: Python app to make a random prime number between 10^300 and 10^301 i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution? import random , math check_prime = 0 print "Please wait ..." def is_prime(n): import math n = abs(n) ...
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution? import random , math check_prime = 0 print "Please wait ..." def is_prime(n): import math n = abs(n) i = 2 while i <= math.sqrt(n): if n % i == 0: ...
[ "First things first: Don't use math.pow(), as it is just a wrapper for the C floating-point function, and your numbers are WAY too big to be accurately represented as floats. Use Python's exponentiation operator, which is **.\nSecond: If you are on a platform which has a version of gmpy, use that for your primal...
[ 6, 4, 4, 4, 2, 1, 0 ]
[]
[]
[ "python", "random" ]
stackoverflow_0005631474_python_random.txt
Q: How can you run a python function stored in a different file I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example: File structure: main.py map.py Scri...
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example: File structure: main.py map.py Scripts/ script1.py map.py contains just an array and a function ...
[ "In your Scripts/ directory, add a blank file called __init__.py\nThen in your map.py file, do this:\nfrom Scripts import script1\n\nmap = {\"One\" : script1.function_one, \"Two\" : script1.function_two]\n\ndef return_mapping(str):\n return map[str]\n\n", "In map.py, the following is simpler:\nimport Scripts.s...
[ 7, 3, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005636986_python.txt
Q: Window close does not close program, even with a function calling sys.exit() bound to the window's close_event. What might cause this? The program below sets up a graph and displays a blue box each time the user clicks. A user can make more boxes using the right-click popup menu. When I implemented the popup menu...
Window close does not close program, even with a function calling sys.exit() bound to the window's close_event. What might cause this?
The program below sets up a graph and displays a blue box each time the user clicks. A user can make more boxes using the right-click popup menu. When I implemented the popup menu (thus allowing multiple blue boxes) the program stopped closing on the window close. I connected a deleteAll() method to the canvas to forc...
[ "Use app.Exit() or app.ExitMainLoop() to exit the main loop instead.\n", "The binding to the close event and the close event function (deleteAll()) needed to be in the class where the graph was being created.\nThe working code is below.\n#**************************************************************************#...
[ 0, 0 ]
[]
[]
[ "matplotlib", "python", "wxpython" ]
stackoverflow_0005623079_matplotlib_python_wxpython.txt
Q: Why does python thread consume so much memory? Why does python thread consumes so much memory? I measured that spawning one thread consumes 8 megs of memory, almost as big as a whole new python process! OS: Ubuntu 10.10 Edit: due to popular demand I'll give some extraneous examples, here it is: from os import getp...
Why does python thread consume so much memory?
Why does python thread consumes so much memory? I measured that spawning one thread consumes 8 megs of memory, almost as big as a whole new python process! OS: Ubuntu 10.10 Edit: due to popular demand I'll give some extraneous examples, here it is: from os import getpid from time import sleep from threading import Thre...
[ "This is not Python-specific, and has to do with the separate stack that gets allocated by the OS for every thread. The default maximum stack size on your OS happens to be 8MB.\nNote that the 8MB is simply a chunk of address space that gets set aside, with very little memory committed to it initially. Additional me...
[ 16 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005636660_multithreading_python.txt
Q: write python script to run the shell script? I run the svn status got the modified files : svn status ? .settings ? .buildpath ? .directory A A.php M B.php D html/C.html M html/D.fr M api/E.api M F.php .. After I want to keep all of these...
write python script to run the shell script?
I run the svn status got the modified files : svn status ? .settings ? .buildpath ? .directory A A.php M B.php D html/C.html M html/D.fr M api/E.api M F.php .. After I want to keep all of these files zcvf MY.tar.gz all files that svn stat dis...
[ "I don't see why you would use python for this if you can do it in a single line of code in the shell. \nsvn status | grep \"^[AMD]\" | sed 's/^.\\{8\\}//' | xargs zcvf My.tar.gz\n\nI used grep to only select lines that are modified, if you want all files that svn status lists (also those that are added / deleted) ...
[ 2, 0, 0, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0005636828_python_shell.txt
Q: Django: using user.get_profile() I have a very newbie question on using django auth. Here is my model: class UserProfile(models.Model): """ Main user profile used on a website """ user = models.ForeignKey(User, unique=True) # reference to built in django user display_name = models.CharFie...
Django: using user.get_profile()
I have a very newbie question on using django auth. Here is my model: class UserProfile(models.Model): """ Main user profile used on a website """ user = models.ForeignKey(User, unique=True) # reference to built in django user display_name = models.CharField(max_length=100, blank=True) # a...
[ "You should be able to use a OneToOneField(User, related_name='profile') in your UserProfile model and then do Post.objects.select_related('author__profile').\n" ]
[ 11 ]
[]
[]
[ "django", "django_authentication", "python" ]
stackoverflow_0005637620_django_django_authentication_python.txt
Q: Python - Screen-scraping and controlling mouse in OS X I'm looking into screen-scraping and controlling the mouse in OS X for a hobby project. I'm not looking for the most elegant way, but I need to be able to capture the screen every half a second or so. I've found that I could use the screencapture command-line ...
Python - Screen-scraping and controlling mouse in OS X
I'm looking into screen-scraping and controlling the mouse in OS X for a hobby project. I'm not looking for the most elegant way, but I need to be able to capture the screen every half a second or so. I've found that I could use the screencapture command-line tool (screencapture -w -W -i ~/Desktop/capture.jpg), but I'm...
[ "Take a look at autopy. Works in OSX, Linux and Windows.\n", "If you're just screenscraping, might I suggest you try Sikuli? It makes interface automation like child's play, and the scripting uses Python.\n", "Would automation software like ControllerMate help?\n\nallows you to customize the behavior\n of your...
[ 4, 2, 0 ]
[]
[]
[ "macos", "python", "screen_scraping" ]
stackoverflow_0004515871_macos_python_screen_scraping.txt
Q: Hide echo from apt-get in python How can i hide the process of installing java (apt-get openjdk-6-jre) when it's runned in python? So i can replace it with "Installing Java..." till it's ready. Thanks in advance. A: Here's an implementation of @khachik's comment: import os from subprocess import STDOUT, check_ca...
Hide echo from apt-get in python
How can i hide the process of installing java (apt-get openjdk-6-jre) when it's runned in python? So i can replace it with "Installing Java..." till it's ready. Thanks in advance.
[ "Here's an implementation of @khachik's comment:\nimport os\nfrom subprocess import STDOUT, check_call\n\ncheck_call(['apt-get', 'install', 'openjdk-6-jre'], \n stdout=open(os.devnull,'wb'), stderr=STDOUT)\n\nIt raises an exception in case of an error.\n", "proc = subprocess.Popen('apt-get install openj...
[ 2, 1 ]
[]
[]
[ "apt_get", "hidden", "python" ]
stackoverflow_0005637016_apt_get_hidden_python.txt
Q: Django form missing a field I have a model and a modelform to change some settings. The form is displayed allright, with the correct values, but when I submit the form one field is missing in the request.POST dict. The model: class NodeSettings(models.Model): nodetype = models.CharField(max_length=8, editable=...
Django form missing a field
I have a model and a modelform to change some settings. The form is displayed allright, with the correct values, but when I submit the form one field is missing in the request.POST dict. The model: class NodeSettings(models.Model): nodetype = models.CharField(max_length=8, editable=False) nodeserial = models.In...
[ "Since you are using generic view, isn't it best to extend ProcessFormView instead of TemplateView?\nEDIT\nI've tried your code with TemplateView:\nclass EditNodeView(TemplateView):\n\nDo you have a get_context_data to push the form?\ndef get_context_data(self, **kwargs):\n instance = NodeSettings.objects.get(pk...
[ 1 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0005636938_django_django_forms_django_models_python.txt
Q: How to save figures to pdf as raster images in matplotlib I have some complex graphs made using matplotlib. Saving them to a pdf using the savefig command uses a vector format, and the pdf takes ages to open. Is there any way to save the figure to pdf as a raster image to get around this problem? A: You can forc...
How to save figures to pdf as raster images in matplotlib
I have some complex graphs made using matplotlib. Saving them to a pdf using the savefig command uses a vector format, and the pdf takes ages to open. Is there any way to save the figure to pdf as a raster image to get around this problem?
[ "You can force individual figure elements to be rasterized like this:\ntext(1,1,'foobar',rasterized=True)\n\n", "Not that I know, but you can use the 'convert' program (ImageMagick') to convert a jpg to a pdf: `convert file.jpg file.pdf'.\n" ]
[ 19, 3 ]
[]
[]
[ "matplotlib", "pdf", "python", "raster" ]
stackoverflow_0005609969_matplotlib_pdf_python_raster.txt
Q: Django template iterating over list I have a list created in Django view: list = [ elem1, elem2, ..., elemN ] The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing e...
Django template iterating over list
I have a list created in Django view: list = [ elem1, elem2, ..., elemN ] The list is variable length: it can contain 0-6 elements. I want to iterate over the list in the template, but I would like the loop to run always 6 times, yielding None or empty string for non-existing elements. I tried something like this: {% ...
[ "You can add an if statement checking if it is your 6th time through the loop.\n{% for item in someList %}\n{% if forloop.counter <= 6 %}\n{{ item }}\n{% endif %}\n{% endfor %}\n\nhttp://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for in the docs.\nOf course, if your list is very long then this is not opt...
[ 2, 0 ]
[]
[]
[ "django", "python", "templates" ]
stackoverflow_0005636999_django_python_templates.txt
Q: Calling wxSizer.Insert() hides item I'm trying to insert a panel into a wxBoxSizer before the last element in that sizer using the following code: sizer = event.EventObject.Parent.GetSizer() # Add new panel from xrc res = xrc.XmlResource('add_panel.xrc') panel = res.LoadPanel(self, 'panel') sizer.Insert(...
Calling wxSizer.Insert() hides item
I'm trying to insert a panel into a wxBoxSizer before the last element in that sizer using the following code: sizer = event.EventObject.Parent.GetSizer() # Add new panel from xrc res = xrc.XmlResource('add_panel.xrc') panel = res.LoadPanel(self, 'panel') sizer.Insert(len(sizer.Children) -1, panel) sizer.Layo...
[ "Your parenting is probably wrong. Some of the object's parents do not correspond to the actual structure and / or sizers. Try this sample:\nimport wx\n\nclass MainWindow(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n self.panel = wx.Panel(self)\n ...
[ 2 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0005637429_python_wxpython_wxwidgets.txt
Q: Adding custom permissions to imported models In my Django project, I would like to add a custom permission to the User model imported from django.contrib.auth. (Specifically, a permission to allow/deny the user to change their password). I do understand how to add permissions to my own model, however, I would like...
Adding custom permissions to imported models
In my Django project, I would like to add a custom permission to the User model imported from django.contrib.auth. (Specifically, a permission to allow/deny the user to change their password). I do understand how to add permissions to my own model, however, I would like the ability to extend an existing model. Is this ...
[ "These instructions are a bit outdated, but should give you an idea on how to extend the User model via inheritance, so that you could add any new functionality to the subclass.\n" ]
[ 1 ]
[]
[]
[ "authentication", "django", "models", "permissions", "python" ]
stackoverflow_0005636722_authentication_django_models_permissions_python.txt
Q: SSH connection with python from a device (not computer) I'm using a Digi 3G router that can be programmed with python, and I want it to make periodic SSH connections to another device. I've read everything about paramiko, but don't know how to install it in the router. I want to know if there is any other way of i...
SSH connection with python from a device (not computer)
I'm using a Digi 3G router that can be programmed with python, and I want it to make periodic SSH connections to another device. I've read everything about paramiko, but don't know how to install it in the router. I want to know if there is any other way of including paramiko into a device, apart from installing (i.e. ...
[ "The description for the Digi 3G states that it is capable of python scripting, using a custom development environment. To make this work, you would have to use the python source code from paramiko; the executable would not be installable directly on the router (since the executable is designed to be run on a comp...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005636251_python.txt
Q: Using Hunch on Google App engine I want to use Hunch on Google App Engine in Python. What libraries do I need to use to do this or are there any good online tutorials that could help me with this? A: I would start from the API Overview documentation of the official site. Basically Hunch API calls are authenticat...
Using Hunch on Google App engine
I want to use Hunch on Google App Engine in Python. What libraries do I need to use to do this or are there any good online tutorials that could help me with this?
[ "I would start from the API Overview documentation of the official site.\nBasically Hunch API calls are authenticated GET or POST HTTP requests where the returned values are JSON encoded. \nExample:\nget the list of the top recommended movies:\nhttp://api.hunch.com/api/v1/get-recommendations/?topic_ids=all_544&lim...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "hunch", "python" ]
stackoverflow_0004745239_google_app_engine_hunch_python.txt
Q: Python random numbers I can't understand the problem in python. I have such code: class Rain: def __init__(self): self.x = random.randint(0, Core.Utils.ScreenResolutionX) print type(Core.Utils.ScreenResolutionX) # prints int print Core.Utils.ScreenResolutionX # print 1152 Error: self....
Python random numbers
I can't understand the problem in python. I have such code: class Rain: def __init__(self): self.x = random.randint(0, Core.Utils.ScreenResolutionX) print type(Core.Utils.ScreenResolutionX) # prints int print Core.Utils.ScreenResolutionX # print 1152 Error: self.x = random.randint(0, Core....
[ "NULL is being returned to Python in one of your methods erroneously. Always make sure to incref and return PyNone to Python if no exception needs to be raised.\n" ]
[ 1 ]
[]
[]
[ "attributeerror", "python", "random" ]
stackoverflow_0005639648_attributeerror_python_random.txt
Q: Viewing a particular html + django I am trying to learn django by reading the tutorial and Django book on the net. I am trying to display a web page on a url. For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function. Also in the home function I wro...
Viewing a particular html + django
I am trying to learn django by reading the tutorial and Django book on the net. I am trying to display a web page on a url. For the same I wrote in the url pattern function the statement (r'^home/$' , home ) where I have imported the home function. Also in the home function I wrote def home( request ): return r...
[ "You need to put the .css in the STATIC_FILES directory (if you are using 1.3 or MEDIA_URL for 1.2)\nhttp://docs.djangoproject.com/en/dev/howto/static-files/\nThen you need to link to the css in the head of the html file with something like:\n<head>\n {% load static %}\n <link rel=\"stylesheet\" href=\"{% get_sta...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005640229_django_python.txt
Q: Writing a django view that does not return an object I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax. I am getting the following error: The view mysite.views.home didn't return an HttpResponse...
Writing a django view that does not return an object
I am writing a django view that just post some data and update a variable in the database. The view will not return anything as I am submitting the data using jquery-ajax. I am getting the following error: The view mysite.views.home didn't return an HttpResponse object Again I do not wish to return an html page or any...
[ "return HttpResponse(\"\")\n\nI usually do:\nreturn HttpResponse(\"OK\")\n\njust because. In case I want to add error codes in later.\n", "A view in Django must return a HttpResponse, even if it's empty.\n", "You still need to return an HttpResponse, even for an Ajax query. If you're sure it doesn't need any co...
[ 9, 7, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005640464_django_python.txt
Q: How to draw matplotlib graph in eclipse? I can draw matplotlib graph in command line(shell) environment, but I find that I could not draw the same graph inside the eclipse IDE. such as plot([1,2,3]) not show in eclipse, I writed show() in the end but still not show anything my matplotlib use GTKAgg as backend, I ...
How to draw matplotlib graph in eclipse?
I can draw matplotlib graph in command line(shell) environment, but I find that I could not draw the same graph inside the eclipse IDE. such as plot([1,2,3]) not show in eclipse, I writed show() in the end but still not show anything my matplotlib use GTKAgg as backend, I use Pydev as plugin of eclipse to develop pyth...
[ "\nimport matplotlib.pyplot as mp\nmp.ion()\nmp.plot(x,y)\nmp.show()\n\n" ]
[ 1 ]
[]
[]
[ "eclipse", "matplotlib", "python" ]
stackoverflow_0004941162_eclipse_matplotlib_python.txt
Q: Mailslots in Python Hello is there any good tutorial / doc. for using the Win MailSlots in Python ? A: http://timgolden.me.uk/python/winsys/mailslots.html
Mailslots in Python
Hello is there any good tutorial / doc. for using the Win MailSlots in Python ?
[ "http://timgolden.me.uk/python/winsys/mailslots.html\n" ]
[ 3 ]
[]
[]
[ "ipc", "python" ]
stackoverflow_0005640571_ipc_python.txt
Q: array filter in python? For example, I have two lists A = [6, 7, 8, 9, 10, 11, 12] subset_of_A = [6, 9, 12]; # the subset of A the result should be [7, 8, 10, 11]; the remaining elements Is there a built-in function in python to do this? A: If the order is not important, you should use set.diffe...
array filter in python?
For example, I have two lists A = [6, 7, 8, 9, 10, 11, 12] subset_of_A = [6, 9, 12]; # the subset of A the result should be [7, 8, 10, 11]; the remaining elements Is there a built-in function in python to do this?
[ "If the order is not important, you should use set.difference. However, if you want to retain order, a simple list comprehension is all it takes.\nresult = [a for a in A if a not in subset_of_A]\n\nEDIT: As delnan says, performance will be substantially improved if subset_of_A is an actual set, since checking for m...
[ 159, 93, 10, 9, 5, 4, 3, 2, 1, 1 ]
[]
[]
[ "filter", "list", "python" ]
stackoverflow_0005640630_filter_list_python.txt
Q: Methods for quickly calculating standard deviation of large number set in Numpy What's the best(fastest) way to do this? This generates what I believe is the correct answer, but obviously at N = 10e6 it is painfully slow. I think I need to keep the Xi values so I can correctly calculate the standard deviation, bu...
Methods for quickly calculating standard deviation of large number set in Numpy
What's the best(fastest) way to do this? This generates what I believe is the correct answer, but obviously at N = 10e6 it is painfully slow. I think I need to keep the Xi values so I can correctly calculate the standard deviation, but are there any techniques to make this run faster? def randomInterval(a,b): r = ...
[ "You made a decent attempt, but should make sure you understand this and don't copy explicitly since this is HW\nimport numpy as np\nN = int(1e6)\na = np.random.uniform(-5,5,size=(N,))\nstandard_deviation = np.std(a)\n\nThis assumes you can use a package like numpy (you tagged it as such). If you can, there are a w...
[ 3, 1 ]
[]
[]
[ "numerical_methods", "numpy", "python", "statistics" ]
stackoverflow_0005640452_numerical_methods_numpy_python_statistics.txt
Q: How can I uniquely identify an IMAP message after copying it? I want to move an IMAP message from INBOX to INBOX/Archive using python's imapclient library, which I'm doing basically like this: def archive_message(imap, message_id): imap.copy([message_id], getOptions().imap_archive_folder) imap.delete_messa...
How can I uniquely identify an IMAP message after copying it?
I want to move an IMAP message from INBOX to INBOX/Archive using python's imapclient library, which I'm doing basically like this: def archive_message(imap, message_id): imap.copy([message_id], getOptions().imap_archive_folder) imap.delete_messages([message_id]) However, this loses my reference to the message....
[ "The value in the Message-Id header is supposed to be unique per email message.\n" ]
[ 2 ]
[]
[]
[ "imap", "imaplib", "python" ]
stackoverflow_0005640832_imap_imaplib_python.txt
Q: `' '.join(e)` isn't changing value of e I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line. def create_word(suffix): e=[] letters="abcefghijklmnopqrstuvwxyz" t=list(letters) for i in t: e.append...
`' '.join(e)` isn't changing value of e
I'm creating a function to create all 26 combinations of words with a fixed suffix. The script works except for the JOIN in the second-to-last line. def create_word(suffix): e=[] letters="abcefghijklmnopqrstuvwxyz" t=list(letters) for i in t: e.append(i) e.append(suffix) ' '.join(e) ...
[ "str.join returns the new value, not transform the existing one. Here's one way to accomplish it.\nresult = ' '.join(e)\nprint result\n\nBut if you're feeling clever, you can streamline a lot of the setup.\nimport string\ndef create_word(suffix):\n return ' '.join(i + suffix for i in string.ascii_lowercase)\n\n"...
[ 2, 0, 0 ]
[ "Beside the problem already mentioned by rekursive, you should have a look at list comprehension:\ndef create_word(suffix):\n return ''.join(\n [i+suffix for i in \"abcefghijklmnopqrstuvwxyz\"]\n )\nprint create_word('suffix')\n\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0005641090_python.txt
Q: f = open() / works in command line but not as CGI script [python] #! /usr/bin/env python import htmlSplitter, htmlGlue headerContent, mainContent, sideSetup, sideContent, footerContent = htmlSplitter.split("../htdocs/bcc/register.html") mainContent = "<h1>This is another Test</h1>" sideContent = "<h2>Jonath...
f = open() / works in command line but not as CGI script [python]
#! /usr/bin/env python import htmlSplitter, htmlGlue headerContent, mainContent, sideSetup, sideContent, footerContent = htmlSplitter.split("../htdocs/bcc/register.html") mainContent = "<h1>This is another Test</h1>" sideContent = "<h2>Jonathan's here!</h2>" htmlDoc = htmlGlue.glue(headerContent, mainContent,...
[ "Maybe just a copy/paste-error, but your shebang seems to be indented. unindent it, and try to start the script via command line on the server, using ./yourscript (not python yourscript, as this is how it probably gets executed by the webserver)\n", "Add the following to the beginning of your script:\n#!/usr/bin/...
[ 0, 0 ]
[]
[]
[ "cgi", "python" ]
stackoverflow_0005637129_cgi_python.txt
Q: "no element found" using xml.etree.ElementTree with XML file from the web Here's the Python source: fsock = urllib2.urlopen('http://eprints.soton.ac.uk/cgi/exportview/divisions/uos-fp/2009/XML/uos-fp_2009.xml') doc=et.parse(fsock) When I tried to run this it gives the following error: Traceback (most recent cal...
"no element found" using xml.etree.ElementTree with XML file from the web
Here's the Python source: fsock = urllib2.urlopen('http://eprints.soton.ac.uk/cgi/exportview/divisions/uos-fp/2009/XML/uos-fp_2009.xml') doc=et.parse(fsock) When I tried to run this it gives the following error: Traceback (most recent call last): File "C:\Python27\reading and writing xml file from web1.py", line 3...
[ "Your code works:\nimport urllib2 \nfrom xml.etree.cElementTree import parse, dump \n\nfsock = urllib2.urlopen('http://eprints.soton.ac.uk/cgi/exportview/divisions/uos-fp/2009/XML/uos-fp_2009.xml')\n\ndoc = parse(fsock) \ndump(doc)\n\n" ]
[ 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0005640961_elementtree_python_xml.txt
Q: Separating a string in Python How would I separate characters once I have a string of unseparated words? For example to translate "take the last character of the suffix and add a space to it every time ("aSuffixbSuffixcSuffix" --> "aSuffix bSuffix cSuffix").` Or, more generally, to replace the x-nth character, wh...
Separating a string in Python
How would I separate characters once I have a string of unseparated words? For example to translate "take the last character of the suffix and add a space to it every time ("aSuffixbSuffixcSuffix" --> "aSuffix bSuffix cSuffix").` Or, more generally, to replace the x-nth character, where x is any integer (e.g., to repl...
[ "Assuming you're getting your string from this question, the easiest way is to not cram all the strings together in the first place. Your original create_word could be changed to this:\ndef create_word(suffix):\n letters=\"abcdefghijklmnopqrstuvwxyz\"\n return [i + suffix for i in letters]\n\nThen you'd be ab...
[ 2, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005641586_python.txt
Q: Trouble Using function in python Hey guys, I have a question that I am a list of numbers and I need to use functions to find the average. I think I pretty much have it, but I can not get it to print the average. Can you please tell me what is wrong. nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,29,40,36,24,26,...
Trouble Using function in python
Hey guys, I have a question that I am a list of numbers and I need to use functions to find the average. I think I pretty much have it, but I can not get it to print the average. Can you please tell me what is wrong. nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,29,40,36,24,26,30,30,32,34,32,28,36,24,32] def avera...
[ "Have you tried print average(nums)? The code you have so far is just defining the function. It isn't doing anything with it. You have to call the function with its parameters and then do something with its return value (i.e. use the print function).\n", "Basically your problem is this: int / int = int. You inste...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005641724_python.txt