content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: How to impress developers with IronPython/Python I need an IronPython\Python example that would show C#/VB.NET developers how awesome this language really is. I'm looking for an easy to understand code snippet or application I can use to demo Python's capabilities. Any thoughts? A: Peter Norvig's spelling corr...
How to impress developers with IronPython/Python
I need an IronPython\Python example that would show C#/VB.NET developers how awesome this language really is. I'm looking for an easy to understand code snippet or application I can use to demo Python's capabilities. Any thoughts?
[ "Peter Norvig's spelling corrector in 21 lines of Python 2.5.\n", "Rewrite any small C# app in IronPython, and show them how many lines of code it took you. If that's not impressing, I don't know what is.\nI'm referring to one of your internal apps.\n", "I'd do a quick demo of something trivial (in Python, at l...
[ 19, 10, 6, 4, 4, 3, 3, 3, 2, 2, 1, 1, 0 ]
[]
[]
[ "ironpython", "python" ]
stackoverflow_0001708103_ironpython_python.txt
Q: Masquerading real module of a class Suppose you have the following layout for a python package ./a ./a/__init__.py ./a/_b.py inside __init__.py you have from _b import * and inside _b.py you have class B(object): pass If you import from interactive prompt >>> import a >>> a.B <class 'a._b.B'> >>> How can I c...
Masquerading real module of a class
Suppose you have the following layout for a python package ./a ./a/__init__.py ./a/_b.py inside __init__.py you have from _b import * and inside _b.py you have class B(object): pass If you import from interactive prompt >>> import a >>> a.B <class 'a._b.B'> >>> How can I completely hide the existence of _b ? The ...
[ "try:\nB.__module__= 'a'\n\nIncidentally you probably want an absolute import:\nfrom a._b import *\n\nas relative imports without the new explicit dot syntax are going away (see PEP 328).\nETA re comment:\n\nI would have to set the module explicitly for every class\n\nYes, I don't think there's a way around that bu...
[ 6, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001808522_python.txt
Q: I just want to download this URL...but it is giving me an error! ...unicode.. (Python) theurl = 'http://bit.ly/6IcCtf/' urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) htmlSource = urlResponse.read() if unicode == 1: #print urlRespons...
I just want to download this URL...but it is giving me an error! ...unicode.. (Python)
theurl = 'http://bit.ly/6IcCtf/' urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlResponse = urllib2.urlopen(urlReq) htmlSource = urlResponse.read() if unicode == 1: #print urlResponse.headers['content-type'] #encoding=urlResponse.headers['content-type'].split('charset='...
[ "Your html data is a string that comes from the internet already encoded with some encoding. Before encoding it to utf-8, you must decode it first.\nPython is implicity trying to decode it (That's why you get a UnicodeDecodeError not UnicodeEncodeError).\nYou can solve the problem by explicity decoding your bytestr...
[ 5, 3, 1 ]
[]
[]
[ "encode", "http", "python", "unicode", "urllib2" ]
stackoverflow_0001808612_encode_http_python_unicode_urllib2.txt
Q: Getting error when INSERT into MySQL _mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1 def getSource(theurl, moved = 0): if moved == 1: theurl = urllib2.urlopen(theurl).geturl() urlReq = urllib2.Request(theurl) urlReq.add_header('User-A...
Getting error when INSERT into MySQL
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1 def getSource(theurl, moved = 0): if moved == 1: theurl = urllib2.urlopen(theurl).geturl() urlReq = urllib2.Request(theurl) urlReq.add_header('User-Agent',random.choice(agents)) urlRespo...
[ "You basically need to ensure proper a string encoding. E.g. the string you provide to django is not UTF-8 encoded and therefore some characters can't be resolved.\nSome helpful advice on how to find the encoding of the requested page can be found here: urllib2 read to Unicode\n", "There are 2 ways to go if you w...
[ 3, 0 ]
[]
[]
[ "database", "django", "html", "mysql", "python" ]
stackoverflow_0001808455_database_django_html_mysql_python.txt
Q: What is the default content-type/charset? According to this answer: urllib2 read to Unicode I have to get the content-type in order to change to Unicode. However, some websites don't have a "charset". For example, the ['content-type'] for this page is "text/html". I can't convert it to Unicode. encoding=urlRespons...
What is the default content-type/charset?
According to this answer: urllib2 read to Unicode I have to get the content-type in order to change to Unicode. However, some websites don't have a "charset". For example, the ['content-type'] for this page is "text/html". I can't convert it to Unicode. encoding=urlResponse.headers['content-type'].split('charset=')[-1]...
[ "\nIs there a default \"encoding\" (English, of course)...so that if nothing is found, I can just use that? \n\nNo, there isn't. You must guess.\nTrivial approach: try and decode as UTF-8. If it works, great, it's probably UTF-8. If it doesn't, choose a most-likely encoding for the kinds of pages you're browsing. F...
[ 3, 3, 0, 0 ]
[]
[]
[ "encoding", "html", "python", "unicode" ]
stackoverflow_0001808567_encoding_html_python_unicode.txt
Q: python: how can i avoid " list index out of range" in this simple while loop my L1 array contains numbers like 0.029999999999999999 which i want to print off as 0.03 my code works, but gives an error at the end because the last count is out of range. i understand why it breaks, but dont know how to fix it. thanks ...
python: how can i avoid " list index out of range" in this simple while loop
my L1 array contains numbers like 0.029999999999999999 which i want to print off as 0.03 my code works, but gives an error at the end because the last count is out of range. i understand why it breaks, but dont know how to fix it. thanks count = 1 while L1: print "%.2f" %L1[count] count = count + 1
[ "If you want to print all numbers in L1, use:\nfor x in L1: print '%.2f' % x\n\nIf you want to skip the first one, for x in L1[1:]: will work.\nEdit: the OP mentions in a comment (!) that their desire is actually to \"create a new array\" (I imagine they actually mean \"a new list\", not an array.array, but that wo...
[ 9, 2, 0, 0 ]
[]
[]
[ "loops", "python", "while_loop" ]
stackoverflow_0001806608_loops_python_while_loop.txt
Q: Algorithm should I create a new thread? Is there an algorithm that checks whether creating a new thread pays off performance wise? I'll set a maximum of threads that can be created anyway but if I add just one task it wouldn't be an advantage to start a new thread for that. The programming language I use is python...
Algorithm should I create a new thread?
Is there an algorithm that checks whether creating a new thread pays off performance wise? I'll set a maximum of threads that can be created anyway but if I add just one task it wouldn't be an advantage to start a new thread for that. The programming language I use is python. Edit 1# Can this question even be answered ...
[ "python (at least standard CPython) is a special case, because it won't run more than one thread at a time, therefore if you are doing number-crunching on a multiple cores, then pure python isn't really the best choice.\nIn CPython, while running python code, only one thread is executing. It protected by the Global...
[ 4, 3, 0, 0 ]
[]
[]
[ "math", "multithreading", "python" ]
stackoverflow_0001808806_math_multithreading_python.txt
Q: NHibernate and python We have an existing C# project based on NHibernate and WPF. I am asked to convert it to Linux and to consider other implementation like Python. But for some reason, they like NHibernate a lot and want to keep it. Do you know if it's possible to keep the NHibernate stuff and make it work with...
NHibernate and python
We have an existing C# project based on NHibernate and WPF. I am asked to convert it to Linux and to consider other implementation like Python. But for some reason, they like NHibernate a lot and want to keep it. Do you know if it's possible to keep the NHibernate stuff and make it work with Python ? I am under the im...
[ "NHibernate is not specific to C#, but it is specific to .NET.\nIronPython is a .NET language from which you could use NHibernate.\n.NET and NHibernate can run on Linux through Mono. I'm not sure how good Mono's support is for WPF.\nI'm not sure if IronPython runs on Linux, but that would seem to be the closest th...
[ 5, 2, 1, 0 ]
[]
[]
[ "nhibernate", "orm", "python" ]
stackoverflow_0001809201_nhibernate_orm_python.txt
Q: How to get the current open file line in python? Suppose you open a file, and do an seek() somewhere in the file, how do you know the current file line ? (I personally solved with an ad-hoc file class that maps the seek position to the line after scanning the file, but I wanted to see other hints and to add this q...
How to get the current open file line in python?
Suppose you open a file, and do an seek() somewhere in the file, how do you know the current file line ? (I personally solved with an ad-hoc file class that maps the seek position to the line after scanning the file, but I wanted to see other hints and to add this question to stackoverflow, as I was not able to find th...
[ "When you use seek(), python gets to use pointer offsets to jump to the desired position in the file. But in order to know the current line number, you have to examine each character up to that position. So you might as well abandon seek() in favor of read():\nReplace\nf = open(filename, \"r\")\nf.seek(55)\n\nwith\...
[ 6, 4 ]
[]
[]
[ "file", "line_count", "python", "seek" ]
stackoverflow_0001809232_file_line_count_python_seek.txt
Q: Is it possible to script for data entry with Drupal? I'm planning on putting a store's inventory on a Drupal site and I'm wondering if it's possible to create a script (maybe in python/php?) to enter the data automatically to Drupal with CCK? Thanks in advance! A: The fastest and easiest thing would be to do the...
Is it possible to script for data entry with Drupal?
I'm planning on putting a store's inventory on a Drupal site and I'm wondering if it's possible to create a script (maybe in python/php?) to enter the data automatically to Drupal with CCK? Thanks in advance!
[ "The fastest and easiest thing would be to do the stuff with a little Drupal module you make for the case, instead of having to send lots of posts to the server and spend resources on node loads and what not.\nAnyways, what you need for this is quite similar to what mac answers here:\nIn this case you don't need al...
[ 2, 2, 2, 0, 0 ]
[]
[]
[ "data_entry", "drupal", "php", "python" ]
stackoverflow_0001808721_data_entry_drupal_php_python.txt
Q: Cross-platform help viewer with search functionality I am looking for a help viewer like Windows CHM that basically provides support for adding content in HTML format define Table of Contents decent search It should work on Windows, Mac and Linux. Bonus points for also having support for generating a "plain HTM...
Cross-platform help viewer with search functionality
I am looking for a help viewer like Windows CHM that basically provides support for adding content in HTML format define Table of Contents decent search It should work on Windows, Mac and Linux. Bonus points for also having support for generating a "plain HTML/javascript" version that can be viewed in any browser (a...
[ "wxHtmlHelpController, which is part of wxWidgets, is a cross-platform viewer for HtmlHelp.\nI'm not sure how easy it is to use it from a non-wxWidgets program, but I think it can be done.\n", "wxHtmlHelpController doesn't support any scripting within pages, nor does it support css.\n" ]
[ 2, 1 ]
[]
[]
[ "chm", "cross_platform", "documentation", "python" ]
stackoverflow_0001468314_chm_cross_platform_documentation_python.txt
Q: python script optimization for app engine i have the following script i am using to scrap data from my uni website and insert into a GAE Db from mechanize import Browser from BeautifulSoup import BeautifulSoup import re import datetime __author__ = "Nash Rafeeq" url = "http://webspace.apiit.edu.my/schedule/tim...
python script optimization for app engine
i have the following script i am using to scrap data from my uni website and insert into a GAE Db from mechanize import Browser from BeautifulSoup import BeautifulSoup import re import datetime __author__ = "Nash Rafeeq" url = "http://webspace.apiit.edu.my/schedule/timetable.jsp" viewurl = "http://localhost:8000/t...
[ "Divide and conquer.\n\nMake a list of tasks (e.g. urls to scrape/parse)\nAdd your tasks into a queue (appengine taskqueue api, amazon sqs, …)\nProcess your queue\n\n", "The first thing you should do is rewrite your script to use the App Engine datastore directly. A large part of the time you're spending is undou...
[ 4, 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0001809335_google_app_engine_python.txt
Q: Why say x = x in Python? In this file, in the function cross_from_below(x, threshold), there is a line that says threshold = threshold. What's the point of this line? Does this do something differently than if this command weren't there? A: There is no point to that assignment. It's probably just left over an...
Why say x = x in Python?
In this file, in the function cross_from_below(x, threshold), there is a line that says threshold = threshold. What's the point of this line? Does this do something differently than if this command weren't there?
[ "There is no point to that assignment. It's probably just left over and should be removed. The next function is nearly identical, and doesn't have it.\n", "No, in the specific example you quote, that line is (harmless but) redundant -- indeed the very next function (cross threshold from above rather than from b...
[ 14, 8, 3, 1 ]
[]
[]
[ "equals", "identity", "python" ]
stackoverflow_0001809805_equals_identity_python.txt
Q: Running twistd as root, modules aren't found I have a simple web server written in Twisted, and I'm trying to start it up daemonized with twistd. Everything works fine with reactor.run() but when I use twistd -y (as root), none of my packages which are in direct child directories get found. I'm running twistd as r...
Running twistd as root, modules aren't found
I have a simple web server written in Twisted, and I'm trying to start it up daemonized with twistd. Everything works fine with reactor.run() but when I use twistd -y (as root), none of my packages which are in direct child directories get found. I'm running twistd as root, since the server runs on port 80. The manpage...
[ "General UNIX wisdom is that searching the working directory for things to execute when root is a bad idea. The argument goes that it opens the door to trojans. In not going out of its way to add the working directory to the Python module import search path when running as root, twistd is basically trying to foll...
[ 7 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0001807484_python_twisted.txt
Q: Hide stderr output in unit tests I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, à la 2> /dev/null? A: I suggest writ...
Hide stderr output in unit tests
I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, à la 2> /dev/null?
[ "I suggest writing a context manager:\nimport contextlib\nimport sys\n\n@contextlib.contextmanager\ndef nostderr():\n savestderr = sys.stderr\n class Devnull(object):\n def write(self, _): pass\n def flush(self): pass\n sys.stderr = Devnull()\n try:\n yield\n finally:\n sy...
[ 26, 12, 5, 4 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0001809958_python_unit_testing.txt
Q: How can I create a script that manufactures MLA citations? I have a folder full of Windows .URL files. I'd like to translate them into a list of MLA citations for my paper. Is this a good application of Python? How can I get the page titles? I'm on Windows XP with Python 3.1.1. A: This is a fantastic use for Pyt...
How can I create a script that manufactures MLA citations?
I have a folder full of Windows .URL files. I'd like to translate them into a list of MLA citations for my paper. Is this a good application of Python? How can I get the page titles? I'm on Windows XP with Python 3.1.1.
[ "This is a fantastic use for Python! The .URL file format has a syntax like this:\n[InternetShortcut]\nURL=http://www.example.com/\nOtherStuff=irrelevant\n\nTo parse your .URL files, start with ConfigParser, which will read this and make an InternetShortcut section that you can read the URL from. Once you have a l...
[ 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001810405_python.txt
Q: Dynamically binding Python methods to an instance correctly binds the method names, but not the method I'm writing a client for a group of RESTful services. The body of the REST calls have the same XML structure, given parameters. There are several dozen calls, and I will not be implementing all of them. As such, ...
Dynamically binding Python methods to an instance correctly binds the method names, but not the method
I'm writing a client for a group of RESTful services. The body of the REST calls have the same XML structure, given parameters. There are several dozen calls, and I will not be implementing all of them. As such, I want to make them easy to specify and easy to use. The REST methods are grouped by functionality in separa...
[ "The lambda is calling m, pulling it from the local scope. After the end of the for loop, m is set to two. Calling c.one or c.two will result in two being called.\nYou can tell that two is being called by looking at the last line of your traceback:\nTypeError: two() takes exactly 2 arguments (1 given)\n\nA good dem...
[ 3, 3 ]
[]
[]
[ "python", "types" ]
stackoverflow_0001810514_python_types.txt
Q: Python/OpenCV: Converting images taken from capture I'm trying to convert images taken from a capture (webcam) and do some processing on them with OpenCV, but I'm having a difficult time.. When trying to convert the image to grayscale, the program crashes. (Python.exe has stopped working) Here is the main snippet ...
Python/OpenCV: Converting images taken from capture
I'm trying to convert images taken from a capture (webcam) and do some processing on them with OpenCV, but I'm having a difficult time.. When trying to convert the image to grayscale, the program crashes. (Python.exe has stopped working) Here is the main snippet of my code: newFrameImageGS = cv.CreateImage ((320, 240),...
[ "For some reason, CvtColor caused the program to crash when the image depths where 8 bit. When I converted them to 32 bit, the program no longer crashed and everything seemed to work OK. I have no idea why this is, but at least it works now.\nnewFrameImage = cv.QueryFrame(ps3eye)\n\nnewFrameImage32F = cv.CreateImag...
[ 4, 1 ]
[]
[]
[ "iplimage", "opencv", "python" ]
stackoverflow_0001807528_iplimage_opencv_python.txt
Q: A simple spider question I am a newbie trying to achive this simple task by using Scrapy with no luck so far. I am asking your advice about how to do this with Scrapy or with any other tool (with Python). Thank you. I want to start from a page that lists bios of attorneys whose last name start with A: initial_url...
A simple spider question
I am a newbie trying to achive this simple task by using Scrapy with no luck so far. I am asking your advice about how to do this with Scrapy or with any other tool (with Python). Thank you. I want to start from a page that lists bios of attorneys whose last name start with A: initial_url = www.example.com/Attorneys/L...
[ "Not sure I fully understand what you're asking, but maybe you need to get the absolute URL to each bio and retrieve the source code for that page:\nimport urllib2\nbio_page = urllib.urlopen(bio_url).read()\n\nThen use a regular expressions or other parsing to get the attorney's law school.\n" ]
[ 0 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0001810652_python_web_crawler.txt
Q: Parsing a string which represents a list of tuples I have strings which look like this one: "(8, 12.25), (13, 15), (16.75, 18.5)" and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values. I could do that with eval("(8, 12.25), ...
Parsing a string which represents a list of tuples
I have strings which look like this one: "(8, 12.25), (13, 15), (16.75, 18.5)" and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values. I could do that with eval("(8, 12.25), (13, 15), (16.75, 18.5)") which gives me a tuple of tupl...
[ ">>> import ast\n>>> print ast.literal_eval(\"(8, 12.25), (13, 15), (16.75, 18.5)\")\n((8, 12.25), (13, 15), (16.75, 18.5))\n\n", "def parse(s):\n tuples = s.split('), ')\n out = []\n for x in tuples:\n a,b = x.strip('()').split(', ')\n out.append((float(a),float(b)))\n return out\n\nthi...
[ 27, 4, 2, 1, 1, 1 ]
[]
[]
[ "data_structures", "eval", "python", "string", "tuples" ]
stackoverflow_0001810109_data_structures_eval_python_string_tuples.txt
Q: Line-breaking Expression in Python I am beginner in python and facing this problem. So how i can break the below expression in 2-3 lines totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold)) Like this. totalIncome = (classACost * float(...
Line-breaking Expression in Python
I am beginner in python and facing this problem. So how i can break the below expression in 2-3 lines totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold)) Like this. totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float...
[ "You always never have to use line continuation characters in python thanks to parentheses:\ntotalIncome = ( (classACost * float(classASeatsSold)) +\n (classBCost * float(classBSeatsSold)) +\n (classCCost * float(classCSeatsSold)) )\n\nWhich gives you the advantage of not having to rem...
[ 14, 4, 4, 1 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0001809890_python_syntax.txt
Q: Standard library - higher-precision floating point? So, I'm having some precision issues in Python. I would like to calculate functions like this: P(x,y) = exp(-x)/(exp(-x) + exp(-y)) Where x and y might be >1000. Python's math.exp(-1000) (in 2.6 at least!) doesn't have enough floating point precision to handle...
Standard library - higher-precision floating point?
So, I'm having some precision issues in Python. I would like to calculate functions like this: P(x,y) = exp(-x)/(exp(-x) + exp(-y)) Where x and y might be >1000. Python's math.exp(-1000) (in 2.6 at least!) doesn't have enough floating point precision to handle this. this form looks like logistic / logit / log-odd...
[ "you could divide the top and bottom by exp(-x)\nP(x,y) = 1/(1 + exp(x-y))\n\n", ">>> import decimal\n>>> decimal.Decimal(-1000).exp()\nDecimal('5.075958897549456765291809480E-435')\n>>> decimal.getcontext().prec = 60\n>>> decimal.Decimal(-1000).exp()\nDecimal('5.07595889754945676529180947957433691930559928289283...
[ 8, 8, 4, 3 ]
[]
[]
[ "floating_point", "python" ]
stackoverflow_0001811010_floating_point_python.txt
Q: How can I track python imports I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just show...
How can I track python imports
I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main ...
[ "Here's a simple (and slightly rudimentary;-) way to trace \"who's trying to import what\" in terms of module names:\nimport inspect\nimport __builtin__\nsavimp = __builtin__.__import__\n\ndef newimp(name, *x):\n caller = inspect.currentframe().f_back\n print name, caller.f_globals.get('__name__')\n return savim...
[ 16, 11, 10 ]
[ "It shouldn't be possible to get a cyclic import in python because it checks if the module has already been imported before importing it again. You can only import a module once, no matter how many times you call import.\nFrom http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d80a1c6db2b867c?pli...
[ -5 ]
[ "import", "python" ]
stackoverflow_0001811095_import_python.txt
Q: Where can I find good tutorials and guides on wxPython and wxGlade? Just out of curiosity, aside from their respective sites, have any of you guys found a better resource for figuring out wxPython/wxGlade? I figured I'd ask while I'm chewing on something else, I plan on using those tools to create a GUI for the pr...
Where can I find good tutorials and guides on wxPython and wxGlade?
Just out of curiosity, aside from their respective sites, have any of you guys found a better resource for figuring out wxPython/wxGlade? I figured I'd ask while I'm chewing on something else, I plan on using those tools to create a GUI for the project I've started.
[ "wxGlade: http://wiki.wxpython.org/WxGladeTutorial\nA video tutorial for wxGlade: http://showmedo.com/videotutorials/video?name=7850030&fromSeriesID=785\nwxPython in general: http://www.wxpython.org/tutorial.php\nAnother wxPython tutorial: http://www.zetcode.com/wxpython/\nIt is also a good idea to study the code s...
[ 2, 0 ]
[]
[]
[ "python", "wxglade", "wxpython" ]
stackoverflow_0001811164_python_wxglade_wxpython.txt
Q: How to make article spinner regex? Let's say I have teh following: {{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}} And I want that to turn into any of the following: Hello world Goodbye noobs Hi earth farewell n3wbz // etc. Paying attention to the way the "spinning" syntax is nes...
How to make article spinner regex?
Let's say I have teh following: {{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}} And I want that to turn into any of the following: Hello world Goodbye noobs Hi earth farewell n3wbz // etc. Paying attention to the way the "spinning" syntax is nested. It could be nested a billion layer...
[ "A simple way with re.subn, which can also accept a function instead of a replacement string:\nimport re\nfrom random import randint\n\ndef select(m):\n choices = m.group(1).split('|')\n return choices[randint(0, len(choices)-1)]\n\ndef spinner(s):\n r = re.compile('{([^{}]*)}')\n while True:\n s...
[ 5, 4, 2, 1, 1 ]
[]
[]
[ ".net", "article", "c#", "python", "spinner" ]
stackoverflow_0001810861_.net_article_c#_python_spinner.txt
Q: Does my code leak memory (python)? links_list = char.getLinks(words) for source_url in links_list: try: print 'Downloading URL: ' + source_url urldict = hash_url(source_url) source_url_short = urldict['url_short'] source_url_hash = urldict['url_short_...
Does my code leak memory (python)?
links_list = char.getLinks(words) for source_url in links_list: try: print 'Downloading URL: ' + source_url urldict = hash_url(source_url) source_url_short = urldict['url_short'] source_url_hash = urldict['url_short_hash'] if Url.objects.filter...
[ "maybe your process uses too much memory and the server (perhaps shared host) just kills it because you exhaust your memory quota.\nhere you use a call that may eat up a lot of memory:\nlinks_list = char.getLinks(words)\nfor source_url in links_list:\n ...\n\nLooks like you might be building a whole list in mem...
[ 1, 0, 0, 0 ]
[]
[]
[ "memory", "memory_management", "python" ]
stackoverflow_0001811413_memory_memory_management_python.txt
Q: How to write the grammar for this in pyparsing: match a set of words but not containing a given pattern I am new to Python and pyparsing. I need to accomplish the following. My sample line of text is like this: 12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009 Washing service (3 Shirt) 23 Mar 2009 I need...
How to write the grammar for this in pyparsing: match a set of words but not containing a given pattern
I am new to Python and pyparsing. I need to accomplish the following. My sample line of text is like this: 12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009 Washing service (3 Shirt) 23 Mar 2009 I need to extract the item description, period tok_date_in_ddmmmyyyy = Combine(Word(nums,min=1,max=2)+ " " + Word(a...
[ "I would suggest looking at SkipTo as the pyparsing class that is most appropriate, since you have a good definition of the unwanted text, but will accept pretty much anything before that. Here are a couple of ways to use SkipTo:\ntext = \"\"\"\\\n12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009\nWashing s...
[ 5, 3 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0001805309_pyparsing_python.txt
Q: How to pass this command to subprocess.call? Command: root@host:~#convert source.jpg -resize x500 -resize "500x<" -gravity center +repage target.jpg Python code: >> command_list = ['convert', 'source.jpg', '-resize', 'x500', '-resize', '\'500x<\'', '-gravity', 'center', 'target.jpg'] >> p = subprocess.call(comman...
How to pass this command to subprocess.call?
Command: root@host:~#convert source.jpg -resize x500 -resize "500x<" -gravity center +repage target.jpg Python code: >> command_list = ['convert', 'source.jpg', '-resize', 'x500', '-resize', '\'500x<\'', '-gravity', 'center', 'target.jpg'] >> p = subprocess.call(command_list) convert: invalid argument for option `'500...
[ "Why the extra quotes on 500x<? Subprocess will correctly quote any arguments. \nKeep in mind that the shell will NOT pass the outer quotes to the application, just the quoted value, but subprocess will pass the quotes if you force it to.\n", "Have you tried '\"500x<\"' instead of '\\'500x<\\''?\n" ]
[ 5, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001811683_python_subprocess.txt
Q: Python wx (Python Card) logging subprocess output to window There are similar questions to this one, but I'd like to see a clarified answer. I'm building a simple GUI with PythonCard to wrap a command line process. Specifically, it's a wrapper for a series of ANT Tasks and other custom operations so non-devs can u...
Python wx (Python Card) logging subprocess output to window
There are similar questions to this one, but I'd like to see a clarified answer. I'm building a simple GUI with PythonCard to wrap a command line process. Specifically, it's a wrapper for a series of ANT Tasks and other custom operations so non-devs can use it. I'd like to redirect the output of the subprocess to a Tex...
[ "Just about every subprocess you can wrap will buffer its output unless you manage to fool it into believing it's actually connected to a terminal -- and subprocess can't do that. Rather, look into pexpect (runs well on every platform that lets you have a pseudoterminal, i.e., every platform except Microsoft Window...
[ 1, 1 ]
[]
[]
[ "python", "pythoncard", "wxpython" ]
stackoverflow_0001200610_python_pythoncard_wxpython.txt
Q: Is it possible to unpack a tuple without using variables? I'm using the os.path.split() function on a path in my program to get the filename and pathname of a file then passing them into another method, but my current solution seems rather ugly: path = os.path.split(somefile) some_class(path[0], path[1]) Is it po...
Is it possible to unpack a tuple without using variables?
I'm using the os.path.split() function on a path in my program to get the filename and pathname of a file then passing them into another method, but my current solution seems rather ugly: path = os.path.split(somefile) some_class(path[0], path[1]) Is it possible to unpack the path tuple in a cleaner way within the cal...
[ "Yes, Python has argument list unpacking. Try this:\nsome_class(*os.path.split(somefile))\n\n" ]
[ 14 ]
[]
[]
[ "iterable_unpacking", "python", "tuples" ]
stackoverflow_0001812020_iterable_unpacking_python_tuples.txt
Q: Processing (possibly) optional arguments in Python I am working on a series of command line tools which connect to the same server and do related but different things. I'd like users to be able to have a single configuration file where they can place common arguments such as connection information that can be sha...
Processing (possibly) optional arguments in Python
I am working on a series of command line tools which connect to the same server and do related but different things. I'd like users to be able to have a single configuration file where they can place common arguments such as connection information that can be shared across all the tools. Ideally, I'd like something t...
[ "This-party module configparse is written to extend optparse from the standard Python library. As the optparse docs I pointed to mention, \"optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either\" (though it follows with a couple of URLs that show you ways to d...
[ 1, 0, 0 ]
[]
[]
[ "command_line", "configparser", "optparse", "python" ]
stackoverflow_0001811540_command_line_configparser_optparse_python.txt
Q: Python ctypes and function calls My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem. I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore t...
Python ctypes and function calls
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem. I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct: from ctypes...
[ "As vincent mentioned, this is due to the allocated page being marked as non executable. Newer processors support this functionality, and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack var...
[ 8, 7, 4, 0, 0 ]
[]
[]
[ "assembly", "c", "ctypes", "python", "x86_64" ]
stackoverflow_0000275207_assembly_c_ctypes_python_x86_64.txt
Q: Creating hierarchy tree from dictionary of pages' contents The following key:value pairs are 'page' and 'page contents'. { 'section-a.html':{'contents':'section-b.html section-c.html section-d.html'}, 'section-b.html':{'contents':'section-d.html section-e.html'}, 'section-c.html':{'contents':'product-a.html ...
Creating hierarchy tree from dictionary of pages' contents
The following key:value pairs are 'page' and 'page contents'. { 'section-a.html':{'contents':'section-b.html section-c.html section-d.html'}, 'section-b.html':{'contents':'section-d.html section-e.html'}, 'section-c.html':{'contents':'product-a.html product-b.html product-c.html product-d.html'}, 'section-d.htm...
[ "Here's a simple approach -- it's O(N squared), so, not all that highly scalable, but will serve you well for a reasonable book size (if you have, say, millions of pages, you need to be thinking about a very different and less simple approach;-).\nFirst, make a more usable dict, mapping page to set of contents: e.g...
[ 2, 1, 0 ]
[]
[]
[ "data_structures", "hierarchical_trees", "python", "tree" ]
stackoverflow_0001809758_data_structures_hierarchical_trees_python_tree.txt
Q: Replacing elements with lxml.html I'm fairly new to lxml and HTML Parsers as a whole. I was wondering if there is a way to replace an element within a tree with another element... For example I have: body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """ d...
Replacing elements with lxml.html
I'm fairly new to lxml and HTML Parsers as a whole. I was wondering if there is a way to replace an element within a tree with another element... For example I have: body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """ doc = lxml.html.fromstring(body) codeblo...
[ "Regarding lxml,\nIn doc.replace(block, hilited)\nblock is the lxml's Element object, hilited is string, you cannot replace that.\nThere is 2 ways to do that\nblock.text=hilited \n\nor\nbody=body.replace(block.text,hilited)\n\n", "If you're new to python HTML parsers, you might try out BeautifulSoup, a html/xml p...
[ 6, 1 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0001812764_lxml_python.txt
Q: What should i use for a Remote Desktop Control? Hi everybody i'm new to stackoverflow and to python programming :-) Can somebody point me in the right direction or suggest me a good way to do this..? The software I'd like to write is a kind of "multiple remote control", it has: One Server ... whose task is to s...
What should i use for a Remote Desktop Control?
Hi everybody i'm new to stackoverflow and to python programming :-) Can somebody point me in the right direction or suggest me a good way to do this..? The software I'd like to write is a kind of "multiple remote control", it has: One Server ... whose task is to send his screen to all the clients Many Clients ... th...
[ "Take a look at the VNC viewer implemented in Python.\n", "Teamtalk is a Python IM software that also has Remote Desktop access. You can download the source and look at the implementation.\n" ]
[ 4, 2 ]
[]
[]
[ "python", "python_imaging_library", "twisted" ]
stackoverflow_0001812890_python_python_imaging_library_twisted.txt
Q: I want to develop a framework in Python for desktop based applications. How should I go about it? I want to develop a desktop application framework in Python, much like QT, but how to go about it? Any tutorials or links related to it would be helpful! A: There is so many great freameworks like wxPython (Tutorial...
I want to develop a framework in Python for desktop based applications. How should I go about it?
I want to develop a desktop application framework in Python, much like QT, but how to go about it? Any tutorials or links related to it would be helpful!
[ "There is so many great freameworks like wxPython (Tutorial), PyQt (Tutorial), PyGtk (Tutorial) already.\nYou just need to try your favorite one.\n", "You can get a pretty comprehensive list of Gui programming frameworks for Python here, http://wiki.python.org/moin/GuiProgramming \n", "theres WxPython tutorial ...
[ 4, 3, 2, 2 ]
[]
[]
[ "desktop", "frameworks", "python" ]
stackoverflow_0001811940_desktop_frameworks_python.txt
Q: Making a Python script Object-Oriented I'm writing an application in Python that is going to have a lot of different functions, so logically I thought it would be best to split up my script into different modules. Currently my script reads in a text file that contains code which has been converted into tokens and ...
Making a Python script Object-Oriented
I'm writing an application in Python that is going to have a lot of different functions, so logically I thought it would be best to split up my script into different modules. Currently my script reads in a text file that contains code which has been converted into tokens and spellings. The script then reconstructs the ...
[ "To speed up your existing code measurably, add def main(): before the assignment to tokenList, indent everything after that 4 spaces, and at the end put the usual idiom\nif __name__ == '__main__':\n main()\n\n(The guard is not actually necessary, but it's a good habit to have nevertheless since, for scripts with ...
[ 56, 1, 0, 0 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0001813117_oop_python.txt
Q: How to Make sure the code is still working after refactoring ( Dynamic language) How to make sure that code is still working after refactoring ( i.e, after variable name change)? In static language, if a class is renamed but other referring class is not, then I will get a compilation error. But in dynamic langua...
How to Make sure the code is still working after refactoring ( Dynamic language)
How to make sure that code is still working after refactoring ( i.e, after variable name change)? In static language, if a class is renamed but other referring class is not, then I will get a compilation error. But in dynamic language there is no such safety net, and your code can break during refactoring if you are ...
[ "Before you start refactoring you should create tests that will be able to test what you're going to change - if you say unit tests will not be enought, or they will be hard to create, then by all means create higher level tests possibly even excersising the whole of your product. \nIf you have code coverage tools ...
[ 17, 10, 1, 0 ]
[]
[]
[ "dynamic_languages", "php", "python" ]
stackoverflow_0000688740_dynamic_languages_php_python.txt
Q: Help ctypes.windll.dnsapi.DnsQuery_A I have trouble with [DnsQuery](http://msdn.microsoft.com/en-us/library/ms682016(VS.85).aspx) API, the *ppQueryResultsSet parameter troubles me. Can anyone show me an example of how to make correct DLL calls in python? import ctypes from ctypes import wintypes from windns_types ...
Help ctypes.windll.dnsapi.DnsQuery_A
I have trouble with [DnsQuery](http://msdn.microsoft.com/en-us/library/ms682016(VS.85).aspx) API, the *ppQueryResultsSet parameter troubles me. Can anyone show me an example of how to make correct DLL calls in python? import ctypes from ctypes import wintypes from windns_types import DNS_RECORD, IP4_ARRAY #declared her...
[ "Isn't it a pointer to pointer to DNS_RECORD? This means you have to initialize rr as POINTER(DNS_RECORD)() and pass it by reference: ctypes.byref(rr).\nUpdate: But I think the problem you see is from passing server_arr: you pass a structure with first field being 0x00000001 instead of reference to this structure, ...
[ 2 ]
[]
[]
[ "ctypes", "dns", "python", "winapi" ]
stackoverflow_0001812564_ctypes_dns_python_winapi.txt
Q: Python: execfile from other file's working directory? I have some code that loads a default configuration file and then allows users to supply their own Python files as additional supplemental configuration or overrides of the defaults: # foo.py def load(cfg_path=None): # load default configuration exec(d...
Python: execfile from other file's working directory?
I have some code that loads a default configuration file and then allows users to supply their own Python files as additional supplemental configuration or overrides of the defaults: # foo.py def load(cfg_path=None): # load default configuration exec(default_config) # load user-specific configuration ...
[ "os.chdir lets you change the working directory as you wish (you can extract the working directory of cfg_path with os.path.dirname); be sure to first get the current directory with os.getcwd if you want to restore it when you're done exec'ing cfg_path.\nPython 3 does indeed remove execfile (in favor of a sequence ...
[ 7 ]
[]
[]
[ "execfile", "python", "working_directory" ]
stackoverflow_0001813282_execfile_python_working_directory.txt
Q: Puzzling App Engine Datastore Issue (ListProperty) Ok so I have the same python code locally and in the gae cloud. when I store an entity locally, the ListProperty field of set element type datetime.datetime looks like so in the Datastore Viewer: 2009-01-01 00:00:00,2010-03-10 00:00:00 when I store same on the cl...
Puzzling App Engine Datastore Issue (ListProperty)
Ok so I have the same python code locally and in the gae cloud. when I store an entity locally, the ListProperty field of set element type datetime.datetime looks like so in the Datastore Viewer: 2009-01-01 00:00:00,2010-03-10 00:00:00 when I store same on the cloud, the viewer displays: [datetime.datetime(2009, 1, 1,...
[ "Ok long story short: it's now classed as a bug in the app engine dev server version and is no longer supported in the production cloud datastore.\nFilled out a further explanation in a blog post, check out point 3.\n", "The problem your see is clearly a conversion to string (calling __str__ or __unicode__) in th...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "listproperty", "python" ]
stackoverflow_0001780618_google_app_engine_google_cloud_datastore_listproperty_python.txt
Q: Custom/Owner draw control in PyQt? I am learning PyQt and wonder if one can create custom/owner draw control like one show in the figure below: alt text http://lh5.ggpht.com/_5XDoB4MglkY/SpoT51SXR1I/AAAAAAAAFcU/ZXjzmhRyDVA/s400/SearchBox.png The search box has magnifier icon on its right border. Is this kind of ...
Custom/Owner draw control in PyQt?
I am learning PyQt and wonder if one can create custom/owner draw control like one show in the figure below: alt text http://lh5.ggpht.com/_5XDoB4MglkY/SpoT51SXR1I/AAAAAAAAFcU/ZXjzmhRyDVA/s400/SearchBox.png The search box has magnifier icon on its right border. Is this kind of thing possible with PyQt? Thanks!
[ "If you only need to show an icon, an easy way is to use style-sheets:\nlineedit = QtGui.QLineEdit() \nlineedit.setStyleSheet(\"\"\"QLineEdit {\n background-image: url(:/images/magnifier.png);\n background-repeat: no-repeat;\n background-position: right;\n background-clip: padding;\n padding-...
[ 6, 0 ]
[]
[]
[ "ownerdrawn", "pyqt", "python", "qt", "user_interface" ]
stackoverflow_0001353181_ownerdrawn_pyqt_python_qt_user_interface.txt
Q: What is the best way to escape Python strings in PHP? I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg. subject_prefix = 'This String From User Input' msg_footer = """This one too.""" The contents of subject_prefix et al need to be wri...
What is the best way to escape Python strings in PHP?
I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg. subject_prefix = 'This String From User Input' msg_footer = """This one too.""" The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the cont...
[ "Do not try write this function in PHP. You will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit.\nFirst, consider what problem you are actually solving. I presume you are just trying to get data from PHP to Python. You might try to write a .ini file rather...
[ 2, 0, 0, 0 ]
[ "I suggest writing a function that will take two arguments: the text to be escaped and the type of quotes the string is in. Then, for example, if the type of quotes are single quotes, the function will escape the single quotes in the string and any other characters that need to be escaped (backslash?).\nfunction es...
[ -2 ]
[ "php", "python", "user_input" ]
stackoverflow_0000196771_php_python_user_input.txt
Q: PyQT events between multiple objects I am creating a GUI program in Python/PyQT and would like to know how I can connect an event which happens in a child object to the parent? For example, if someone clicks a 'Submit' button, how would i trigger something to happen in the parent object (lets say update a QLabel o...
PyQT events between multiple objects
I am creating a GUI program in Python/PyQT and would like to know how I can connect an event which happens in a child object to the parent? For example, if someone clicks a 'Submit' button, how would i trigger something to happen in the parent object (lets say update a QLabel on the parent) Any help would be greatly ap...
[ "It is done like in C++ Qt by connecting signals to slots, you will find all the information on this page (and here for the old way).\n", "You must connect these methods every time you set new parent (and remove old connections!!)\nhttp://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#connect\n(...
[ 4, 0 ]
[]
[]
[ "events", "pyqt", "python" ]
stackoverflow_0001627148_events_pyqt_python.txt
Q: Remove Duplicate Items in Dictionary I'm trying to remove duplicate items in a list through a dictionary: def RemoveDuplicates(list): d = dict() for i in xrange(0, len(list)): dict[list[i]] = 1 <------- error here return d.keys() But it is raising me the following error: TypeError: 'ty...
Remove Duplicate Items in Dictionary
I'm trying to remove duplicate items in a list through a dictionary: def RemoveDuplicates(list): d = dict() for i in xrange(0, len(list)): dict[list[i]] = 1 <------- error here return d.keys() But it is raising me the following error: TypeError: 'type' object does not support item assignmen...
[ "You should have written:\nd[list[i]] = 1\n\nBut why not do this?\ndef RemoveDuplicates(l):\n return list(set(l))\n\nAlso, don't use built-in function names as variable names. It can lead to confusing bugs.\n", "In addition to what others have said, it is unpythonic to do this:\nfor i in xrange(0, len(lst)):\n...
[ 11, 4, 3, 3, 0 ]
[]
[]
[ "duplicate_removal", "python" ]
stackoverflow_0001813469_duplicate_removal_python.txt
Q: How to deal with "None" DB values in Django queries I have the following filter query which is doing an SQL OR statement: results = Stores.objects.filter(Q(title__icontains=prefs.address1) | Q(title__icontains=prefs.address2)) This works fine but if the prefs.address1 and prefs.address2 values (which come from an...
How to deal with "None" DB values in Django queries
I have the following filter query which is doing an SQL OR statement: results = Stores.objects.filter(Q(title__icontains=prefs.address1) | Q(title__icontains=prefs.address2)) This works fine but if the prefs.address1 and prefs.address2 values (which come from another model) are blank in mySQL, Django complains with th...
[ "You could do this which is easily generalisable to more queries\nquery = Q()\nfor search in (prefs.address1, prefs.address2):\n if search:\n query |= Q(title__icontains=search)\nresults = Stores.objects.filter(query)\n\n", "This?\nthefilter = Q(title__icontains=prefs.address1)\nif prefs.address2 is not...
[ 12, 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001813653_django_python.txt
Q: Django, how to generate an admin panel without models? I'm building a rather large project, that basically consists of this: Server 1: Ice based services. Glacier2 for session handling. Firewall allowing access to Glacier2. Server 2: Web interface (read, public) for Ice services via Glacier2. Admin inter...
Django, how to generate an admin panel without models?
I'm building a rather large project, that basically consists of this: Server 1: Ice based services. Glacier2 for session handling. Firewall allowing access to Glacier2. Server 2: Web interface (read, public) for Ice services via Glacier2. Admin interface for Ice services via Glacier 2. The point I'm concerned...
[ "I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.\nTake a look at models.py, admin.py and urls.py here: django-webfaction\nTo create an entry on the admin index page us...
[ 7, 3, 1, 0 ]
[]
[]
[ "django", "django_admin", "ice", "python" ]
stackoverflow_0001813637_django_django_admin_ice_python.txt
Q: How does python webdriver work? I want to add some features to webdriver, but since I don't know Java at all, I want to understand the way it works first. So as I get it, there is a firefox plugin (javascript) and there is java code that starts firefox with that extension installed, then this java code listens to ...
How does python webdriver work?
I want to add some features to webdriver, but since I don't know Java at all, I want to understand the way it works first. So as I get it, there is a firefox plugin (javascript) and there is java code that starts firefox with that extension installed, then this java code listens to a local port and when it gets some co...
[ "Yeah you've got it. The Java server controls a browser with a special JavaScript environment that allows the server to control it. The server listens for commands given to it through http, when it receives commands, it pulls the strings on the browser to make it do stuff. The Python API for webdriver is code that ...
[ 4 ]
[]
[]
[ "firefox", "java", "javascript", "python", "webdriver" ]
stackoverflow_0001813824_firefox_java_javascript_python_webdriver.txt
Q: Losing session data when user logs in I have been working on a shop that is built in Python on the back of the django framework, everything was working fine until I noticed that when a user proceeds to the checkout and is requested to log in they do so and their basket empties...obvioulsy this is not a great thin...
Losing session data when user logs in
I have been working on a shop that is built in Python on the back of the django framework, everything was working fine until I noticed that when a user proceeds to the checkout and is requested to log in they do so and their basket empties...obvioulsy this is not a great thing for a basket to do, I was wondering what ...
[ "Are you running two django instances on the same machine? If so, check that SESSION_COOKIE_NAME is set to something different for each instance.\nWe had the problem that instances using sessions using the same SESSION_COOKIE_NAME had very sporadic (read bizarre) behaviour.\n", "This will probably be something to...
[ 1, 0 ]
[]
[]
[ "django", "e_commerce", "python", "session" ]
stackoverflow_0001791818_django_e_commerce_python_session.txt
Q: python and securing pyc files on disk I set django's settings.py file to chmod 600 to keep felonious folks from spying my database connection info, but on import python compiles this file and writes out settings.pyc as mode 644. It doesn't take much sleuthing for the bad guys to get the info they need from this co...
python and securing pyc files on disk
I set django's settings.py file to chmod 600 to keep felonious folks from spying my database connection info, but on import python compiles this file and writes out settings.pyc as mode 644. It doesn't take much sleuthing for the bad guys to get the info they need from this compiled version. I fear my blog entries are ...
[ "You can set the umask directly in python. The interpreter uses this umask to create the pyc files:\nimport os\nos.umask(077) # Only keep rights for owner\nimport test\n\nVerify the test.pyc created:\n$> ls -l test.py*\n-rw-r--r-- 1 shad users 0 2009-11-29 00:15 test.py\n-rw------- 1 shad users 94 2009-11-29 00:15...
[ 6, 1 ]
[]
[]
[ "python", "security" ]
stackoverflow_0001814053_python_security.txt
Q: How to delete Firefox cookies from webdriver in python? when I can't delete FF cookies from webdriver. When I use the .delete_all_cookies method, it returns None. And when I try to get_cookies, I get the following error: webdriver_common.exceptions.ErrorInResponseException: Error occurred when processing packet:Co...
How to delete Firefox cookies from webdriver in python?
when I can't delete FF cookies from webdriver. When I use the .delete_all_cookies method, it returns None. And when I try to get_cookies, I get the following error: webdriver_common.exceptions.ErrorInResponseException: Error occurred when processing packet:Content-Length: 120 {"elementId": "null", "context": "{9b44672f...
[ "Hmm, I actually haven't worked with Webdriver so this may be of no help at all... but in your other post you mention that you're experimenting with modifying the delete cookie webdriver js function. Did get_cookies fail before you were modifying the delete function? What happens when you get cookies before deletin...
[ 0 ]
[]
[]
[ "firefox", "python", "webdriver" ]
stackoverflow_0001813044_firefox_python_webdriver.txt
Q: A puzzle concerning Q objects and Foreign Keys I've got a model like this: class Thing(models.Model): property1 = models.IntegerField() property2 = models.IntegerField() property3 = models.IntegerField() class Subthing(models.Model): subproperty = models.IntegerField() thing = modelsForeignkey...
A puzzle concerning Q objects and Foreign Keys
I've got a model like this: class Thing(models.Model): property1 = models.IntegerField() property2 = models.IntegerField() property3 = models.IntegerField() class Subthing(models.Model): subproperty = models.IntegerField() thing = modelsForeignkey(Thing) main = models.BooleanField() I've got a...
[ "It's a bit easier to understand if you explicitly give your Subthings a \"related_name\" in their relationship to the Thing\nclass Subthing(models.Model):\n ...\n thing = models.ForeignKey(Thing, related_name='subthings')\n ...\n\nNow, you use Django join syntax to build your Q object:\nQ(subthings__main=...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "django_q", "django_queryset", "python" ]
stackoverflow_0001813777_django_django_models_django_q_django_queryset_python.txt
Q: Django, displaying a view in an another view? I would like to know if I can display a view inside another view with django. This is what I tried to do: def displayRow(request, row_id): row = Event.objects.get(pk=row_id) return render_to_response('row.html', {'row': row}) def listEventsSummary(request): ...
Django, displaying a view in an another view?
I would like to know if I can display a view inside another view with django. This is what I tried to do: def displayRow(request, row_id): row = Event.objects.get(pk=row_id) return render_to_response('row.html', {'row': row}) def listEventsSummary(request): listEventsSummary = Event.objects.all().order_by(...
[ "http response contains headers along with html, or anything else, so you can't just add them up like strings.\nif you want to modularize your view function, then have sub-procedure calls return strings and then you can do it the way you propose\nProbably in your case it would be better to put a loop showing rows i...
[ 4 ]
[]
[]
[ "django", "django_views", "python" ]
stackoverflow_0001814255_django_django_views_python.txt
Q: What is the idiomatic way of invoking a list of functions in Python? I have a list of callback functions that I need to invoke when an event is fired. Is this idiomatic python? def first_callback(m): print 'first ' + m def second_callback(m): print 'second ' + m lst = [first_callback, second_callback] map(...
What is the idiomatic way of invoking a list of functions in Python?
I have a list of callback functions that I need to invoke when an event is fired. Is this idiomatic python? def first_callback(m): print 'first ' + m def second_callback(m): print 'second ' + m lst = [first_callback, second_callback] map(lambda x: x("event_info"),lst) #is this how you do it?
[ "Use map only for functions without side effects (like print). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic:\nfor f in lst:\n f(\"event_info\")\n\nEdit: also, as of Python 3.0, map returns an iterator instead of a list. Hence in Python 3.0 the code ...
[ 18, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000897362_python.txt
Q: Global disk resource becomes unavailable If I've got a global disk resource (mount point on an isilon file server) that multiple servers use to access a lock file. What is a good way to handle the situation if that global disk becomes unavailable and the servers can't access the global lock file? Thanks, Doug A: ...
Global disk resource becomes unavailable
If I've got a global disk resource (mount point on an isilon file server) that multiple servers use to access a lock file. What is a good way to handle the situation if that global disk becomes unavailable and the servers can't access the global lock file? Thanks, Doug
[ "If this happens intermittently, you might just want to try waiting a short period and retrying. Other than that... log the error and fail. Maybe throw an exception that someone higher up can catch and deal with more gracefully.\n" ]
[ 1 ]
[]
[]
[ "fileserver", "flock", "linux", "python" ]
stackoverflow_0001814393_fileserver_flock_linux_python.txt
Q: Python: How to shutdown a threaded HTTP server with persistent connections (how to kill readline() from another thread)? I'm using python2.6 with HTTPServer and the ThreadingMixIn, which will handle each request in a separate thread. I'm also using HTTP1.1 persistent connections ('Connection: keep-alive'), so nei...
Python: How to shutdown a threaded HTTP server with persistent connections (how to kill readline() from another thread)?
I'm using python2.6 with HTTPServer and the ThreadingMixIn, which will handle each request in a separate thread. I'm also using HTTP1.1 persistent connections ('Connection: keep-alive'), so neither the server or client will close a connection after a request. Here's roughly what the request handler looks like request,...
[ "You're almost there—the correct approach is to call rfile.close() and to catch the broken pipe errors and exit your loop when that happens.\n", "If you set daemon_threads to true in your HTTPServer subclass, the activity of the threads will not prevent the server from exiting.\nclass ThreadedHTTPServer(Threading...
[ 1, 1, 0 ]
[]
[]
[ "multithreading", "python", "sockets" ]
stackoverflow_0001814575_multithreading_python_sockets.txt
Q: How to search a HTML page for an item in a given list I have a list of schools schools = ['Harvard Law School', 'Stanford Law School', 'Yale Law School', 'Columbia Law School', 'NYU School of Law', 'University of Chicago Law School'] and bios of lawyers that contain one of these schools: html = "page that contain...
How to search a HTML page for an item in a given list
I have a list of schools schools = ['Harvard Law School', 'Stanford Law School', 'Yale Law School', 'Columbia Law School', 'NYU School of Law', 'University of Chicago Law School'] and bios of lawyers that contain one of these schools: html = "page that contains one of these schools" like this "<strong><em>Education...
[ "I don't know nothing about Python but I often create dynamic regex expressions into a string like:\n\"(school 1|school 2|school 3|school n)\"\nThen I instantiate a regex object, passing the string.\nYou can then match your schools, regardless of the form of the document unless a HTML tag is in the middle of a sch...
[ 1, 1, 1, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001813921_python.txt
Q: New transport and reader type in Twisted I'm trying to add a new transport to Twisted, which will read data from a stream - either a file in a tail -f way, or from a pipe, but I have some problems with Twisted architecture. I've got the transport itself (implements ITransport) ready - it handles all file opening. ...
New transport and reader type in Twisted
I'm trying to add a new transport to Twisted, which will read data from a stream - either a file in a tail -f way, or from a pipe, but I have some problems with Twisted architecture. I've got the transport itself (implements ITransport) ready - it handles all file opening. I've got streaming functions/deferreds ready. ...
[ "It sounds like you've mostly figured out how to do this. You might be interested in twisted.internet.fdesc.readFromFD, but it's only a few lines long and it's not doing anything particularly complicated (it's a few lines you don't have to maintain, though). Aside from that - yes, you have to do the I/O monitorin...
[ 5 ]
[]
[]
[ "architecture", "protocols", "python", "transport", "twisted" ]
stackoverflow_0001814467_architecture_protocols_python_transport_twisted.txt
Q: Display gaps in dates with Python and Django I'm building an application that requires each user to make a post on a daily basis. I'd like to display the gaps in dates where users haven't made posts. Since it doesn't seem like a good idea to insert empty database rows for empty posts, I'm only inserting a record w...
Display gaps in dates with Python and Django
I'm building an application that requires each user to make a post on a daily basis. I'd like to display the gaps in dates where users haven't made posts. Since it doesn't seem like a good idea to insert empty database rows for empty posts, I'm only inserting a record when the user adds a post. The model contains a fie...
[ "I recommend building a set of dates that a user has posted, then start at the earliest date and iterate until the current day. For each day, print the date and check whether a post exists for that day. By using a set we can do this check in constant time, not that this will likely matter.\ndays = set( Post.objec...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001814664_django_python.txt
Q: What is wrong with my "digit finder" in python? I am learning python through the Project Euler problems. For problem 40 I wrote this code: import math i = 1 counter = 0 while counter <= 1000000: MMM = int(math.log(i, 10)) + 1 counter = counter + MMM V = math.log(i, 10) print(i, counter, MMM, V) ...
What is wrong with my "digit finder" in python?
I am learning python through the Project Euler problems. For problem 40 I wrote this code: import math i = 1 counter = 0 while counter <= 1000000: MMM = int(math.log(i, 10)) + 1 counter = counter + MMM V = math.log(i, 10) print(i, counter, MMM, V) i += 1 It is supposed to return the number conta...
[ "Floating point error somewhere along the way? It might be possible that at some point math.log is returning something that's barely less than (or greater, depending on the direction of your off-by-1 result) an integer boundary and thus int() is truncating it to the wrong value. Floating-point numbers are not preci...
[ 4, 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0001814933_python.txt
Q: How do I check the index of a an element in a list? (Python) list = [('ba',4), ('hh',5), ('gg', 25)] How do I do: list.index('hh') ...and returns 1? Then, how do I sort it by the 25, 5, 4? What if I have 2 lists: list1 = [('ba',4), ('hh',5), ('gg', 25)] list2 = [('ja',40), ('hgh',88), ('hh', 2)] how do I do a fo...
How do I check the index of a an element in a list? (Python)
list = [('ba',4), ('hh',5), ('gg', 25)] How do I do: list.index('hh') ...and returns 1? Then, how do I sort it by the 25, 5, 4? What if I have 2 lists: list1 = [('ba',4), ('hh',5), ('gg', 25)] list2 = [('ja',40), ('hgh',88), ('hh', 2)] how do I do a for each? for item in l1: if item[0] in l2[0 of the tuple]:
[ "First of, don't use list as the name for a variable, as it shadows the built-in list function.\n\nYou can use enumerate to pair up list elements and their index:\n>>> l = [('ba',4), ('hh',5), ('gg', 25)]\n>>> [i for i, e in enumerate(l) if e[0] == 'hh']\n[1]\n\nFor sorting you can use a lambda expression as shown ...
[ 5, 3, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001815258_list_python.txt
Q: How to pass an unicode char argument to ImageMagick? Suppose the char of "▣" is in somefont.ttf's glyph table. char = unichr(9635) subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', '-label:%s' % char, 'output.png']) subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', ('-l...
How to pass an unicode char argument to ImageMagick?
Suppose the char of "▣" is in somefont.ttf's glyph table. char = unichr(9635) subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', '-label:%s' % char, 'output.png']) subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', ('-label:%s' % char).encode('utf-8'), 'output.png']) Both cre...
[ "According to this link, you need to pass the text encoded in UTF8.\nIt will be able to draw the correct character outside ASCII range.\n", "\nTry to get it working by hand using ASCII labels in your console.\n\n\n $ convert -font somefont.ttf -size 50x50 -label:A output.png\n convert: unrecognized option `...
[ 1, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0001815427_python_unicode.txt
Q: What is the preferred technique to convert an object's properties to a sorted list of tuples? I'm working with an open-source library and they define a class like so: class Provider(object): """ Defines for each of the supported providers """ DUMMY = 0 EC2 = 1 EC2_EU = 2 RACKSPACE = 3 SLICE...
What is the preferred technique to convert an object's properties to a sorted list of tuples?
I'm working with an open-source library and they define a class like so: class Provider(object): """ Defines for each of the supported providers """ DUMMY = 0 EC2 = 1 EC2_EU = 2 RACKSPACE = 3 SLICEHOST = 4 GOGRID = 5 VPSNET = 6 LINODE = 7 VCLOUD = 8 RIMUHOSTING = 9 I need to...
[ "If you are looking for class variables that are of the type integer, you could do it like this:\nimport inspect\nPROVIDER_CHOICES = inspect.getmembers(Foo, lambda x: isinstance(x, int))\n\nCheck out the inspect module for more information.\n\nAs an aside: you can use PROVIDER_CHOICES.sort(key=...) in your last lin...
[ 6, 0 ]
[]
[]
[ "python", "sorting" ]
stackoverflow_0001815693_python_sorting.txt
Q: What's an easy way to implement a --quiet option in a python script Am working on a command line python script - throughout the script, I have a lot of information I am print-ing to the terminal window so that I may follow along with what is happening. Using OptionParser I want to add a --quiet option so I can sil...
What's an easy way to implement a --quiet option in a python script
Am working on a command line python script - throughout the script, I have a lot of information I am print-ing to the terminal window so that I may follow along with what is happening. Using OptionParser I want to add a --quiet option so I can silence all the output. I am looking for a pythonic way to go about impleme...
[ "You could use logging and assign those things that should not be printed if QUIET a different log level.\nEdit: THC4K's answer shows an example of how to do this, assuming that all output should be silent if QUIET is set. Note that in Python 3 from __future__ import print_function is not necessary:\nprint = loggin...
[ 30, 15, 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001815760_python.txt
Q: want to develop a app in python which interacts with the web and posts on facebook , twitter and gtalk? i want to develop a python desktop app which interacts and posts its content on facebook , twitter or gtalk as a message . is it possible?... tutorials and ideas will help A: The Twitter API will help you for ...
want to develop a app in python which interacts with the web and posts on facebook , twitter and gtalk?
i want to develop a python desktop app which interacts and posts its content on facebook , twitter or gtalk as a message . is it possible?... tutorials and ideas will help
[ "The Twitter API will help you for Twitter, since it's intended to help you post messages. The Facebook API isn't actually what you want - it helps you write applications which run on Facebook, but doesn't necessarily help you communicate with Facebook the way that a user would. To do that you might need to look ...
[ 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0001816024_python.txt
Q: Python: Extract HTML from an XML file My XML file looks like this: <strings> <string>Bla <b>One &amp; Two</b> Foo</string> </strings> I want to extract the content of each <string> while maintaining the inner tags. That is, I would like to see the following Python string: u"Bla <b>One & Two</b> Foo". Alte...
Python: Extract HTML from an XML file
My XML file looks like this: <strings> <string>Bla <b>One &amp; Two</b> Foo</string> </strings> I want to extract the content of each <string> while maintaining the inner tags. That is, I would like to see the following Python string: u"Bla <b>One & Two</b> Foo". Alternatively, I guess I could settle on u"Bla ...
[ "There may be a better way of conditionally handling objects returned by the xpath() function, but I'm not sufficiently conversant with lxml to know what it is, so I had to write a function to return the text value of a node. But that said, this shows a general approach to the problem:\n>>> from lxml import etree\...
[ 3, 2, 0 ]
[ "Not using parser, but just pure string manipulation\nmystring=\"\"\"\n <strings>\n <string>Bla <b>One &amp; Two</b> Foo</string>\n </strings>\n\"\"\"\nfor s in mystring.split(\"</string>\"):\n if \"<string>\" in s:\n i = s.index(\"<string>\")\n print s[i+len(\"<string>\"):].replace(\"&amp;\",...
[ -1 ]
[ "html", "lxml", "python", "xml" ]
stackoverflow_0001814923_html_lxml_python_xml.txt
Q: Python py2exe - memory load error I am creating a medium level application in Python. Everything works well now, and I am trying to make this a windows executable with py2exe. The executable is created fine, but when I try to run it, it fails with the following error. File "zipextimporter.pyo", line 82, in load_...
Python py2exe - memory load error
I am creating a medium level application in Python. Everything works well now, and I am trying to make this a windows executable with py2exe. The executable is created fine, but when I try to run it, it fails with the following error. File "zipextimporter.pyo", line 82, in load_module File "ffhandler.pyo", line 33,...
[ "You're missing some DLL's in your build...\nFirst search your hard drive for the file _pyAAC.pyd. Make sure it is included (shipped) in your build.\nThen use 'dependency walker' on the .pyd file (in your py2exe compiled version!) to see what it is that is still missing (other DLL's which are causing the MemoryLoad...
[ 0 ]
[]
[]
[ "py2exe", "python" ]
stackoverflow_0001816439_py2exe_python.txt
Q: Get process argument info in windows with python/pywin32? In linux, I know with 'ps' you can get the arguments that a command was run with. I need the equivalent in windows Right now in python I'm doing Process[i] = subprocess.Popen(cmd + " --daemon --config " + str(i) + ".conf", shell=False) But I'm doing this i...
Get process argument info in windows with python/pywin32?
In linux, I know with 'ps' you can get the arguments that a command was run with. I need the equivalent in windows Right now in python I'm doing Process[i] = subprocess.Popen(cmd + " --daemon --config " + str(i) + ".conf", shell=False) But I'm doing this in a daemon that is meant to be up all (or most) of the time. S...
[ "This one might give you some inspiration.\n" ]
[ 1 ]
[]
[]
[ "api", "process", "python", "pywin32", "winapi" ]
stackoverflow_0001815733_api_process_python_pywin32_winapi.txt
Q: Dynamic URL's inside Google's AppEngine Good Afternoon, I'm currently trying to build something incredibly simple inside of the Google AppEngine. The goal is to build a simple photo sharing application that will connect back to my iPhone application. It's all a learning experience for both Python and Objective-C...
Dynamic URL's inside Google's AppEngine
Good Afternoon, I'm currently trying to build something incredibly simple inside of the Google AppEngine. The goal is to build a simple photo sharing application that will connect back to my iPhone application. It's all a learning experience for both Python and Objective-C. (I've been a PHP programmer for quite som...
[ "A simple way to grab them all:\nphotos = Photo.gql('ORDER BY __key__')\n\nFor more, see Queries on Keys in the App Engine docs.\nAre you storing your photos with predefined keys?\nphoto = Photo(key_name=\"xzy123\")\nphoto.put()\n\nThen you can retrieve it in your ViewPage:\nphotos = [ Photo(key_name=\"%s\" % id) ]...
[ 3 ]
[]
[]
[ "dynamic_url", "google_app_engine", "python" ]
stackoverflow_0001816529_dynamic_url_google_app_engine_python.txt
Q: How can I translate this XPath expression to BeautifulSoup? In answer to a previous question, several people suggested that I use BeautifulSoup for my project. I've been struggling with their documentation and I just cannot parse it. Can somebody point me to the section where I should be able to translate this exp...
How can I translate this XPath expression to BeautifulSoup?
In answer to a previous question, several people suggested that I use BeautifulSoup for my project. I've been struggling with their documentation and I just cannot parse it. Can somebody point me to the section where I should be able to translate this expression to a BeautifulSoup expression? hxs.select('//td[@class="a...
[ "one option is to use lxml (I'm not familiar with beautifulsoup, so I can't say how to do with it), it defaultly supports XPath\nEdit:\ntry (untested) tested:\nsoup.findAll('td', 'altRow')[1].findAll('a', href=re.compile(r'/.a\\w+'), recursive=False)\n\nI used docs at http://www.crummy.com/software/BeautifulSoup/do...
[ 6, 4, 2, 1 ]
[]
[]
[ "beautifulsoup", "python", "xpath" ]
stackoverflow_0001814750_beautifulsoup_python_xpath.txt
Q: How to create a generator/iterator with the Python C API? How do I replicate the following Python code with the Python C API? class Sequence(): def __init__(self, max): self.max = max def data(self): i = 0 while i < self.max: yield i i += 1 So far, I have th...
How to create a generator/iterator with the Python C API?
How do I replicate the following Python code with the Python C API? class Sequence(): def __init__(self, max): self.max = max def data(self): i = 0 while i < self.max: yield i i += 1 So far, I have this: #include <Python/Python.h> #include <Python/structmember.h>...
[ "Below is a simple implementation of module spam with one function myiter(int) returning iterator:\nimport spam\nfor i in spam.myiter(10):\n print i\n\nprints numbers from 0 to 9.\nIt is simpler then your case but shows main points: defining object with standard __iter__() and next() methods, and implementing it...
[ 65, 5 ]
[]
[]
[ "c", "generator", "iterator", "python", "python_c_api" ]
stackoverflow_0001815812_c_generator_iterator_python_python_c_api.txt
Q: Adding custom JS to a django admin field In a django application I have the following model: class Appointment(models.Model): #some other fields #address fields zipcode=models.CharField(max_length=5) address=models.CharField(max_length=120) latitude=models.FloatField() longitude=models.Floa...
Adding custom JS to a django admin field
In a django application I have the following model: class Appointment(models.Model): #some other fields #address fields zipcode=models.CharField(max_length=5) address=models.CharField(max_length=120) latitude=models.FloatField() longitude=models.FloatField() When I'm rendering an Appointment, I...
[ "What is primarily being dealt with is client-side markup and client-side javascript. Being the case, it would seem that using a facility that's designed to handle those would be the proper choice. I'd also recommend making a custom admin widget. I've used this pattern myself. Depending on the size of the clien...
[ 20, 4 ]
[]
[]
[ "django", "django_admin", "google_maps", "python", "user_interface" ]
stackoverflow_0001816444_django_django_admin_google_maps_python_user_interface.txt
Q: Getting Unique Foreign Keys in Django? Suppose my model looks like this: class Farm(models.Model): name = ... class Tree(models.Model): farm = models.ForeignKey(Farm) ...and I get a QuerySet of Tree objects. How do I determine what farms are represented in that QuerySet? A: http://docs.djangoproject.com/...
Getting Unique Foreign Keys in Django?
Suppose my model looks like this: class Farm(models.Model): name = ... class Tree(models.Model): farm = models.ForeignKey(Farm) ...and I get a QuerySet of Tree objects. How do I determine what farms are represented in that QuerySet?
[ "http://docs.djangoproject.com/en/dev/ref/models/querysets/#in\nFarm.objects.filter(tree__in=TreeQuerySet)\n\n", "There might be a better way to do it with the Django ORM and keep it lazy but you can get what you want with regular python (off the top of my head):\n>>> set([ t.farm for t in qs ])\n\n", "Here is ...
[ 6, 4, 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0001816572_django_django_models_python.txt
Q: Why does PIP install of python-couchdb experimental branch from SVN fail? I'm setting up a Fabric/virtualenv/pip automated deployment for a project and I need to install the latest experimental branch of python-couchdb. Naturally, I stick it in my pip requirements file, like so: -e svn+http://couchdb-python.googl...
Why does PIP install of python-couchdb experimental branch from SVN fail?
I'm setting up a Fabric/virtualenv/pip automated deployment for a project and I need to install the latest experimental branch of python-couchdb. Naturally, I stick it in my pip requirements file, like so: -e svn+http://couchdb-python.googlecode.com/svn/branches/experimental/httplib@195#egg=CouchDB-dev_r195 However, ...
[ "Per John Paulett's comment--you must indeed have subversion installed on the server in order to execute it on the server.\nI would like the egg delivered to my face chilled, if possible.\n" ]
[ 1 ]
[]
[]
[ "deployment", "fabric", "pip", "python", "virtualenv" ]
stackoverflow_0001815963_deployment_fabric_pip_python_virtualenv.txt
Q: get `object.__doc__` as raw string Is there a way to get object.__doc__ as a raw string, apart from adding an 'r' in-front of the doctring itself in the source code? I have latex code inside and the '\r's, '\f's etc are creating problems. A: There's no such Python type as "raw string" -- there are raw string lit...
get `object.__doc__` as raw string
Is there a way to get object.__doc__ as a raw string, apart from adding an 'r' in-front of the doctring itself in the source code? I have latex code inside and the '\r's, '\f's etc are creating problems.
[ "There's no such Python type as \"raw string\" -- there are raw string literals, which are just one syntax approach (out of many) to specify constants (i.e., literals) that are of string types. So \"getting\" something \"as a raw string\" just makes no sense. You can write docstrings as raw string literals (i.e.,...
[ 7, 2, 2 ]
[]
[]
[ "pydoc", "python" ]
stackoverflow_0001817064_pydoc_python.txt
Q: MySQL driver issues with INFORMATION_SCHEMA? I'm trying out the Concurrence framework for Stackless Python. It includes a MySQL driver and when running some code that previously ran fine with MySQLdb it fails. What I am doing: Connecting to the MySQL database using dbapi with username/password/port/database. Exec...
MySQL driver issues with INFORMATION_SCHEMA?
I'm trying out the Concurrence framework for Stackless Python. It includes a MySQL driver and when running some code that previously ran fine with MySQLdb it fails. What I am doing: Connecting to the MySQL database using dbapi with username/password/port/database. Executing SELECT * FROM INFORMATION_SCHEMA.COLUMNS Th...
[ "It definitely looks like a driver issue. Maybe the python driver don't support the DB prefix.\nJust to be sure, try the other way around: first use INFORMATION_SCHEMA and then SELECT * FROM mydatabase.sometable\n", "I finally found the reason.\nThe driver just echoed the server capability flags back in the proto...
[ 1, 1 ]
[]
[]
[ "mysql", "python", "python_db_api", "python_stackless" ]
stackoverflow_0001814408_mysql_python_python_db_api_python_stackless.txt
Q: Python MySQL: clean multiple foreign keys table I am working with Python MySQL, and need to clean a table in my database that has 13328 rows. I can not make a simple drop table, because this table is child and also father of other child foreign-keys linked on it. If I try drop table, the system forbidden me. The t...
Python MySQL: clean multiple foreign keys table
I am working with Python MySQL, and need to clean a table in my database that has 13328 rows. I can not make a simple drop table, because this table is child and also father of other child foreign-keys linked on it. If I try drop table, the system forbidden me. The table is defined with ON UPDATE CASCADE, ON DELETE CAS...
[ "To remove all records from the table: \ntruncate table product\n\nTo reset next ID to 1:\nALTER TABLE product AUTO_INCREMENT = 1\n\nor \nSET insert_id;\nINSERT INTO product ...;\n\n(I haven't tested this. But i should work) \n", "If you clean a table with truncate:\nTRUNCATE TABLE product\n\nAs a side effect...
[ 2, 2, 0 ]
[]
[]
[ "auto_increment", "foreign_keys", "mysql", "python" ]
stackoverflow_0001812191_auto_increment_foreign_keys_mysql_python.txt
Q: SQL syntax error using Python and psycopg How can you fix this SQL-code? My Python code: import os, pg, sys, re, psycopg2 conn = psycopg2.connect("dbname=tk user=masi password=123") cur = conn.cursor() cur.execute("""INSERT INTO courses ('course_nro') VALUES ( `:...
SQL syntax error using Python and psycopg
How can you fix this SQL-code? My Python code: import os, pg, sys, re, psycopg2 conn = psycopg2.connect("dbname=tk user=masi password=123") cur = conn.cursor() cur.execute("""INSERT INTO courses ('course_nro') VALUES ( `:1` )""", ['hen']) I get: Traceback (most recen...
[ "You made 3 different errors in the same query:\n\nField names should not be quoted.\npsycopg2 uses tuples, not lists for arguments.\nPositional arguments like \":1\" are not supported.\n\nChange your query into:\ncur.execute(\"\"\"INSERT INTO courses (course_nro)\n VALUES (%s)\"\"\", ('hen',))\n", "Remove...
[ 2, 1 ]
[]
[]
[ "python", "sql", "sql_injection" ]
stackoverflow_0001778778_python_sql_sql_injection.txt
Q: Constants in python? I have the following variables declared in a lot of functions, as I need those values in each one of them. Is there anyway I can declare them at a global scope or something, such as I won't have to declare them in all my methods? I am using all this methods on instance methods of a class of mi...
Constants in python?
I have the following variables declared in a lot of functions, as I need those values in each one of them. Is there anyway I can declare them at a global scope or something, such as I won't have to declare them in all my methods? I am using all this methods on instance methods of a class of mine. x = 0 y = 1 t = 2 In ...
[ "If they're all within a single module, then they only live in that module's namespace and you don't have to worry about name clashes. (And you can still import them into other namesapaces)\nFor example\nMyModWithContstants.py\nx = 0\ny = 0\n\ndef someFunc():\n dosomethingwithconstants(x,y)\n\nand we can also do\n...
[ 12, 5, 1, 1, 0 ]
[ "import __builtin__\n__builtin__.__dict__[\"X\"] = 5\nThis will store the X constant in all modules executed until the interpreter exits.\nRemember though to use it with care, as other python developers are not likely to expect this.\nI use it mainly for storing the translation function '_'.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0001817144_python.txt
Q: Override default User model method I've been trying to override the default __unicode__() method for the django.contrib.auth.models User model but I can't get it to work. I tried it like this: from django.db import models from django.contrib.auth.models import User class User(models.Model): def __unicode_...
Override default User model method
I've been trying to override the default __unicode__() method for the django.contrib.auth.models User model but I can't get it to work. I tried it like this: from django.db import models from django.contrib.auth.models import User class User(models.Model): def __unicode__(self): return "pie" and f...
[ "You might want to look at Django's Proxy Model concept. They even show an example using User as a base class.\nOn the other hand, if you are trying to change the actual __unicode__() method in the actual User class, you probably will have to MonkeyPatch it. It's not difficult, but I'll leave the specifics as a lea...
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001817244_django_python.txt
Q: PyKDE4 documentation I'm trying to get started using Python for KDE development. What is the canonical source for PyKDE4 reference documentation? The Python page of KDE TechBase is surprisingly sparse on details, and googling hasn't helped. A: Here.
PyKDE4 documentation
I'm trying to get started using Python for KDE development. What is the canonical source for PyKDE4 reference documentation? The Python page of KDE TechBase is surprisingly sparse on details, and googling hasn't helped.
[ "Here.\n" ]
[ 1 ]
[]
[]
[ "pykde", "python" ]
stackoverflow_0001817751_pykde_python.txt
Q: What are these errors and how do I handle them? I am using this simple code for l in bios: OpenThisLink = url + l response = urllib2.urlopen(OpenThisLink) to open about 200 urls and search them with regex (and BeautifulSoup), but after a dozen or so I get these errors and IDLE quits. What do they mean? Ho...
What are these errors and how do I handle them?
I am using this simple code for l in bios: OpenThisLink = url + l response = urllib2.urlopen(OpenThisLink) to open about 200 urls and search them with regex (and BeautifulSoup), but after a dozen or so I get these errors and IDLE quits. What do they mean? How can I handle them? Thank you. Traceback (most recen...
[ "The error being raised is HTTPError - specifically, a 404 is being thrown for one of your URLs. You could either ignore it:\nfor l in bios:\n OpenThisLink = url + l\n try:\n response = urllib2.urlopen(OpenThisLink)\n except urllib2.HTTPError:\n pass\n\nOr, you could re-raise the error with a...
[ 3, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0001817815_beautifulsoup_python.txt
Q: Format Python List to SQL script? I have a list need to be format it to SQL scripte list = [['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0\n'], ['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0\n'], ['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'",...
Format Python List to SQL script?
I have a list need to be format it to SQL scripte list = [['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0\n'], ['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0\n'], ['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0\n'], To sql scr...
[ "Iterate over each element in the list\n Unpack the element (which is also a list) into its fields\n Generate a SQL line from these fields\n\nThe simplest and ugliest way that just gets the job done is:\nlist = [\n ['11', ' 0', \" 'MMB'\", \" '2 MB INTERNATIONAL'\", ' NULL', ' NULL', ' 0'], \n ['12', ' 0', ...
[ 1, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0001817886_python.txt
Q: How to convert seconds to hh:mm:ss with the Django's date template tag? Edit : is there a way to easily convert {{ value|date:"Z" }} to one of the +hh:mm or -hh:mm formats (because date:"Z" returns xxxx or -xxxx seconds). Show this for more explanations about the needed format. Thank you and sorry for my ugly engl...
How to convert seconds to hh:mm:ss with the Django's date template tag?
Edit : is there a way to easily convert {{ value|date:"Z" }} to one of the +hh:mm or -hh:mm formats (because date:"Z" returns xxxx or -xxxx seconds). Show this for more explanations about the needed format. Thank you and sorry for my ugly english. ;)
[ "Just clarifying here, it's the timezone offset that needs the colon, ie 2009-11-29T14:33:59-0600 in the above example should be 2009-11-29T14:33:59-06:00 to conform to the W3C guidelines.\nLooking at the code at django/utils/dateformat.py:\n def O(self):\n \"Difference to Greenwich time in hours; e.g. '+0200'\...
[ 2, 1 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0001816176_django_django_templates_python.txt
Q: Choosing and deploying a comet server I want to push data to the browser over HTTP without killing my django/python application. I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly). I've looked into the following engines: ...
Choosing and deploying a comet server
I want to push data to the browser over HTTP without killing my django/python application. I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly). I've looked into the following engines: orbited cometd ejabberd jetty Has anyone ha...
[ "I would recommend looking into Twisted, their twisted.web server, and the comet work done on top of it at Divmod. They can handle far more concurrent connections than traditional thread or process based servers, which is exactly what you need for something like this. And, yes, I've architected systems using Twiste...
[ 5, 2, 2, 2, 2, 2 ]
[]
[]
[ "comet", "daemon", "django", "python" ]
stackoverflow_0000621802_comet_daemon_django_python.txt
Q: what functional tools remain in Python 3k? I have have read several entries regarding dropping several functional functions from future python, including map and reduce. What is the official policy regarding functional extensions? is lambda function going to stay? A: Well, Python 3.0 and 3.1 are already releas...
what functional tools remain in Python 3k?
I have have read several entries regarding dropping several functional functions from future python, including map and reduce. What is the official policy regarding functional extensions? is lambda function going to stay?
[ "Well, Python 3.0 and 3.1 are already released, so you can check this out for yourself. The end result was that map and filter were kept as built-ins, and lambda was also kept. The only change was that reduce was moved to the functools module; you just need to do\nfrom functools import reduce\n\nto use it.\nFuture ...
[ 10, 3 ]
[]
[]
[ "functional_programming", "python", "python_3.x" ]
stackoverflow_0001817771_functional_programming_python_python_3.x.txt
Q: SQLAlchemy not returning selected data I'm using SQLAlchemy as the ORM within an application i've been building for some time. So far, it's been quite a painless ORM to implement and use, however, a recent feature I'm working on requires a persistent & distributed queue (list & worker) style implementation, which ...
SQLAlchemy not returning selected data
I'm using SQLAlchemy as the ORM within an application i've been building for some time. So far, it's been quite a painless ORM to implement and use, however, a recent feature I'm working on requires a persistent & distributed queue (list & worker) style implementation, which I've built in MySQL and Python. It's all wor...
[ "You have executed 3 queries and MySQLdb creates a result set for each. You have to fetch first result, then call cursor.nextset(), fetch second and so on. \nThis answers your question, but won't be useful for you, because it won't solve locking issue. You have to understand how FOR UPDATE works first: it locks ret...
[ 3 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0001818054_mysql_python_sqlalchemy.txt
Q: Sound Monitoring in C++/Python I'm looking for an API (or some information as to where to look/start) that will ultimately allow me to monitor sound being played by the computer. My end goal (well, certain to eventually be a stepping-stone) is an oscilloscope. Where should I begin to look (aside from Google, whic...
Sound Monitoring in C++/Python
I'm looking for an API (or some information as to where to look/start) that will ultimately allow me to monitor sound being played by the computer. My end goal (well, certain to eventually be a stepping-stone) is an oscilloscope. Where should I begin to look (aside from Google, which has yielded unsatisfactory results...
[ "As @cobbal noted, on Mac OS X you would need to use PortAudio in some way to get the audio as it plays. The only other way to do it would be to use an audio player that has a plugin API, then write your code as a plugin for that one player. But a CoreAudio solution should make it possible for you to monitor all ...
[ 2, 1 ]
[]
[]
[ "audio", "c", "c++", "macos", "python" ]
stackoverflow_0001817733_audio_c_c++_macos_python.txt
Q: Python - Overridding print() I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless). Doing this doesn't work: print = myPrintFunction Since it's a syntax error. :( A: Print is not a function in Python 2.x, so this is not directly possible. You can, however, ...
Python - Overridding print()
I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless). Doing this doesn't work: print = myPrintFunction Since it's a syntax error. :(
[ "Print is not a function in Python 2.x, so this is not directly possible.\nYou can, however, override sys.stdout.\nIf you are on Python 3.0 in which print is now a function what you have would then work, assuming you have the right signature. Also see a related question in this site.\n", "Would\nimport sys\nsys.s...
[ 13, 6, 1, 1, 0 ]
[]
[]
[ "mod_wsgi", "python", "python_3.x", "wsgi" ]
stackoverflow_0000770657_mod_wsgi_python_python_3.x_wsgi.txt
Q: python 2.3 regex problem how do i set the regular expressions flags like multiline and ignorecase in python 2.3? in python 2.6 its like this re.findall(pattern,string, re.multiline | re.ignorecase) but this doesn't seem to wok for python 2.3, any ideas? pointers appreciated edit: sorry, it was python 2.3 not 2.4 ...
python 2.3 regex problem
how do i set the regular expressions flags like multiline and ignorecase in python 2.3? in python 2.6 its like this re.findall(pattern,string, re.multiline | re.ignorecase) but this doesn't seem to wok for python 2.3, any ideas? pointers appreciated edit: sorry, it was python 2.3 not 2.4
[ "Compile the regexp in advance with re.compile(pattern[, flags]). Then you can pass the options as the second parameter.\n", "the flags are uppercase in 2.4, e.g.:\nre.findall(pattern,string, re.MULTILINE | re.IGNORECASE)\n\nworks for me;\nPython 2.4.3 (#1, Sep 3 2009, 15:37:37) \n[GCC 4.1.2 20080704 (Red Hat 4....
[ 1, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0001818622_python_regex.txt
Q: How to have a URL like this in Django? How can I have URLs like example.com/category/catename-operation/ in Django? Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become example.com/my home...
How to have a URL like this in Django?
How can I have URLs like example.com/category/catename-operation/ in Django? Also in some cases the user enters a space separated category, how can I handle that? E.g if the user enters the category as "my home", then the URL for this category will become example.com/my home/ which is not a valid URL. How can I handle...
[ "If you want to keep your URLs pretty, for example when a user enters \"my category\" you could have \"my-category\" instead of \"my%20category\" in the URL. I suggest you look into SlugField (http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield) and prepopulating that slugfield using ModelAdmin's prep...
[ 6, 3, 1, 1, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0001788432_django_python.txt
Q: GAE Image Posting to Datastore through Django Form I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "Using the Images Python API" on the GAE web site. The sample they provide doesn't seem to work wi...
GAE Image Posting to Datastore through Django Form
I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "Using the Images Python API" on the GAE web site. The sample they provide doesn't seem to work with Django though. Searching around here, I found a threa...
[ "In your image serving code, you're writing out a redirect, with the 'URL' for the redirect being the image data - eg, you're redirecting users to \"%PNG...\". You need to write out the response data directly.\nBesides that, what is HttpResponseRedirect? It's not part of the webapp framework.\nAlso, have you checke...
[ 1, 0, 0 ]
[]
[]
[ "django", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0001785637_django_google_app_engine_google_cloud_datastore_python.txt
Q: Close and open a new browser in Selenium I'm writing a script which needs the browser that selenium is operating close and re-open, without losing its cookies. Any idea on how to go about it? Basically, it's a check to see that if the user opens and closes his browser, his cookies stay intact. A: You should be a...
Close and open a new browser in Selenium
I'm writing a script which needs the browser that selenium is operating close and re-open, without losing its cookies. Any idea on how to go about it? Basically, it's a check to see that if the user opens and closes his browser, his cookies stay intact.
[ "You should be able to use the stop and start commands. You will need to ensure that you are not clearing cookies between sessions, and depending on the browser you're launching you may also need to use the -browserSessionReuse command line option.\n", "This is a feature of the browser and not your concern: If th...
[ 3, 0 ]
[]
[]
[ "python", "selenium" ]
stackoverflow_0001818969_python_selenium.txt
Q: python logging in django I am using the basic python logger in django and it seems to be workng well. I have the logging setup in my setting.py as; logging.baseConfig(level = logging.NOTSET, format='a format', datemt=' a datefmt', filename='p...
python logging in django
I am using the basic python logger in django and it seems to be workng well. I have the logging setup in my setting.py as; logging.baseConfig(level = logging.NOTSET, format='a format', datemt=' a datefmt', filename='path to log', ...
[ "There's no need to catch the exception just so you can log it. You can log it and handle it, or else let it bubble up to some higher level which will log it and handle it. If you want to log exceptions which occur in some view, which you don't want to handle, then you can install some exception middleware which lo...
[ 1, 0 ]
[]
[]
[ "django", "exception_handling", "logging", "python" ]
stackoverflow_0001818236_django_exception_handling_logging_python.txt
Q: Creating new list with values from two prior lists Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2 , followed by the second to last element of list1 , followed by the second to last element of list2 ,...
Creating new list with values from two prior lists
Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2 , followed by the second to last element of list1 , followed by the second to last element of list2 , and so on (in other words the new list should consist o...
[ "l1 = [1,2,3]\nl2 = [4,5,6]\n\nnewl = []\nfor item1, item2 in zip(reversed(l1), reversed(l2)):\n newl.append(item1)\n newl.append(item2)\n\nprint newl\n\n", "list(sum(zip(list1,list2)[::-1],()))\n\n", "Yet another way,\nfrom itertools import izip\nl1 = [1, 2, 3, 4]\nl2 = [5, 6, 7, 8]\nl = []\nfor _ in izi...
[ 7, 2, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0001818763_list_python.txt
Q: Executing a subprocess fails I tried to call a process via Python with several arguments. Executing the batch file itself works fine for me but translating it into Python makes me scream. Here the contents of the batch file: "C:\Program Files\bin\cspybat" "C:\Program Files\bin\armproc.dll" "C:\Program Files\bin\ar...
Executing a subprocess fails
I tried to call a process via Python with several arguments. Executing the batch file itself works fine for me but translating it into Python makes me scream. Here the contents of the batch file: "C:\Program Files\bin\cspybat" "C:\Program Files\bin\armproc.dll" "C:\Program Files\bin\armjlink.dll" "C:\Documents and Sett...
[ "To execute a batch file in Windows:\nfrom subprocess import Popen\np = Popen(\"batchfile.bat\", cwd=r\"c:\\directory\\containing\\batchfile\")\nstdout, stderr = p.communicate()\n\nIf you don't want to execute the batch file, but rather execute the command in your question directly from Python, you need to experime...
[ 28, 0 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0001818774_python_subprocess.txt
Q: Are there functions in Python, or is everything a method? Or is everything a method? Since everything is an object, a def whatever: is just a method of that file.py, right? A: Python has functions. As everything is an object functions are objects too. So, to use your example: >>> def whatever(): ... pass ...
Are there functions in Python, or is everything a method?
Or is everything a method? Since everything is an object, a def whatever: is just a method of that file.py, right?
[ "Python has functions. As everything is an object functions are objects too.\nSo, to use your example:\n>>> def whatever():\n... pass\n...\n>>> whatever\n<function whatever at 0x00AF5F30>\n\nWhen we use def we have created an object which is a function. We can, for example, look at an attribute of the object:...
[ 31, 2, 0 ]
[]
[]
[ "function", "methods", "oop", "python" ]
stackoverflow_0001819372_function_methods_oop_python.txt
Q: Database query across django ManyToManyField I'd like to find how to select all objects whose ManyToMany field contains another object. I have the following models (stripped down) class Category(models.Model): pass class Picture(models.Model): categories = models.ManyToManyField(Category) visible = mo...
Database query across django ManyToManyField
I'd like to find how to select all objects whose ManyToMany field contains another object. I have the following models (stripped down) class Category(models.Model): pass class Picture(models.Model): categories = models.ManyToManyField(Category) visible = models.BooleanField() I need a function to select a...
[ "Why write a custom function and not use something like this? (untested)\npics = Picture.objects.filter(categories__in = [1,2,3]).filter(visible=True)\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_database", "python" ]
stackoverflow_0001819613_django_django_database_python.txt
Q: Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress? I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin: http://simplepie.org/wiki/plugins/wordpress/simp...
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin: http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing Can I find something similar to this for my Django applicati...
[ "You are looking for the universal feed parser.\n", "http://www.djangosnippets.org/tags/rss/\n" ]
[ 1, 0 ]
[]
[]
[ "django", "django_templates", "python", "rss", "simplepie" ]
stackoverflow_0000795976_django_django_templates_python_rss_simplepie.txt
Q: Getting value of TextCtrl from a different wxPanel I was trying to get my first wxWindow application to work and I ran into following difficulty: I create wxPanel and add a wxNotebook object to it. Then I add a page to notebook created from another wxPanel object. How do I access a value of TextCtrl from first wxP...
Getting value of TextCtrl from a different wxPanel
I was trying to get my first wxWindow application to work and I ran into following difficulty: I create wxPanel and add a wxNotebook object to it. Then I add a page to notebook created from another wxPanel object. How do I access a value of TextCtrl from first wxPanel in the second one? import wx class BasicApp(wx.App...
[ "One solution is to pass the control to the constructor of the tab, then you can directly reference it. For example:\nclass Tab1(wx.Panel):\n def __init__(self, parent, id, textCtrl1):\n wx.Panel.__init__(self, parent, id);\n self.textCtrl1 = textCtrl1\n ...\n def Create_OnClick(self, event):\n text1 = ...
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001816353_python_wxpython.txt