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: Using Python or Java, what would be the best way to create charts? I've been searching and found jFreeChart, Python Google Chart and matplotlib. Searching here I also found CairoPlot. I've heard I might be able to use OpenOffice to do it too. Is the API easy to use? Or would it be simpler to stick to one of those ...
Using Python or Java, what would be the best way to create charts?
I've been searching and found jFreeChart, Python Google Chart and matplotlib. Searching here I also found CairoPlot. I've heard I might be able to use OpenOffice to do it too. Is the API easy to use? Or would it be simpler to stick to one of those libraries? I have more experience with Java, but I've read most of Dive ...
[ "I recommend you to use matplotlib, it has high quality backends and a lot of graphical representations, you'll have the whole control over your plots and Python is a very handy and easy language to automatize tests, very practical for what you're willing to do. Matplotlib has also a large community that can help y...
[ 3, 0 ]
[]
[]
[ "charts", "java", "python" ]
stackoverflow_0003170013_charts_java_python.txt
Q: Determining the minimum of a list of n elements I'm having some trouble developing an algorithm to determine the minimum of a list of n elements. It's not the case of finding the minimum of an array of length n, that's simple: min = A[0] for i in range(1, len(A)): if min > A[i]: min = A[i] print min But my li...
Determining the minimum of a list of n elements
I'm having some trouble developing an algorithm to determine the minimum of a list of n elements. It's not the case of finding the minimum of an array of length n, that's simple: min = A[0] for i in range(1, len(A)): if min > A[i]: min = A[i] print min But my list contains objects: class Object: def __init__(s...
[ "filtered = [obj for obj in lst if obj.classification == 'A' and obj.type = 'x']\nmin(filtered, key=lambda x: x.last - x.first)\n\nNote: don't name your variable list: it shadows built-in.\n", "Here's a simple understandable dynamic procedural way of going about it:\nclass Object:\n def __init__(self, somelist...
[ 7, 2, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003169711_algorithm_python.txt
Q: How can I repeat a 3x9 texture in OpenGL's GLSL? I have a texture with a 3x9 repeating section. I don't want to store the tesselated 1920x1080 image that I have for the texture, I'd much rather generate it in code so that it can be applied correctly at other resolutions. Any ideas on how I can do this? The origina...
How can I repeat a 3x9 texture in OpenGL's GLSL?
I have a texture with a 3x9 repeating section. I don't want to store the tesselated 1920x1080 image that I have for the texture, I'd much rather generate it in code so that it can be applied correctly at other resolutions. Any ideas on how I can do this? The original texture is here: http://img684.imageshack.us/img684/...
[ "Almost like you'd do it with fixed pipe. Set your bound texture's wrap mode to repeat before setting sampler uniform and texture coordinates outside 0-1 range will repeat the texture.\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\nglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\nIn...
[ 4 ]
[]
[]
[ "glsl", "opengl", "python", "shader", "textures" ]
stackoverflow_0003169099_glsl_opengl_python_shader_textures.txt
Q: How to use BeautifulSoup to extract from within a HTML paragraph? I'm using BeautifulSoup to do some screen-scraping. My problem is this: I need to extract specific things out of a paragraph. An example: <p><b><a href="/name/abe">ABE</a></b> &nbsp; <font class="masc">m</font> &nbsp; <font class="info"><a href="/nm...
How to use BeautifulSoup to extract from within a HTML paragraph?
I'm using BeautifulSoup to do some screen-scraping. My problem is this: I need to extract specific things out of a paragraph. An example: <p><b><a href="/name/abe">ABE</a></b> &nbsp; <font class="masc">m</font> &nbsp; <font class="info"><a href="/nmc/eng.php" class="usg">English</a>, <a href="/nmc/jew.php" class="usg">...
[ "The following should work...:\nhtm = '''<p><b><a href=\"/name/abe\">ABE</a></b> &nbsp; <font class=\"masc\">m\n</font>&nbsp; <font class=\"info\"><a href=\"/nmc/eng.php\" class=\"usg\">English\n</a>, <a href=\"/nmc/jew.php\" class=\"usg\">Hebrew</a></font><br />\nShort form of <a href=\"/name/abraham\" class=\"nl\...
[ 1, 0 ]
[]
[]
[ "beautifulsoup", "html", "paragraph", "python" ]
stackoverflow_0003169350_beautifulsoup_html_paragraph_python.txt
Q: In python, when using select.select on socket objects, how should I handle sockets that end up on the error list? read, write, error = select.select(sockets, sockets, sockets, 60.0) What is recommended if something ends up in the error list? A: On the operating systems I know, there's nothing you can do with th...
In python, when using select.select on socket objects, how should I handle sockets that end up on the error list?
read, write, error = select.select(sockets, sockets, sockets, 60.0) What is recommended if something ends up in the error list?
[ "On the operating systems I know, there's nothing you can do with the sockets suffering \"exceptional conditions\", except trying to close them (which may raise an exception, so be sure to use a try/except around the attempt). You know that the connections those sockets stood for have terminated abnormally, and ma...
[ 1 ]
[]
[]
[ "python", "select", "sockets" ]
stackoverflow_0003170332_python_select_sockets.txt
Q: I suspect I have multiple version of Python 2.6 installed on Mac OS X 10.6.3; how do I set which one Terminal should launch? When I enter in python in Terminal it loads up Python 2.6.2. However there are folders by the name of Python 2.6 in different places on my drive. I'm not sure if that's because Python 2.6 ha...
I suspect I have multiple version of Python 2.6 installed on Mac OS X 10.6.3; how do I set which one Terminal should launch?
When I enter in python in Terminal it loads up Python 2.6.2. However there are folders by the name of Python 2.6 in different places on my drive. I'm not sure if that's because Python 2.6 has been installed in different places or because Python just likes to have lots of folers in different places. If there are multipl...
[ "When you run python in a shell or command prompt it will execute the first executable file which is found in your PATH environment variable.\nTo find out what file is being executed use which python or where python.\n", "Don't make it complicated. In your ~/.bash_aliases put the following (assuming you are using...
[ 4, 1, 1 ]
[]
[]
[ "macos", "python", "terminal" ]
stackoverflow_0003046183_macos_python_terminal.txt
Q: Google App Engine: UnicodeDecode Error in bulk data upload I'm getting an odd error with Google App Engine devserver 1.3.5, and Python 2.5.4, on Windows. A sample row in the CSV: EQS,550,foobar,"<some><html><garbage /></html></some>",odp,Ti4=,http://url.com,success The error: ........................................
Google App Engine: UnicodeDecode Error in bulk data upload
I'm getting an odd error with Google App Engine devserver 1.3.5, and Python 2.5.4, on Windows. A sample row in the CSV: EQS,550,foobar,"<some><html><garbage /></html></some>",odp,Ti4=,http://url.com,success The error: ........................................................................................................
[ "Looks like some row of the CSV has some non-ascii data (maybe a LATIN SMALL LETTER E WITH GRAVE -- that's what 0xe8 would be in ISO-8859-1, for example) and yet you're mapping it to str (should be unicode, and I believe the CSV should be in utf-8).\nTo find if any row of a text file has non-ascii data, a simple Py...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003170489_google_app_engine_python.txt
Q: Google App Engine: "Cannot create a file when that file already exists" I'm running the Google App Engine devserver 1.3.3 on Windows 7. Usually, this method works fine, but this time it gave an error: def _deleteType(type): results = type.all().fetch(1000) while results: db.delete(results) ...
Google App Engine: "Cannot create a file when that file already exists"
I'm running the Google App Engine devserver 1.3.3 on Windows 7. Usually, this method works fine, but this time it gave an error: def _deleteType(type): results = type.all().fetch(1000) while results: db.delete(results) results = type.all().fetch(1000) The error: File "src\modelutils.py", line...
[ "Unfortunately, 1.3.3 is too far back for me to look at its sources and try to diagnose your problem precisely - the SDK has no 1.3.3 release tag and I can't guess which revision of the datastore_filestub.py was in 1.3.3. Can you upgrade to the current version, 1.3.5, and try again? Running old versions (especial...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003162980_google_app_engine_python.txt
Q: Google application engine, maximum number of static files? I am developing an application in google application engine which would have a user profiles kind of feature. I was going through the Google App's online tutorial where I found that the maximum number of static files (app files and static files) should not...
Google application engine, maximum number of static files?
I am developing an application in google application engine which would have a user profiles kind of feature. I was going through the Google App's online tutorial where I found that the maximum number of static files (app files and static files) should not exceed 3000. I am afraid whether the user's would be able to up...
[ "Welcome to Stack Overflow!\nOne of the limitations in App Engine is that you cannot write directly to the filesystem from your app. Static files would be things like HTML, CSS, javascript and images that are global to your application, and get uploaded manually when you deploy. They are uploaded to and served from...
[ 5, 2, 0 ]
[]
[]
[ "django", "google_app_engine", "python" ]
stackoverflow_0003165753_django_google_app_engine_python.txt
Q: Cross-platform Audio Playback in Python Is there a cross-platform Python library for audio playback available? The operating systems I am targeting are (in order of importance) Windows, Linux, and Mac OSX. The file formats which need to be supported are (in order of importance) MP3, OGG, WAV, and FLAC. Does someth...
Cross-platform Audio Playback in Python
Is there a cross-platform Python library for audio playback available? The operating systems I am targeting are (in order of importance) Windows, Linux, and Mac OSX. The file formats which need to be supported are (in order of importance) MP3, OGG, WAV, and FLAC. Does something like this exist? I have tried a few of th...
[ "gstreamer is multiplatform. It runs on Linux, PPC, ARM, Solaris on x86 and SPARC, MacOSX, Microsoft Windows, IBM OS/400 and Symbian OS.\n", "It's probably overkill for what you want, but I've had good experience with the PyAudiere library. I've had it working on Windows and Linux without trouble, but I haven't ...
[ 2, 1, 1 ]
[]
[]
[ "audio", "linux", "macos", "python", "windows" ]
stackoverflow_0003169666_audio_linux_macos_python_windows.txt
Q: Python library for experimenting with compiler optimizations I want to learn about compilers and some optimization techniques, and I thought it would be helpful to do some quick implementations of the algorithms. Is there a library/framework for Python that can make things easier (like the Natural Language Toolkit...
Python library for experimenting with compiler optimizations
I want to learn about compilers and some optimization techniques, and I thought it would be helpful to do some quick implementations of the algorithms. Is there a library/framework for Python that can make things easier (like the Natural Language Toolkit) - generating the parse tree, manipulating loops, methods? I ...
[ "As far as I know, there is no Python module to do what you want. But you can create structures by yourself in Python, or use PyPy and write your compiler with JIT enabled features in RPython.\nIf you really want to test some algorithms, I highly recommend you to use LLVM, it is in C++, but is the currently state-o...
[ 4 ]
[]
[]
[ "compiler_construction", "optimization", "python" ]
stackoverflow_0003171538_compiler_construction_optimization_python.txt
Q: How can I make a T9 style on-screen keyboard for Windows? Sometimes at night, I like to watch movies in bed, or TV shows online. This is convenient since my computer is right beside my desk, so I just spin one of my monitors around, disable my other screen and pull my mouse over. My keyboard doesn't quite reach wi...
How can I make a T9 style on-screen keyboard for Windows?
Sometimes at night, I like to watch movies in bed, or TV shows online. This is convenient since my computer is right beside my desk, so I just spin one of my monitors around, disable my other screen and pull my mouse over. My keyboard doesn't quite reach without re-routing the cable in a way that doesn't work when I mo...
[ "About 12 years ago, I wrote a program for Windows that sat in the tray and would send keystrokes to certain windows when they gained focus. I no longer have the code, and I've forgotten all the details.\nStill, the process will work something like this.\nFor your GUI, if using Python, you probably want to use PyQT...
[ 3 ]
[]
[]
[ "python", "soft_keyboard", "windows", "windows_7" ]
stackoverflow_0003171045_python_soft_keyboard_windows_windows_7.txt
Q: Passing strings in value field in pyscopg2 Sorry this is a very newbie question. When I'm trying to pass a tuple into an insert statement the quotations seem to disappear. line=[0, 1, 3000248, 'G', 'T', 102, 102, 60, 25] SNPinfo = tuple(line) curs.execute("""INSERT INTO akr (code, chrID, chrLOC, refBase, conBa...
Passing strings in value field in pyscopg2
Sorry this is a very newbie question. When I'm trying to pass a tuple into an insert statement the quotations seem to disappear. line=[0, 1, 3000248, 'G', 'T', 102, 102, 60, 25] SNPinfo = tuple(line) curs.execute("""INSERT INTO akr (code, chrID, chrLOC, refBase, conBase, \ consqual, SNPqual, maxMapqual, numbReadBas...
[ "You are missing the single quotes around the varchars on your string formatting:\ncurs.execute(\"\"\"INSERT INTO akr (code, chrID, chrLOC, refBase, conBase, \\\nconsqual, SNPqual, maxMapqual, numbReadBases) \\\nVALUES (%s,%s,%s,'%s','%s',%s,%s,%s,%s)\"\"\", SNPinfo) \n\nThis would produce:\nINSERT INTO akr (code, ...
[ 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0003170106_psycopg2_python.txt
Q: Python: how do you remember the order of `super`'s arguments? As the title says, how do you remember the order of super's arguments? Is there a mnemonic somewhere I've missed? After years of Python programming, I still have to look it up :( (for the record, it's super(Type, self)) A: Inheritance makes me think o...
Python: how do you remember the order of `super`'s arguments?
As the title says, how do you remember the order of super's arguments? Is there a mnemonic somewhere I've missed? After years of Python programming, I still have to look it up :( (for the record, it's super(Type, self))
[ "Inheritance makes me think of a classification hierarchy. And the order of the arguments to super is hierarchical: first the class, then the instance.\nAnother idea, inspired by the answer from ~unutbu:\nclass Fubb(object):\n def __init__(self, *args, **kw):\n # Crap, I can't remember how super() goes!?\...
[ 11, 10, 5, 2 ]
[]
[]
[ "python", "super" ]
stackoverflow_0003171824_python_super.txt
Q: Is it possible to put a toolbar button on the right side of it using wxpython? I'm making a toolbar using wxpython and I want to put the Quit button on the right side of it, I don't want to put them sequencially. Is it possible to define this position? Thanks in advance! A: If you add the quit button last, it wi...
Is it possible to put a toolbar button on the right side of it using wxpython?
I'm making a toolbar using wxpython and I want to put the Quit button on the right side of it, I don't want to put them sequencially. Is it possible to define this position? Thanks in advance!
[ "If you add the quit button last, it will be on the right side.\n" ]
[ 0 ]
[]
[]
[ "button", "position", "python", "toolbar", "wxpython" ]
stackoverflow_0002964108_button_position_python_toolbar_wxpython.txt
Q: Comparing if datetime.datetime exists or None I'm running a small app on Google App Engine with Python. In the model I have a property of type DateTimeProperty, which is datetime.datetime. When it's created there is no value (i.e. "None"). I want compare if that datetime.datetime is None, but I can't. if object.up...
Comparing if datetime.datetime exists or None
I'm running a small app on Google App Engine with Python. In the model I have a property of type DateTimeProperty, which is datetime.datetime. When it's created there is no value (i.e. "None"). I want compare if that datetime.datetime is None, but I can't. if object.updated_date is None or object.updated_date >= past: ...
[ "Given that the previous discussion seems to have established that either of the variables could be None, one approach would be (assuming you want to set object.updated_date when either of the variables is None):\nif None in (past, object.updated_date) or object.updated_date >= past:\n object.updated_date = now\n\...
[ 7, 6, 3 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003170640_google_app_engine_python.txt
Q: Is there any way to store cookies in django which is independent to browser? Is there any way in django to store cookies which is independent to browser ? is there any technique just like what flash SharedObject does ..? A: A Django view receives an instance of HttpRequest as its first argument. That object has...
Is there any way to store cookies in django which is independent to browser?
Is there any way in django to store cookies which is independent to browser ? is there any technique just like what flash SharedObject does ..?
[ "A Django view receives an instance of HttpRequest as its first argument. That object has an attribute COOKIES which is, and I quote,\n\nA standard Python dictionary\n containing all cookies. Keys and\n values are strings.\n\nYou can of course save that dictionary in any way you like (e.g., pickle it into a blob...
[ 2, 1, 0 ]
[]
[]
[ "cookies", "django", "flash", "python" ]
stackoverflow_0003171404_cookies_django_flash_python.txt
Q: Most Efficient way to calculate Frequency of values in a Python list? I am looking for a fast and efficient way to calculate the frequency of list items in python: list = ['a','b','a','b', ......] I want a frequency counter which would give me an output like this: [ ('a', 10),('b', 8) ...] The items should be a...
Most Efficient way to calculate Frequency of values in a Python list?
I am looking for a fast and efficient way to calculate the frequency of list items in python: list = ['a','b','a','b', ......] I want a frequency counter which would give me an output like this: [ ('a', 10),('b', 8) ...] The items should be arranged in descending order of frequency as shown above.
[ "Python2.7+\n>>> from collections import Counter\n>>> L=['a','b','a','b']\n>>> print(Counter(L))\nCounter({'a': 2, 'b': 2})\n>>> print(Counter(L).items())\ndict_items([('a', 2), ('b', 2)])\n\npython2.5/2.6\n>>> from collections import defaultdict\n>>> L=['a','b','a','b']\n>>> d=defaultdict(int)\n>>> for item in L:\...
[ 33 ]
[]
[]
[ "frequency", "list", "python" ]
stackoverflow_0003172173_frequency_list_python.txt
Q: wxPython segmentation fault with Editors I have created a wx.grid.Grid with a wx.grid.PyGridTableBase derived class to provide its data. I want to also to control the editors used on the table. Towards that end I defined the following method def GetAttr(self, row, col, kind): attr = wx.grid.GridCellAttr() ...
wxPython segmentation fault with Editors
I have created a wx.grid.Grid with a wx.grid.PyGridTableBase derived class to provide its data. I want to also to control the editors used on the table. Towards that end I defined the following method def GetAttr(self, row, col, kind): attr = wx.grid.GridCellAttr() if col == 0: attr.SetEditor( wx.grid.G...
[ "I figured out the problem:\nThe wxWidgets code assumes that the same Editor will be consistently returned from GetCellAttr. Returning a different editor each time as I was doing caused the segmentation faults.\nIn order to return the same editor multiple times I also need to call IncRef() on the editor to keep it ...
[ 4, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003168971_python_wxpython.txt
Q: Splitting words in running text using Python? I am writing a piece of code which will extract words from running text. This text can contain delimiters like \r,\n etc. which might be there in text. I want to discard all these delimiters and only extract full words. How can I do this with Python? any library avail...
Splitting words in running text using Python?
I am writing a piece of code which will extract words from running text. This text can contain delimiters like \r,\n etc. which might be there in text. I want to discard all these delimiters and only extract full words. How can I do this with Python? any library available for crunching text in python?
[ "Assuming your definition of \"word\" agrees with that of the regular expression module (re), that is, letters, digits and underscores, it's easy:\nimport re\nfullwords = re.findall(r'\\w+', thetext)\n\nwhere thetext is the string in question (e.g., coming from an f.read() of a file object f open for reading, if th...
[ 5, 1 ]
[]
[]
[ "parsing", "python", "text_processing" ]
stackoverflow_0003172236_parsing_python_text_processing.txt
Q: Un/bound methods in Cheetah Is there a way to declare static methods in cheetah? IE snippets.tmpl #def address($address, $title) <div class="address"> <b>$title</h1></b> #if $address.title $address.title <br/> #end if $address.line1 <br/> #if $address.line2 $address.line2 <br/> #end if $address.town, $address.stat...
Un/bound methods in Cheetah
Is there a way to declare static methods in cheetah? IE snippets.tmpl #def address($address, $title) <div class="address"> <b>$title</h1></b> #if $address.title $address.title <br/> #end if $address.line1 <br/> #if $address.line2 $address.line2 <br/> #end if $address.town, $address.state $address.zipcode </div> #end de...
[ "This page seems to have some relevant information, but I'm not in a position to try it out myself right now, sorry.\nSpecifically, you should just be able to do:\n#@staticmethod\n#def address($address, $title)\n\n...and have it work.\n(If you didn't know, staticmethod is a built-in function that creates a... stati...
[ 0 ]
[]
[]
[ "cheetah", "python" ]
stackoverflow_0003172279_cheetah_python.txt
Q: python curses.newwin not working I'm learning curses for the first time, and I decided to do it in python because it would be easier than constantly recompiling. However, I've hit a hitch. When I try to update a seccond window, I get no output. Here's a code snippet: import curses win = curses.initscr() curses.no...
python curses.newwin not working
I'm learning curses for the first time, and I decided to do it in python because it would be easier than constantly recompiling. However, I've hit a hitch. When I try to update a seccond window, I get no output. Here's a code snippet: import curses win = curses.initscr() curses.noecho() curses.cbreak() curses.curs_set...
[ "Seems OK to me -- I always use curses.wrapper and my terminal doesn't support cursor visibility of 0, so this is what I have...:\nimport curses\n\nex = None\n\ndef main(stdscr):\n global ex\n try:\n curses.curs_set(0)\n except Exception, e:\n ex = e\n\n field = curses.newwin(1, 20, 1, 1)\...
[ 4, 2 ]
[]
[]
[ "curses", "python", "window", "windows" ]
stackoverflow_0003170406_curses_python_window_windows.txt
Q: Access Gmail atom feed using OAuth I'm trying to grab the Gmail atom feed from a python application using OAuth. I have a working application that downloads the Google Reader feed, and I think it should simply be a matter of changing the scope and feed URLs. After replacing the URLs I can still successfully get Re...
Access Gmail atom feed using OAuth
I'm trying to grab the Gmail atom feed from a python application using OAuth. I have a working application that downloads the Google Reader feed, and I think it should simply be a matter of changing the scope and feed URLs. After replacing the URLs I can still successfully get Request and Access tokens, but when I try ...
[ "You might want to try accessing Google's IMAP servers with OAuth instead of using the ATOM feed. After a little googling I found this:\n\n\"Gmail supports OAuth over IMAP and\n SMTP via a standard they call XOAUTH.\n This allows you to authenticate\n against Gmail's IMAP and SMTP servers\n using an OAuth token...
[ 3 ]
[]
[]
[ "gdata", "gmail", "oauth", "python" ]
stackoverflow_0003170347_gdata_gmail_oauth_python.txt
Q: How to draw a spherical triangle on a sphere in 3D? Suppose you know the three vertices for a spherical triangle. Then how do you draw the sides on a sphere in 3D? I need some python code to use in Blender 3d modelisation software. I already have the sphere done in 3D in Blender. Thanks & happy blendering. note ...
How to draw a spherical triangle on a sphere in 3D?
Suppose you know the three vertices for a spherical triangle. Then how do you draw the sides on a sphere in 3D? I need some python code to use in Blender 3d modelisation software. I already have the sphere done in 3D in Blender. Thanks & happy blendering. note 1: i have the 3 points / vertices (p1,p2,p3 ) on the sphe...
[ "Create Sine Mesh\nPython code to create a sine wave mesh in Blender:\nimport math\nimport Blender\nfrom Blender import NMesh\n\nx = -1 * math.pi\n\nmesh = NMesh.GetRaw()\nvNew = NMesh.Vert( x, math.sin( x ), 0 )\nmesh.verts.append( vNew )\n\nwhile x < math.pi:\n x += 0.1\n vOld = vNew\n vNew = NMesh.Vert( x, math....
[ 4, 0 ]
[]
[]
[ "blender", "python" ]
stackoverflow_0003172535_blender_python.txt
Q: how to show chinese word , not unicode word this is my code: from whoosh.analysis import RegexAnalyzer rex = RegexAnalyzer(re.compile(ur"([\u4e00-\u9fa5])|(\w+(\.?\w+)*)")) a=[(token.text) for token in rex(u"hi 中 000 中文测试中文 there 3.141 big-time under_score")] self.render_template('index.html',{'a':a})...
how to show chinese word , not unicode word
this is my code: from whoosh.analysis import RegexAnalyzer rex = RegexAnalyzer(re.compile(ur"([\u4e00-\u9fa5])|(\w+(\.?\w+)*)")) a=[(token.text) for token in rex(u"hi 中 000 中文测试中文 there 3.141 big-time under_score")] self.render_template('index.html',{'a':a}) and it show this on the web page: [u'hi', u'\u4...
[ "By default, printing a larger built-in structure gives the repr() of each of the elements. If you want the str()/unicode() instead then you need to iterate over the sequence yourself.\na = u\"['\" + u\"', '\".join(token.text for token in ...) + u\"']\"\nprint a\n\n" ]
[ 3 ]
[]
[]
[ "list", "python", "string", "utf_8" ]
stackoverflow_0003172741_list_python_string_utf_8.txt
Q: Open File with Python I am writing a tkinter program that is kind of a program that is like a portfolio and opens up other programs also writen in python. So for example i have FILE_1 and FILE_2 and i want to write a program that onced clicked on a certain button opens either FILE_1 or FILE_2. i dont need help w...
Open File with Python
I am writing a tkinter program that is kind of a program that is like a portfolio and opens up other programs also writen in python. So for example i have FILE_1 and FILE_2 and i want to write a program that onced clicked on a certain button opens either FILE_1 or FILE_2. i dont need help with the look like with butt...
[ "Hook the button up a callback which calls subprocess.Popen:\nimport subprocess\np=subprocess.Popen('FILE_1.py')\np.communicate()\n\nThis will try to run FILE_1.py as a separate process. \np.communicate() will cause your main program to wait until FILE_1.py exits.\n" ]
[ 3 ]
[]
[]
[ "file_io", "popen", "python", "tkinter" ]
stackoverflow_0003172787_file_io_popen_python_tkinter.txt
Q: Python: Google App Engine source uses tab depth 2 Looking through the Google App Engine source, I noticed that the tab depth is 2 spaces instead of the conventional 4. Is there some wisdom behind this, or is it just someone's preference? (Maybe it's trivial, or maybe Google knows something that isn't immediately ...
Python: Google App Engine source uses tab depth 2
Looking through the Google App Engine source, I noticed that the tab depth is 2 spaces instead of the conventional 4. Is there some wisdom behind this, or is it just someone's preference? (Maybe it's trivial, or maybe Google knows something that isn't immediately obvious.) UPDATE I wasn't suggesting that it ran differ...
[ "The Google Python Style Guide is published here, and, besides being generally vaster than \nPEP 8, it also differs from it in some aspects. However, the published version of the guide does mandate 4-space indents (like PEP 8 and like just about everybody else does).\nWithin Google, however, the actual rule is two...
[ 5, 3 ]
[ "It's miserably bad style. 2-space indentation is simply unreadable. Don't copy it. Never use less than 4 spaces to indent in any language.\n(Don't assume that something is good simply because Google source is doing it. If you've ever spent some time looking through the Android source you'd know that there's as...
[ -6 ]
[ "google_app_engine", "python" ]
stackoverflow_0003172893_google_app_engine_python.txt
Q: Flattening mixed lists in Python (containing iterables and noniterables) Possible Duplicate: Flatten (an irregular) list of lists in Python How would I go about flattening a list in Python that contains both iterables and noniterables, such as [1, [2, 3, 4], 5, [6]]? The result should be [1,2,3,4,5,6], and lists...
Flattening mixed lists in Python (containing iterables and noniterables)
Possible Duplicate: Flatten (an irregular) list of lists in Python How would I go about flattening a list in Python that contains both iterables and noniterables, such as [1, [2, 3, 4], 5, [6]]? The result should be [1,2,3,4,5,6], and lists of lists of lists (etc.) are certain never to occur. I have tried using iter...
[ "So you want to flatten only 1 or 2 levels, not recursively to further depts; and only within lists, not other iterables such as strings, tuples, arrays... did I get your specs right? OK, if so, then...:\ndef flat2gen(alist):\n for item in alist:\n if isinstance(item, list):\n for subitem in item: yield s...
[ 3 ]
[]
[]
[ "arrays", "list", "python" ]
stackoverflow_0003172930_arrays_list_python.txt
Q: Google App Engine: "Error: Server Error" but nothing in the logs I deployed an app to Google App Engine. When I navigate to it, I get this: Error: Server Error The server encountered an error and could not complete your request. If the problem persists, please report your problem and mention this error me...
Google App Engine: "Error: Server Error" but nothing in the logs
I deployed an app to Google App Engine. When I navigate to it, I get this: Error: Server Error The server encountered an error and could not complete your request. If the problem persists, please report your problem and mention this error message and the query that caused it. All the pages do this. appcfg.py ...
[ "If you build your application abject (assuming you're using the webapp microframework that comes with App Engine, since you haven't mentioned that crucial detail;-) in the following way...:\napplication = webapp.WSGIApplication(url_to_handlers, debug=True)\n\nthe debug=True means you should be seeing a traceback i...
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003172856_google_app_engine_python.txt
Q: pyparsing ambiguity I'm trying to parse some text using PyParser. The problem is that I have names that can contain white spaces. So my input might look like this. First, a list of names: Joe bob Jimmy X grjiaer-rreaijgr Y Then, things they do: Joe A bob B Jimmy X C the problem of course is that a thing they do ...
pyparsing ambiguity
I'm trying to parse some text using PyParser. The problem is that I have names that can contain white spaces. So my input might look like this. First, a list of names: Joe bob Jimmy X grjiaer-rreaijgr Y Then, things they do: Joe A bob B Jimmy X C the problem of course is that a thing they do can be the same as the en...
[ "You pretty much need more than a simple parser. Parsers use the symbols in a string to define which pieces of the string represent different elements of a grammar. This is why FM asked for some clue to indicate how you know what part is the name and what part is the rest of the sentence. If you could say that n...
[ 2, 1, 0 ]
[]
[]
[ "parsing", "pyparsing", "python" ]
stackoverflow_0002982219_parsing_pyparsing_python.txt
Q: In interactive Python, how to unambiguously import a module In interactive python I'd like to import a module that is in, say, C:\Modules\Module1\module.py What I've been able to do is to create an empty C:\Modules\Module1\__init__.py and then do: >>> import sys >>> sys.path.append(r'C:\Modules\Module1') >>> im...
In interactive Python, how to unambiguously import a module
In interactive python I'd like to import a module that is in, say, C:\Modules\Module1\module.py What I've been able to do is to create an empty C:\Modules\Module1\__init__.py and then do: >>> import sys >>> sys.path.append(r'C:\Modules\Module1') >>> import module And that works, but I'm having to append to sys.path...
[ "EDIT: Here's something I'd forgotten about: Is this correct way to import python scripts residing in arbitrary folders? I'll leave the rest of my answer here for reference.\n\nThere is, but you'd basically wind up writing your own importer which manually creates a new module object and uses execfile to run the mod...
[ 4, 1 ]
[]
[]
[ "import", "path", "python" ]
stackoverflow_0003173229_import_path_python.txt
Q: Python: Passing functions with arguments to a built-in function? like this question I want to pass a function with arguments. But I want to pass it to built-in functions. Example: files = [ 'hey.txt', 'hello.txt', 'goodbye.jpg', 'howdy.gif' ] def filterex(path, ex): pat = r'.+\.(' + ex + ')$' match = re.searc...
Python: Passing functions with arguments to a built-in function?
like this question I want to pass a function with arguments. But I want to pass it to built-in functions. Example: files = [ 'hey.txt', 'hello.txt', 'goodbye.jpg', 'howdy.gif' ] def filterex(path, ex): pat = r'.+\.(' + ex + ')$' match = re.search(pat, path) return match and match.group(1) == ex) I cou...
[ "def make_filter(ex):\n def do_filter(path):\n pat = r'.+\\.(' + ex + ')$'\n match = re.search(pat, path)\n return match and match.group(1) == ex\n return do_filter\n\nfilter(make_filter('txt'), files)\n\nOr if you don't want to modify filterex:\nfilter(lambda path: filterex(path, 'txt'),...
[ 8, 3 ]
[]
[]
[ "python", "refactoring" ]
stackoverflow_0003173355_python_refactoring.txt
Q: Python event handler method not returning value in conditional I'm completely new to python (and it's been a while since I've coded much). I'm trying to call a method which acts as an event handler in a little "hello world" type game, but it's not working at all. I'm using the pygames 1.9.1 lib with python 2.6.1 ...
Python event handler method not returning value in conditional
I'm completely new to python (and it's been a while since I've coded much). I'm trying to call a method which acts as an event handler in a little "hello world" type game, but it's not working at all. I'm using the pygames 1.9.1 lib with python 2.6.1 on OSX 10.6.3. So this is in a while loop: self.exitCheck() ...
[ "Aren't you missing some parentheses there? \nif self.controlUpdate() == True:\n", "Edit: The problem is that pygame.event.get() both returns and removes all events from the event queue. This means that every time you call controlUpdate(), the event queue will be empty and nothing inside the for loop will be exe...
[ 3, 1 ]
[]
[]
[ "conditional", "pygame", "python" ]
stackoverflow_0003173385_conditional_pygame_python.txt
Q: Problem creating a vritualenv using virtualenv with OS X So I'm not sure what my problem is. Trying to configure a virtualenv this is the error I get: 20:59:51 $ virtualenv test -p /usr/local/bin/python Running virtualenv with interpreter /usr/local/bin/python New python executable in test/bin/python Please make s...
Problem creating a vritualenv using virtualenv with OS X
So I'm not sure what my problem is. Trying to configure a virtualenv this is the error I get: 20:59:51 $ virtualenv test -p /usr/local/bin/python Running virtualenv with interpreter /usr/local/bin/python New python executable in test/bin/python Please make sure you remove any previous custom paths from your /Users/nlan...
[ "It's hard to tell exactly what's going on from the truncated output provided but it appears you are trying to update an existing virtual environment (note the Overwriting message). First, verify that the python at /usr/local/bin/python works correctly on its own. Then, try creating a virtualenv in a new (non-exi...
[ 0 ]
[]
[]
[ "python", "virtualenv" ]
stackoverflow_0003173482_python_virtualenv.txt
Q: Word Frequency in text using Python but disregard stop words This gives me a frequency of words in a text: fullWords = re.findall(r'\w+', allText) d = defaultdict(int) for word in fullWords : d[word] += 1 finalFreq = sorted(d.iteritems(), key = operator.itemgetter(1), reverse=True) self.response...
Word Frequency in text using Python but disregard stop words
This gives me a frequency of words in a text: fullWords = re.findall(r'\w+', allText) d = defaultdict(int) for word in fullWords : d[word] += 1 finalFreq = sorted(d.iteritems(), key = operator.itemgetter(1), reverse=True) self.response.out.write(finalFreq) This also gives me useless words like "the"...
[ "You can download lists of stopwords as files in various formats, e.g. from here -- all Python needs to do is to read the file (and these are in csv format, easily read with the csv module), make a set, and use membership in that set (probably with some normalization, e.g., lowercasing) to exclude words from the co...
[ 5, 3, 2, 0 ]
[]
[]
[ "frequency_analysis", "google_app_engine", "python", "word_frequency" ]
stackoverflow_0003173592_frequency_analysis_google_app_engine_python_word_frequency.txt
Q: difficulty with Python def myfunc(x): y = x y.append('How do I stop Python from modifying x here?') return y x = [] z = myfunc(x) print(x) A: You do: y = x[:] to make a copy of list x. A: You need to copy X before you modify it, def myfunc(x): y = list(x) y.append('How do I stop Python from modifying x...
difficulty with Python
def myfunc(x): y = x y.append('How do I stop Python from modifying x here?') return y x = [] z = myfunc(x) print(x)
[ "You do:\ny = x[:]\n\nto make a copy of list x.\n", "You need to copy X before you modify it, \ndef myfunc(x):\n y = list(x)\n y.append('How do I stop Python from modifying x here?')\n return y\n\nx = []\nz = myfunc(x)\nprint(x)\n\n" ]
[ 11, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003173660_python.txt
Q: Python: finding files with matching extensions or extensions with matching names in a list Suppose I have a list of filenames: [exia.gundam, dynames.gundam, kyrios.gundam, virtue.gundam], or [exia.frame, exia.head, exia.swords, exia.legs, exia.arms, exia.pilot, exia.gn_drive, lockon_stratos.data, tieria_erde.data,...
Python: finding files with matching extensions or extensions with matching names in a list
Suppose I have a list of filenames: [exia.gundam, dynames.gundam, kyrios.gundam, virtue.gundam], or [exia.frame, exia.head, exia.swords, exia.legs, exia.arms, exia.pilot, exia.gn_drive, lockon_stratos.data, tieria_erde.data, ribbons_almark.data, otherstuff.dada]. In one iteration, I'd like to have all the *.gundam or *...
[ "In my first version, it looks like I misinterpreted your question. So if I've got this correct, you're trying to process a list of files so that you can easily access all the filenames with a given extension, or all the filenames with a given base (\"base\" being the part before the period)?\nIf that's the case, I...
[ 2, 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0003173652_python_regex_string.txt
Q: WxPython custom styled controls I'd need to make a new style for buttons and text entry controls. It should look something like Is there a way to do this? A: For a start, try to look up the wx.Frame style property wx.FRAME_SHAPED here: http://docs.wxwidgets.org/stable/wx_wxframe.html#wxframe I think it only app...
WxPython custom styled controls
I'd need to make a new style for buttons and text entry controls. It should look something like Is there a way to do this?
[ "For a start, try to look up the wx.Frame style property wx.FRAME_SHAPED here: http://docs.wxwidgets.org/stable/wx_wxframe.html#wxframe\nI think it only applies to wx.Frame but maybe you can bind an event to mouse clicks inside the custom-shaped frame.\n" ]
[ 1 ]
[]
[]
[ "controls", "python", "wxpython" ]
stackoverflow_0003171044_controls_python_wxpython.txt
Q: VIM: Preview height I am new to vim so I was trying to edit an existing script for the vimrc file. The script will take the content of the current buffer and copy it into a new window and then run Python. The scrip works but the preview window is always 50% of the current window. This is the script: " Preview win...
VIM: Preview height
I am new to vim so I was trying to edit an existing script for the vimrc file. The script will take the content of the current buffer and copy it into a new window and then run Python. The scrip works but the preview window is always 50% of the current window. This is the script: " Preview window for python fu! DoRunP...
[ "You could try changing the window height before setting it to 'previewwindow':\n\" copy the buffer into a new window, then run that buffer through python\nsil %y a | below new | sil put a | sil %!python -\n\" indicate the output window as the current previewwindow\nsetlocal winheight 20\nsetlocal previewwindow ro ...
[ 4 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0003173950_python_vim.txt
Q: Py-appscript: How to configure mail created by reply() I'm trying to reply to a mail in Mail.app with py-appscript. I tried the code below, from appscript import * mailapp = app('Mail') # get mail to be replied msg = mailapp.accounts.first.mailboxes.first.messages.first # create reply mail reply_msg = mailapp.r...
Py-appscript: How to configure mail created by reply()
I'm trying to reply to a mail in Mail.app with py-appscript. I tried the code below, from appscript import * mailapp = app('Mail') # get mail to be replied msg = mailapp.accounts.first.mailboxes.first.messages.first # create reply mail reply_msg = mailapp.reply(msg) # set mail (got error) reply_msg.visible.set(True...
[ "Works fine on 10.6 but there's a bug in Mail on 10.5 (and probably earlier) that causes outgoing messages created by the reply command not to work correctly. \nIf you have to support 10.5, I think your only option is to build a new outgoing message from scratch, copying the relevant information from the message yo...
[ 0 ]
[]
[]
[ "applescript", "python" ]
stackoverflow_0003173361_applescript_python.txt
Q: How to spider a password protected site in python? currently I have a spider written in Java that logs into a supplier website and spiders the website. (using htmlunit) It keeps the session (cookie) and even lets me enable/disable javascript etc. I also use htmlparser (java) to help parse the html and extract the ...
How to spider a password protected site in python?
currently I have a spider written in Java that logs into a supplier website and spiders the website. (using htmlunit) It keeps the session (cookie) and even lets me enable/disable javascript etc. I also use htmlparser (java) to help parse the html and extract the relevant information. Does python have something similar...
[ "Python has urllib2 to crawl pages, which supports password authentication and cookies.\nThere is also a HTMLParser for extracting html, but some people prefer the more feature-full BeatifulSoup.\n", "Scrapy API uses urllib2 plus adds wires up some different parsers and helper routines.\n" ]
[ 4, 1 ]
[]
[]
[ "python", "web_crawler" ]
stackoverflow_0003173433_python_web_crawler.txt
Q: HTML Tag Cloud creation using Python? Is there a library which can take a python dict with word freq = { 'abc' : 25, .... } and convert this into a html based Tag Cloud? A: There a numerous examples for this on the web, e.g. here: http://sujitpal.blogspot.com/2007/04/building-tag-cloud-with-python.html http://...
HTML Tag Cloud creation using Python?
Is there a library which can take a python dict with word freq = { 'abc' : 25, .... } and convert this into a html based Tag Cloud?
[ "There a numerous examples for this on the web, e.g. here:\n\nhttp://sujitpal.blogspot.com/2007/04/building-tag-cloud-with-python.html\nhttp://snipplr.com/view/8875/tag-cloud/\nhttp://pypi.python.org/pypi/cs.tags/0.1.1\nand more ...\n\n" ]
[ 3 ]
[]
[]
[ "dictionary", "python", "tag_cloud" ]
stackoverflow_0003173734_dictionary_python_tag_cloud.txt
Q: How do I stop a Python function from modifying its inputs? I've asked almost this just before now, but the fix doesn't work for x = [[]], which I'm guessing is because it is a nested list, which is what I will be working with. def myfunc(w): y = w[:] y[0].append('What do I need to do to get this to work here?') ...
How do I stop a Python function from modifying its inputs?
I've asked almost this just before now, but the fix doesn't work for x = [[]], which I'm guessing is because it is a nested list, which is what I will be working with. def myfunc(w): y = w[:] y[0].append('What do I need to do to get this to work here?') y[0].append('When I search for the manual, I get pointed to pyt...
[ "Here's how you could fix your problem:\ndef myfunc(w):\n y = [el[:] for el in w]\n y[0].append('What do I need to do to get this to work here?')\n y[0].append('When I search for the manual, I get pointed to python.org, but I can\\'t find the answer there.')\n return y\n\nx = [[]]\nz = myfunc(x)\nprint(...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003173875_python.txt
Q: decomposing a string into known patterns Here's the python list of strings: patterns = [ "KBKKB", "BBBK", "BKB", "KBBB", "KBB", "BKBB", "BBKB", "KKBKB", "BKBK", "KBKB", "KBKBK", "BBK", "BB", "BKKB", "BBB", "KBBK", "BKKBK", "KB", "KBKBK", "KKBKKB", "KBK", "BBKBK", "BBBB", "BK", "KKBKBK", "KBBKB", "BBKKB", "KKKKBB",...
decomposing a string into known patterns
Here's the python list of strings: patterns = [ "KBKKB", "BBBK", "BKB", "KBBB", "KBB", "BKBB", "BBKB", "KKBKB", "BKBK", "KBKB", "KBKBK", "BBK", "BB", "BKKB", "BBB", "KBBK", "BKKBK", "KB", "KBKBK", "KKBKKB", "KBK", "BBKBK", "BBBB", "BK", "KKBKBK", "KBBKB", "BBKKB", "KKKKBB", "KKB" ] I have an input string that consist o...
[ "Here's one way using recursion:\ndef getPossibleDecompositions(s):\n if s == '':\n yield []\n else:\n for pattern in patterns:\n if s.startswith(pattern):\n for x in getPossibleDecompositions(s[len(pattern):]):\n yield [pattern] + x\n\nfor x in getPo...
[ 5 ]
[]
[]
[ "pattern_matching", "python", "string" ]
stackoverflow_0003174586_pattern_matching_python_string.txt
Q: Does ruby have something similar to buildout or virtualenv? I was wondering: In python, canon says to use buildout or virtualenv, to avoid installing into the system packages. It's second nature now, I no longer see anything ludicrously bizarre to the practice. It makes a kind of sense. In Ruby, is there somethi...
Does ruby have something similar to buildout or virtualenv?
I was wondering: In python, canon says to use buildout or virtualenv, to avoid installing into the system packages. It's second nature now, I no longer see anything ludicrously bizarre to the practice. It makes a kind of sense. In Ruby, is there something similar? How does ruby deal with this problem? Does ruby hav...
[ "There are several projects trying to handle this issue:\n\nrip\nbundler\nrvm via gemsets\nsandbox\n\n" ]
[ 7 ]
[]
[]
[ "buildout", "python", "ruby", "virtualenv" ]
stackoverflow_0003173792_buildout_python_ruby_virtualenv.txt
Q: How to make a dynamic number of horizontal BoxSizers? I have a function that calculates the number of images that can be displayed on the screen, if there are more images than the ones that can be put on screen, I resize the images till they all can appear. Then, I want to display them with one vertical box sizer ...
How to make a dynamic number of horizontal BoxSizers?
I have a function that calculates the number of images that can be displayed on the screen, if there are more images than the ones that can be put on screen, I resize the images till they all can appear. Then, I want to display them with one vertical box sizer and several horizontal box sizers! The horizontal number of...
[ "Why not simply make the horizontal sizers in a loop, .Adding them to the same vertical sizer? E.g.\ndef HorzInVert(n):\n vert = wx.BoxSizer(wx.VERTICAL)\n horizontals = []\n for i in range(n):\n horz = wx.BoxSizer(wx.HORIZONTAL)\n vert.Add(horz,1, wx.ALL, 0)\n horizontals.append(horz)\n return vert, ...
[ 3, 0 ]
[]
[]
[ "python", "sizer", "wxpython" ]
stackoverflow_0003171256_python_sizer_wxpython.txt
Q: How to create a Cocoa library and use it in python I've been making a game and the python library I was used is terrible (Pyglet). I want to try using Cocoa for the OSX version. I'll be able to figure out using the objects from classes like NSWindow and NSOpenGLView and then put these objects in my own class for t...
How to create a Cocoa library and use it in python
I've been making a game and the python library I was used is terrible (Pyglet). I want to try using Cocoa for the OSX version. I'll be able to figure out using the objects from classes like NSWindow and NSOpenGLView and then put these objects in my own class for the game loop. I have no idea how I can use PyObjC to loa...
[ "PyObjC bridges Python to the Objective-C runtime, so if you create NSObject subclasses in Python, they'll be accessible from Objective-C code running in the same process. What this means is that you'll need to encapsulate all of your Python functionality in a subclass of NSObject that you can access over the bridg...
[ 2 ]
[]
[]
[ "cocoa", "objective_c", "pyobjc", "python" ]
stackoverflow_0003171650_cocoa_objective_c_pyobjc_python.txt
Q: Need help making a program remember settings, cPickle How do I make this code remember the last position of the scale, upon reopening? import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(Fa...
Need help making a program remember settings, cPickle
How do I make this code remember the last position of the scale, upon reopening? import Tkinter import cPickle root = Tkinter.Tk() root.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1) root.sclX.pack(ipadx=75) root.resizable(False,False) root.title('Scale') with open('myconfig.pk'...
[ "You need many changes and fixes to make your code work as intended:\nimport Tkinter\nimport cPickle\n\nroot = Tkinter.Tk()\nplace = 0\nroot.place = Tkinter.IntVar()\nroot.sclX = Tkinter.Scale(root, from_=0, to=1500, orient='horizontal', resolution=1,\n variable=root.place)\nroot.sclX.pack(...
[ 2 ]
[]
[]
[ "pickle", "python", "tkinter" ]
stackoverflow_0003173897_pickle_python_tkinter.txt
Q: how to submit the query to http://www.ratsit.se/BC/Search.aspx ? I write a script but seems something wrong with the "Click" button import urllib2, cookielib import ClientForm from BeautifulSoup import BeautifulSoup first_name = "Mona" last_name = "Sahlin" url = 'http://www.ratsit.se/BC/Search.aspx' cookiejar = c...
how to submit the query to http://www.ratsit.se/BC/Search.aspx ? I write a script but seems something wrong with the "Click" button
import urllib2, cookielib import ClientForm from BeautifulSoup import BeautifulSoup first_name = "Mona" last_name = "Sahlin" url = 'http://www.ratsit.se/BC/Search.aspx' cookiejar = cookielib.LWPCookieJar() cookiejar = urllib2.HTTPCookieProcessor(cookiejar) opener = urllib2.build_opener(cookiejar) urllib2.install_open...
[ "Here's a working version:\nimport urllib2, cookielib\nimport ClientForm\nfrom BeautifulSoup import BeautifulSoup\n\nfirst_name = \"Mona\"\nlast_name = \"Sahlin\"\nurl = 'http://www.ratsit.se/BC/Search.aspx'\ncookiejar = cookielib.LWPCookieJar()\ncookiejar = urllib2.HTTPCookieProcessor(cookiejar)\n\nopener = urllib...
[ 1 ]
[]
[]
[ "asp.net", "clientform", "python" ]
stackoverflow_0003174924_asp.net_clientform_python.txt
Q: bezier triangle patch in 3D i would like a python script to draw in 3D a triangle bezier patch this is an old problem and there must be some old script available to do this somehwere! Thanks for any help A: OpenGL RedBook, "Chapter 12 Evaluators and NURBS". C examples are here. But I really don't think you'll b...
bezier triangle patch in 3D
i would like a python script to draw in 3D a triangle bezier patch this is an old problem and there must be some old script available to do this somehwere! Thanks for any help
[ "OpenGL RedBook, \"Chapter 12 Evaluators and NURBS\". C examples are here. But I really don't think you'll be able to use it on triangles, only on quads. If you want to go through the trouble of tesselating triangle, pick spline formula from wikipedia, and try to implement it yourself.\n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0003174603_python.txt
Q: How to design a twisted solution to download a file by reading on certain portion? How do I download a remote file into several chunks using twisted? Lets say if the file is 100 bytes, I want to spawn 10 connection which will read 10 bytes each but in no particular order and then later on merge them all. I was abl...
How to design a twisted solution to download a file by reading on certain portion?
How do I download a remote file into several chunks using twisted? Lets say if the file is 100 bytes, I want to spawn 10 connection which will read 10 bytes each but in no particular order and then later on merge them all. I was able to do this using threads in Python but I don't have any idea how to use twisted's reac...
[ "I don't think this really provides the direction the user requires - the question seems to be clear in how to use Twisted to achieve this - the answer implies reasonable knowledge of Twisted.\n" ]
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003174374_python_twisted.txt
Q: Delimiting choices in ModelChoiceField I'm new to python and to django so this question will probably be easy to solve but I can't get it to work. Basically I have a model which contains two foreign keys of User type. I'm building a form in which I want to remove one of the choices of a ModelChoiceField based on a...
Delimiting choices in ModelChoiceField
I'm new to python and to django so this question will probably be easy to solve but I can't get it to work. Basically I have a model which contains two foreign keys of User type. I'm building a form in which I want to remove one of the choices of a ModelChoiceField based on another field. I want the user to be unable t...
[ "Try to put it in the form's __init__:\nclass DeudaForm(forms.ModelForm):\n\n class Meta:\n model = Deuda\n exclude = ('propietario',)\n\n def __init__(self, propietario):\n forms.ModelForm.__init__(self)\n self.fields['adeudado'].queryset = User.objects.exclude(pk=d.propietario.pk...
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0003175443_django_django_forms_python.txt
Q: Using optparse to read in a list from command line options I am calling a python script with the following command line: myscript.py --myopt="[(5.,5.),(-5.,-5.)]" The question is -- how to convert myopt to a list variable. My solution was to use optparse, treating myopt as a string, and using (options, args) = ...
Using optparse to read in a list from command line options
I am calling a python script with the following command line: myscript.py --myopt="[(5.,5.),(-5.,-5.)]" The question is -- how to convert myopt to a list variable. My solution was to use optparse, treating myopt as a string, and using (options, args) = parser.parse_args() myopt = eval(options.myopt) Now, becaus...
[ "ast.literal_eval(node_or_string):\n\nSafely evaluate an expression node or\n a string containing a Python\n expression. The string or node\n provided may only consist of the\n following Python literal structures:\n strings, numbers, tuples, lists,\n dicts, booleans, and None.\nThis can be used for safely eva...
[ 3, 1 ]
[]
[]
[ "eval", "parsing", "python" ]
stackoverflow_0003175606_eval_parsing_python.txt
Q: OOPs paradigm in Python Here is something I've been having a doubt about. Consider the following snippet. class A(object): def check(self): super(A, self).check() print "inside a" class B(object): def check(self): print "inside b" class C(A, B): pass c = C() c.setup() Now th...
OOPs paradigm in Python
Here is something I've been having a doubt about. Consider the following snippet. class A(object): def check(self): super(A, self).check() print "inside a" class B(object): def check(self): print "inside b" class C(A, B): pass c = C() c.setup() Now this gives the output, inside b...
[ "The algorithm is explained in this excellent article.\nIn short, \nsuper(A,self) looks in self.__class__.__mro__ for the next class after A.\nIn your case, self is c, so self.__class__ is C.\nC.__mro__ is [C,A,B,object]. So the next class in the MRO after A happens to be B. \nSo super(A,self) returns a super objec...
[ 9 ]
[]
[]
[ "c++", "java", "oop", "python" ]
stackoverflow_0003175714_c++_java_oop_python.txt
Q: Set minimum column width to header width in PyQt4 QTableWidget I'm working with the QTableWidget component in PyQt4 and I can't seem to get columns to size correctly, according to their respective header lengths. Here's what the table layout should look like (sans pipes, obviously): Index | Long_Header | Longer_He...
Set minimum column width to header width in PyQt4 QTableWidget
I'm working with the QTableWidget component in PyQt4 and I can't seem to get columns to size correctly, according to their respective header lengths. Here's what the table layout should look like (sans pipes, obviously): Index | Long_Header | Longer_Header 1 | 102402 | 100 2 | 123123 | 2 3 | 45468...
[ "table.resizeColumnsToContents()\n\nshould do the trick for this specific example.\nBe sure to bookmark the PyQt documentation if you haven't done so already (handy when you're looking for a specific function).\n" ]
[ 9 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0003175665_pyqt4_python.txt
Q: Are there any implementations of slashdot style moderation in python? Are there any implementations of slashdot style moderation in python? A: On slash ports site (http://www.slashcode.com/slashalikes.shtml) a Python version isn't listed. You may try to use slash perl code as a guide and develop your own version...
Are there any implementations of slashdot style moderation in python?
Are there any implementations of slashdot style moderation in python?
[ "On slash ports site (http://www.slashcode.com/slashalikes.shtml) a Python version isn't listed. You may try to use slash perl code as a guide and develop your own version, though.\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0003176048_python.txt
Q: XPath and lxml syntax I have a XML file with the structure as shown below: <x> <y/> <y/> . . </x> The number of <y> tags are arbitrary. I want to get the text of the <y> tags and for this I decided to use XPath. I have figured out the syntax, say for the first y: (Assume root as x) textFirst = root.x...
XPath and lxml syntax
I have a XML file with the structure as shown below: <x> <y/> <y/> . . </x> The number of <y> tags are arbitrary. I want to get the text of the <y> tags and for this I decided to use XPath. I have figured out the syntax, say for the first y: (Assume root as x) textFirst = root.xpath('y[1]/text()') This wo...
[ "what about 'y[%i]/text()' % x ?\nnow you see where you did a mistake? :)\n( .. note that you can capture all y elements together with xpath 'y' or '//y' )\n", "To count the number of y nodes, you can use the XPath expression 'count(/x/y)'.\nAlso, I think the problem with your expression in the try_it function is...
[ 1, 1 ]
[]
[]
[ "lxml", "python", "xpath" ]
stackoverflow_0003176105_lxml_python_xpath.txt
Q: Compare two audio files Basically, I have a lot of audio files representing the same song. However, some of them are worse quality than the original, and some are edited to where they do not match the original song anymore. What I'd like to do is programmatically compare these audio files to the original and see w...
Compare two audio files
Basically, I have a lot of audio files representing the same song. However, some of them are worse quality than the original, and some are edited to where they do not match the original song anymore. What I'd like to do is programmatically compare these audio files to the original and see which ones match up with that ...
[ "This is actually not a trivial task. I do not think any off-the-shelf library can do it. Here is a possible approach:\n\nDecode mp3 to PCM.\nEnsure that PCM data has specific sample rate, which you choose beforehand (e.g. 16KHz). You'll need to resample songs that have different sample rate. High sample rate is no...
[ 21, 6, 5 ]
[]
[]
[ "audio", "mp3", "python" ]
stackoverflow_0003172911_audio_mp3_python.txt
Q: Help with HTML parsing and sending requests to a web server I'm working on a small project and I've run into a small problem. The script I have needs to fetch a website and find a specific value in the source HTML file. The value is like this: id='elementID'> <fieldset> <input type='hidden' name='hash' val...
Help with HTML parsing and sending requests to a web server
I'm working on a small project and I've run into a small problem. The script I have needs to fetch a website and find a specific value in the source HTML file. The value is like this: id='elementID'> <fieldset> <input type='hidden' name='hash' value='e46c945fe32a3' /> </fieldset> Now I'm been trying to use ...
[ "You might consider looking at the BeautifulSoup library - it's designed to be quick and easy to use.\n" ]
[ 2 ]
[]
[]
[ "httplib", "python", "urllib", "urllib2" ]
stackoverflow_0003176663_httplib_python_urllib_urllib2.txt
Q: Python: Install 2.5.5? Here is the page I found to get 2.5.5: http://www.python.org/download/releases/2.5.5/ (I need it for Google App Engine.) All I see is source files, not an installer. I'm not entirely sure how to build them on my windows machine. What do I do? (Open in Visual Studio, build there?) Or is there...
Python: Install 2.5.5?
Here is the page I found to get 2.5.5: http://www.python.org/download/releases/2.5.5/ (I need it for Google App Engine.) All I see is source files, not an installer. I'm not entirely sure how to build them on my windows machine. What do I do? (Open in Visual Studio, build there?) Or is there an installer I can use?
[ "2.5.5 is unfortunately only available as source, but you can get 2.5.4 installers here. If you're just debugging on your local machine for GAE, the differences between 2.5.4 and 2.5.5 won't matter to you.\nYou can find build instructions for Windows here if you want to build from source. While they're intended f...
[ 2, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003170080_google_app_engine_python.txt
Q: Why doesn't finite repetition in lookbehind work in some flavors? I want to parse the 2 digits in the middle from a date in dd/mm/yy format but also allowing single digits for day and month. This is what I came up with: (?<=^[\d]{1,2}\/)[\d]{1,2} I want a 1 or 2 digit number [\d]{1,2} with a 1 or 2 digit number a...
Why doesn't finite repetition in lookbehind work in some flavors?
I want to parse the 2 digits in the middle from a date in dd/mm/yy format but also allowing single digits for day and month. This is what I came up with: (?<=^[\d]{1,2}\/)[\d]{1,2} I want a 1 or 2 digit number [\d]{1,2} with a 1 or 2 digit number and slash ^[\d]{1,2}\/ before it. This doesn't work on many combinations...
[ "On lookbehind support\nMajor regex flavors have varying supports for lookbehind differently; some imposes certain restrictions, and some doesn't even support it at all.\n\nJavascript: not supported\nPython: fixed length only\nJava: finite length only\n.NET: no restriction\n\nReferences\n\nregular-expressions.info/...
[ 14, 4, 3, 2 ]
[]
[]
[ "c#", "java", "lookbehind", "python", "regex" ]
stackoverflow_0003159524_c#_java_lookbehind_python_regex.txt
Q: How can I improve this code? # max_list = [83, 1350, 1, 100] for i in range(len(max_list)): new_value = 1 while new_value < max_list[i]: new_value *= 10 max_list = new_value What I'm doing is rounding numbers up to the closest, uhm, zero filled value? I'm not sure what it would be called....
How can I improve this code?
# max_list = [83, 1350, 1, 100] for i in range(len(max_list)): new_value = 1 while new_value < max_list[i]: new_value *= 10 max_list = new_value What I'm doing is rounding numbers up to the closest, uhm, zero filled value? I'm not sure what it would be called. But basically, I want 83 -> 100, ...
[ "I'd do it mathematically:\nfrom math import ceil, log10\nint(pow(10, ceil(log10(abs(x or 0.1)))))\n\n", "def nextPowerOfTen(x):\n if x in [0, 1]:\n return x\n elif x < 1:\n return -nextPowerOfTen(abs(x))\n else:\n return 10**len(str(int(x) - 1))\n\n>>> nextPowerOfTen(83)\n100\n>>> nextPowerOfTen(135...
[ 11, 3, 1, 1, 0, 0, 0 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0003176773_python_rounding.txt
Q: Scraping sites that require login with Python I use several ad networks for my sites, and to see how much money I made I need to log in to each daily to add up the values. I was thinking of making a Python script that would do this for me to get a quick total. I know I need to do a POST request to log in, then sto...
Scraping sites that require login with Python
I use several ad networks for my sites, and to see how much money I made I need to log in to each daily to add up the values. I was thinking of making a Python script that would do this for me to get a quick total. I know I need to do a POST request to log in, then store the cookies that I get back and then GET request...
[ "See if this work for you:\nhttp://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/\n", "cookielib does client-side cookie handling, and mechanize enhances it in several ways -- including a way to initialize a cookie jar by reading the cookies from an Internet Explorer cache (so, if you can log ...
[ 6, 1, 1 ]
[]
[]
[ "python", "screen_scraping" ]
stackoverflow_0003121639_python_screen_scraping.txt
Q: best python lib to make the textarea safe in the web page when user submit i want to clean some tag like : <script> and other, so what python lib you are using to do this . thanks A: You can try Web2py , it is a webframework for python with support for Wiki Markup , MarkDown , and many things + Server side Val...
best python lib to make the textarea safe in the web page when user submit
i want to clean some tag like : <script> and other, so what python lib you are using to do this . thanks
[ "You can try Web2py , it is a webframework for python with support for Wiki Markup , MarkDown , and many things + Server side Validation , XSS Prevention. If you want to use only it's Lib you can use gluon of web2py (which is lib of web2py framework)\nwww.web2py.com\n", "BeautifulSoup\nThis function should work f...
[ 0, 0 ]
[]
[]
[ "python", "tags", "textarea" ]
stackoverflow_0003175925_python_tags_textarea.txt
Q: What's wrong with my regular expression? I'm expecting a string NOT to match a regular expression, but it is! >>> re.compile('^P|([LA]E?)$').match('PE').group() 'P' This seems like a bug, because I see no way for the $ to match. On the other hand, it seems unlikely that Python's re lib would not be able to handle...
What's wrong with my regular expression?
I'm expecting a string NOT to match a regular expression, but it is! >>> re.compile('^P|([LA]E?)$').match('PE').group() 'P' This seems like a bug, because I see no way for the $ to match. On the other hand, it seems unlikely that Python's re lib would not be able to handle this simple case. Am I missing something here...
[ "^P|([LA]E?)$\n\nbecomes\n^P\n|\n([LA]E?)$\n\n", "You wrote \"P or ([LA]E?)\". \"P\" matches.\nIf you meant for the anchors to apply to both cases, then perhaps you meant this:\n^(?:P|([LA]E?))$\n", "Two other points worth mentioning: ^ is redundant when you use re.match(), and if you want to match the end of t...
[ 4, 3, 2, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003176717_python_regex.txt
Q: Python checking daytime Basically, I want my script to pause between 4 and 5 AM. The only way to do this I've come up with so far is this: seconds_into_day = time.time() % (60*60*24) if 60*60*4 < seconds_into_day < 60*60*5: sleep(time_left_till_5am) Any "proper" way to do this? Aka some built-in function/lib ...
Python checking daytime
Basically, I want my script to pause between 4 and 5 AM. The only way to do this I've come up with so far is this: seconds_into_day = time.time() % (60*60*24) if 60*60*4 < seconds_into_day < 60*60*5: sleep(time_left_till_5am) Any "proper" way to do this? Aka some built-in function/lib for calculating time; rather ...
[ "You want datetime\n\nThe datetime module supplies classes for manipulating dates and times in both simple and complex ways\n\nIf you use date.hour from datetime.now() you'll get the current hour:\ndatetimenow = datetime.now();\nif datetimenow.hour in range(4, 5)\n sleep(time_left_till_5am)\n\nYou can calculate ...
[ 3, 2, 1, 0 ]
[]
[]
[ "datetime", "python", "time" ]
stackoverflow_0003176360_datetime_python_time.txt
Q: Unstructured Text to Structured Data I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from som...
Unstructured Text to Structured Data
I am looking for references (tutorials, books, academic literature) concerning structuring unstructured text in a manner similar to the google calendar quick add button. I understand this may come under the NLP category, but I am interested only in the process of going from something like "Levi jeans size 32 A0b293" to...
[ "You need to provide more information about the source of the text (the web? user input?), the domain (is it just clothes?), the potential formatting and vocabulary...\nAssuming worst case scenario you need to start learning NLP. A very good free book is the documentation of NLTK: http://www.nltk.org/book . It is a...
[ 7, 1, 1, 0 ]
[]
[]
[ "nlp", "python", "structured_data" ]
stackoverflow_0003162450_nlp_python_structured_data.txt
Q: Advice on preparing/presenting a Python Master Class? I am preparing a master class to present to a group of Technical Artists# at work. Everyone in the group has previously programmed in C/C++/MEL/MAXScript/Python. The purpose of the class is to collectively bring everyone's skill levels and technical understandi...
Advice on preparing/presenting a Python Master Class?
I am preparing a master class to present to a group of Technical Artists# at work. Everyone in the group has previously programmed in C/C++/MEL/MAXScript/Python. The purpose of the class is to collectively bring everyone's skill levels and technical understanding on variety of Computer Science topics to a common level....
[ "Just some quick comments/thoughts from my experience:\n\nI think your time allotment is tight, so I would focus on a handful of key topics to drive home. Certainly spend some time on basic lists, tuple and dictionary usage and manipulation.\nI like to put together a cheat sheet of libraries and select methods/exa...
[ 1 ]
[]
[]
[ "computer_science", "python" ]
stackoverflow_0003173710_computer_science_python.txt
Q: Why does Django use a BaseForm? I think I finally figured out they need to use this DeclarativeFieldsMetaclass (to turn the class fields into instance variables and maintain their order with an ordered/sorted dict). However, I'm still not quite sure why they opted to use a BaseForm rather than implementing everyth...
Why does Django use a BaseForm?
I think I finally figured out they need to use this DeclarativeFieldsMetaclass (to turn the class fields into instance variables and maintain their order with an ordered/sorted dict). However, I'm still not quite sure why they opted to use a BaseForm rather than implementing everything directly within the Form class? T...
[ "I think reason is simpl,e with BaseForm alone you can't define fields using a decalrative syntax i.e.\nclass MyForm(Form):\n field_xxx = form.TextField(...)\n field_nnn _ form.IntegerField(...)\n\nFor such thing to work for should have a metaclass DeclarativeFieldsMetaclass which is set in Form only, they di...
[ 2, 1 ]
[]
[]
[ "design_patterns", "django", "python" ]
stackoverflow_0003176594_design_patterns_django_python.txt
Q: How to convert generator or iterator to list recursively I want to convert generator or iterator to list recursively. I wrote a code in below, but it looks naive and ugly, and may be dropped case in doctest. Q1. Help me good version. Q2. How to specify object is immutable or not? import itertools def isiterable...
How to convert generator or iterator to list recursively
I want to convert generator or iterator to list recursively. I wrote a code in below, but it looks naive and ugly, and may be dropped case in doctest. Q1. Help me good version. Q2. How to specify object is immutable or not? import itertools def isiterable(datum): return hasattr(datum, '__iter__') def issubscrip...
[ "To avoid badly affecting the original object, you basically need a variant of copy.deepcopy... subtly tweaked because you need to turn generators and iterators into lists (deepcopy wouldn't deep-copy generators anyway). Note that some effect on the original object is unfortunately inevitable, because generators a...
[ 5 ]
[]
[]
[ "generator", "immutability", "iterator", "python", "recursion" ]
stackoverflow_0003177442_generator_immutability_iterator_python_recursion.txt
Q: Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict? I have a Django project for managing a list of journal articles. The main model is Article. This has various fields to store things like title of the article, publication date, subject, as well as list of companies mention...
Django Templates - Printing Comma-separated ManyToManyField, sorting results list into dict?
I have a Django project for managing a list of journal articles. The main model is Article. This has various fields to store things like title of the article, publication date, subject, as well as list of companies mentioned in the article. (company is it's own model). I want a template that prints out a list of the ar...
[ "first question \nUse the python like join filter\n{{ article.company.all|join:\", \" }}\n\nhttp://docs.djangoproject.com/en/dev/ref/templates/builtins/#join\nsecond question \n\nMy question is, is it better to use\n the dictsort template-tag to sort this\n inside the template, or should I use\n QuerySet's order...
[ 18, 17 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003177461_django_django_templates_python.txt
Q: python path django How can I add something to my "Pythonpath". Where exactly are the files located, I have to change to add to my pythonpath? What exactly do I add to my Pythonpath? If Python calls: /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/ But I want it to call /Library/Fram...
python path django
How can I add something to my "Pythonpath". Where exactly are the files located, I have to change to add to my pythonpath? What exactly do I add to my Pythonpath? If Python calls: /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/ But I want it to call /Library/Frameworks/Python.framework/...
[ ">>> import sys\n>>> sys.path\n\nsys.path is the list of search path for modules.\nif you want a module to be loaded from /Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages instead of /Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/\nyou just need to make s...
[ 7 ]
[ "This tutorial will probably work for you if you want to remove an old version:\nhttp://docs.djangoproject.com/en/1.2/topics/install/#removing-old-versions-of-django\n" ]
[ -4 ]
[ "django", "path", "python" ]
stackoverflow_0003177715_django_path_python.txt
Q: Help with urllib + proxy in Python My program isn't running properly as should be... I'm getting only the error message (except part) of the urlopen with the proxy... why? At least, one of the proxy was tested and work correctly... please, some one take a look on the code here: http://pastebin.com/cBfv5H8J edit: t...
Help with urllib + proxy in Python
My program isn't running properly as should be... I'm getting only the error message (except part) of the urlopen with the proxy... why? At least, one of the proxy was tested and work correctly... please, some one take a look on the code here: http://pastebin.com/cBfv5H8J edit: the code doesn't work on the first try pa...
[ "At least one error:\nh = urllib.urlopen(website, proxies = {'http': proxylist})\n\nShould be\nh = urllib.urlopen(website, proxies = {'http': proxy})\n\n" ]
[ 0 ]
[]
[]
[ "proxy", "python", "urllib", "windows" ]
stackoverflow_0003178038_proxy_python_urllib_windows.txt
Q: Getting an external list of ip and turning in to variable dic in Python How can I do this: Enter on this website (http://www.samair.ru/proxy/time-01.htm) and get the list of the ip address and turn it to a dictionary variable? whit these code in particular, I only can get the first ip of the website ip = urllib.ur...
Getting an external list of ip and turning in to variable dic in Python
How can I do this: Enter on this website (http://www.samair.ru/proxy/time-01.htm) and get the list of the ip address and turn it to a dictionary variable? whit these code in particular, I only can get the first ip of the website ip = urllib.urlopen('http://www.samair.ru/proxy/time-01.htm').read() clientIp = re.search("...
[ "Use findall instead of search:\nip = urllib.urlopen('http://www.samair.ru/proxy/time-01.htm').read()\nclientIp = re.findall(r\"\\d+\\.\\d+\\.\\d+\\.\\d+\", ip)\n\nNote the “raw” string r\"…\" that prevents interpretation of the backslashes as escape character.\nThis gives you a list of strings containing the IP ad...
[ 1, 1 ]
[]
[]
[ "python", "windows" ]
stackoverflow_0003178101_python_windows.txt
Q: Print output in a single line I have the following code: >>> x = 0 >>> y = 3 >>> while x < y: ... print '{0} / {1}, '.format(x+1, y) ... x += 1 Output: 1 / 3, 2 / 3, 3 / 3, I want my output like: 1 / 3, 2 / 3, 3 / 3 I searched and found that the way to do this in a single line would be: sys.stdout.w...
Print output in a single line
I have the following code: >>> x = 0 >>> y = 3 >>> while x < y: ... print '{0} / {1}, '.format(x+1, y) ... x += 1 Output: 1 / 3, 2 / 3, 3 / 3, I want my output like: 1 / 3, 2 / 3, 3 / 3 I searched and found that the way to do this in a single line would be: sys.stdout.write('{0} / {1}, '.format(x+1, y)) ...
[ "you can use\n\nprint \"something\",\n\n(with a trailing comma, to not insert a newline), so\ntry this\n... print '{0} / {1}, '.format(x+1, y), #<= with a ,\n\n", "I think that sys.stdout.write() would be fine, but the standard way in Python 2 is print with a trailing comma, as mb14 suggested. If you are using Py...
[ 6, 3, 2, 2, 2 ]
[ "Here is a way to achieve what you want using itertools. This will also work ok for Python3 where print becomes a function\nfrom itertools import count, takewhile\ny=3\nprint(\", \".join(\"{0} / {1}\".format(x,y) for x in takewhile(lambda x: x<=y,count(1))))\n\nYou may find the following approach is easier to foll...
[ -1 ]
[ "printing", "python" ]
stackoverflow_0003178026_printing_python.txt
Q: How do I create a data structure that will be serialized this JSON format in python? I have a function that accepts a list of date objects and should output the following dictionary in JSON: { "2010":{ "1":{ "id":1, "title":"foo", "postContent":"bar" }, "7":{ ...
How do I create a data structure that will be serialized this JSON format in python?
I have a function that accepts a list of date objects and should output the following dictionary in JSON: { "2010":{ "1":{ "id":1, "title":"foo", "postContent":"bar" }, "7":{ "id":2, "title":"foo again", "postContent":"bar baz boo" }...
[ "Something along the lines of this should work:\nfrom collections import defaultdict\nimport json\n\nd = defaultdict(dict)\nfor date in dates:\n d[date.year][date.month] = info_for_date(date)\njson.dumps(d)\n\nWhere info_for_date is a function that returns a dict like those in your question.\n" ]
[ 4 ]
[]
[]
[ "dictionary", "django", "json", "list", "python" ]
stackoverflow_0003178028_dictionary_django_json_list_python.txt
Q: Django Python Delete Project App Library If I want to delete a Django App or Project. Is there a way to cleanly delete it? Or a library in Python? How can I delete and re install libraries. So I am SURE that nothing is left of that library. A: If you want to delete some python library go to /site-packages or /d...
Django Python Delete Project App Library
If I want to delete a Django App or Project. Is there a way to cleanly delete it? Or a library in Python? How can I delete and re install libraries. So I am SURE that nothing is left of that library.
[ "If you want to delete some python library go to /site-packages or /dist-packages, find this module(single file) or package(directory) or egg file (look at the extension) and delete this.\nIf you want to delete an app and you have it inside your project, simply delete app directory, remove it from settings and remo...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003178259_django_python.txt
Q: converting wav to mp3 (and vice versa) using GStreamer I am using Python bindings for Gstreamer and am using the following pipeline to convert a wav file to mp3. I used one of the suggestions in this question , with some modifications (as I was getting some errors when original syntax was used) gst.parse_laun...
converting wav to mp3 (and vice versa) using GStreamer
I am using Python bindings for Gstreamer and am using the following pipeline to convert a wav file to mp3. I used one of the suggestions in this question , with some modifications (as I was getting some errors when original syntax was used) gst.parse_launch("filesrc location=C:\\music.wav ! decodebin ! audioconve...
[ "your pipeline is correct - or more specifically, your choice of elements and properties is correct.\nthe problem is most likely in another part of your code. have you set the pipeline to gst.STATE_PLAYING?\npipeline = gst.parse_launch(\"filesrc location=C:\\\\music.wav ! decodebin ! audioconvert ! lame ! filesink...
[ 1, 0 ]
[]
[]
[ "gstreamer", "python" ]
stackoverflow_0002172000_gstreamer_python.txt
Q: How can I alter a file and write only the changes to disk - basically, sed (python)? Let's say I have a file /etc/conf1 it's contents are along the lines of option = banana name = monkey operation = eat and let's say I want to replace "monkey" with "ostrich". How can I do that without reading the file to memory,...
How can I alter a file and write only the changes to disk - basically, sed (python)?
Let's say I have a file /etc/conf1 it's contents are along the lines of option = banana name = monkey operation = eat and let's say I want to replace "monkey" with "ostrich". How can I do that without reading the file to memory, altering it and then just writing it all back? Basically, how can I modify the file "in p...
[ "You can't. \"ostrich\" is one letter more than \"monkey\", so you'll have to rewrite the file at least from that point onwards. File systems do not support \"shifting\" file contents upwards or downwards.\nIf it's just a small file, there's no reason to bother with even this, and you might as well rewrite the whol...
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "file", "file_manipulation", "fopen", "python", "sed" ]
stackoverflow_0003178135_file_file_manipulation_fopen_python_sed.txt
Q: Changing property names in Google application engine Is there any way to alter the Property names in the Google application engine for a Kind, or in other words is there a way to alter the column names of a table in Google application Engine (though it follows a different way to handle the data)? I am using python...
Changing property names in Google application engine
Is there any way to alter the Property names in the Google application engine for a Kind, or in other words is there a way to alter the column names of a table in Google application Engine (though it follows a different way to handle the data)? I am using python. Please suggest. Thanks in advance.
[ "Refactoring on Google AppEngine involves you having to either modify all of the records in your datastore as you make the change, or write the code so that it will still read the old value if the new value doesn't exist.\nRemoving a column from the datastore is possible but not easy. More information can be found ...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003178190_google_app_engine_python.txt
Q: I want to make this program remember settings I have tried unsuccessfully several times to get programs to remember settings after they've been destroyed. A large reason for that is because I don't have an example code to work off of. Below I have a simple program I wrote. I'd like it so that it both remembers the...
I want to make this program remember settings
I have tried unsuccessfully several times to get programs to remember settings after they've been destroyed. A large reason for that is because I don't have an example code to work off of. Below I have a simple program I wrote. I'd like it so that it both remembers the position of the scale, and the contents of the tex...
[ "It's not a matter of asking people to write code for you but knowing what to look for, you could write your own code after that!\nI think remembering settings like you describe is commonly done in two ways:\n\nConfig file\nRegistry entries\n\nYou can then read in the stored value from either the config file/regist...
[ 3, 2, 1 ]
[]
[]
[ "memory", "python", "tkinter" ]
stackoverflow_0003176984_memory_python_tkinter.txt
Q: How do I print some python function output to console (for debugging purposes, while using manage.py runserver) from within a django template I am working on a custom Django form field and accompanying widget. While rendering the template, i would like to inspect the form.field as a python object. How do I do that...
How do I print some python function output to console (for debugging purposes, while using manage.py runserver) from within a django template
I am working on a custom Django form field and accompanying widget. While rendering the template, i would like to inspect the form.field as a python object. How do I do that, because anything in a Django template outside of template tags and filters is rendered as text.
[ "You'll need to write and install a custom tag (or filter... though that might considered be somewhat bizarre, it may help you fit in more places) that, as a side effect, performs the logging calls you desire (or print>>sys.stderr or whatever).\n", "You could put pdb on the form field render surely?\nIf you reall...
[ 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0003177759_django_django_templates_python.txt
Q: Convert XML to python objects using lxml I'm trying to use the lxml library to parse an XML file...what I want is to use XML as the datasource, but still maintain the normal Django-way of interactive with the resulting objects...from the docs, I can see that lxml.objectify is what I'm suppossed to use, but I don't...
Convert XML to python objects using lxml
I'm trying to use the lxml library to parse an XML file...what I want is to use XML as the datasource, but still maintain the normal Django-way of interactive with the resulting objects...from the docs, I can see that lxml.objectify is what I'm suppossed to use, but I don't know how to proceed after: list = objectify.p...
[ "Firstly, \"list\" isn't a very good variable because it \"shadows\" the built-in type \"list.\"\nNow, say you have this xml:\n<root>\n<node1 val=\"foo\">derp</node1>\n<node2 val=\"bar\" />\n</root>\n\nNow, you could do this:\nroot = objectify.parse(\"myfile.xml\")\nprint root.node1.get(\"val\") # prints \"foo\"\np...
[ 1 ]
[]
[]
[ "lxml", "python", "xml_parsing" ]
stackoverflow_0003178863_lxml_python_xml_parsing.txt
Q: SQLAlchemy many-to-many relationship on declarative tables I have the following tables defined declaratively (very simplified version): class Profile(Base): __tablename__ = 'profile' id = Column(Integer, primary_key = True) name = Column(String(65), nullable = False) def __init__(...
SQLAlchemy many-to-many relationship on declarative tables
I have the following tables defined declaratively (very simplified version): class Profile(Base): __tablename__ = 'profile' id = Column(Integer, primary_key = True) name = Column(String(65), nullable = False) def __init__(self, name): self.name = name class Question(Base)...
[ "\nThe documentation says I need to use\n an association object to do this but\n it's confusing me and I can't get it\n to work.\n\nThat's right. And the Answer class is your association object as it maps to the association table 'answer'.\n\nHow do I define the many-to-many\n relationship for the Profile and\n...
[ 13 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0003174979_python_sqlalchemy.txt
Q: Create a structure in a flat xml file I have an xml file made like this: <car>Ferrari</car> <color>red</color> <speed>300</speed> <car>Porsche</car> <color>black</color> <speed>310</speed> I need to have it in this form: <car name="Ferrari"> <color>red</color> <speed>300</speed> </car> <car name="Porsche"...
Create a structure in a flat xml file
I have an xml file made like this: <car>Ferrari</car> <color>red</color> <speed>300</speed> <car>Porsche</car> <color>black</color> <speed>310</speed> I need to have it in this form: <car name="Ferrari"> <color>red</color> <speed>300</speed> </car> <car name="Porsche"> <color>black</color> <speed>310</...
[ "XSLT is the perfect tool for transforming one XML structure into another.\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <!-- copy the root element and handle its <car> children -->\n <xsl:template match=\"/root\">\n <xsl:copy>\n <xsl:apply-templates select=\"car...
[ 8, 1, 0, 0 ]
[]
[]
[ "python", "xml" ]
stackoverflow_0003178584_python_xml.txt
Q: Accessing static properties in Python I am relatively new to Python and was hoping someone could explain the following to me: class MyClass: Property1 = 1 Property2 = 2 print MyClass.Property1 # 1 mc = MyClass() print mc.Property1 # 1 Why can I access Property1 both statically and through a MyClass instance?...
Accessing static properties in Python
I am relatively new to Python and was hoping someone could explain the following to me: class MyClass: Property1 = 1 Property2 = 2 print MyClass.Property1 # 1 mc = MyClass() print mc.Property1 # 1 Why can I access Property1 both statically and through a MyClass instance?
[ "The code \nclass MyClass:\n Property1 = 1\n\ncreates a class MyClass which has a dict:\n>>> MyClass.__dict__\n{'Property1': 1, '__doc__': None, '__module__': '__main__'}\n\nNotice the key-value pair 'Property1': 1. \nWhen you say MyClass.Property1, Python looks in the dict MyClass.__dict__ for the key Property1 a...
[ 30 ]
[]
[]
[ "python" ]
stackoverflow_0003179474_python.txt
Q: How to detect source code in a text? Is it possible to detect a programming language source code (primarily Java and C# ) in a text? For example I want to know whether there is any source code part in this text. .. text text text text text text text text text text text text text text text text text text text text...
How to detect source code in a text?
Is it possible to detect a programming language source code (primarily Java and C# ) in a text? For example I want to know whether there is any source code part in this text. .. text text text text text text text text text text text text text text text text text text text text text text text text text text text publi...
[ "There are some syntax highlighters around (pygments, google-code-prettify) and they've solved code detection and classification. Studying their sources could give an impression how it is done.\n(now that I looked at pygments again - I don't know if they can autodetect the programming language. But google-code-pret...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003179439_python.txt
Q: using Pygsl with GCC 4.0 in Python I am trying to install pygsl using latest version of GCC, i.e.: $ gcc --version i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659) I get the error: $ sudo python setup.py build numpy Building testing ufuncs! running build running build_py running build_ext buildi...
using Pygsl with GCC 4.0 in Python
I am trying to install pygsl using latest version of GCC, i.e.: $ gcc --version i686-apple-darwin10-gcc-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5659) I get the error: $ sudo python setup.py build numpy Building testing ufuncs! running build running build_py running build_ext building 'errno' extension C compiler: gcc-4.0...
[ "Although gcc-4.2 is installed, you see that the build is using gcc-4.0 -- confusing.\nWhere's the \"gcc-4.0\" coming from ? Maybe the setup.py,\nor ~/.pydistutils.cfg, or export CC-gcc-4.0 or ... just guessing, I don't have pygsl.\nCan you get gcc-4.0 out of the way, as described in\nSO setting-gcc-4-2-as-the-defa...
[ 1 ]
[]
[]
[ "gsl", "numpy", "pygsl", "python", "scipy" ]
stackoverflow_0003172513_gsl_numpy_pygsl_python_scipy.txt
Q: Problem unpacking list of lists in a for loop? I have a list of lists that I want to unpack in for loops, but I'm running into an issue. >>> a_list = [(date(2010, 7, 5), ['item 1', 'item 2']), (date(2010, 7, 6), ['item 1'])] >>> >>> for set in a_list: ... a, b = set ... print a, b ... 2010-07-05 ['item 1',...
Problem unpacking list of lists in a for loop?
I have a list of lists that I want to unpack in for loops, but I'm running into an issue. >>> a_list = [(date(2010, 7, 5), ['item 1', 'item 2']), (date(2010, 7, 6), ['item 1'])] >>> >>> for set in a_list: ... a, b = set ... print a, b ... 2010-07-05 ['item 1', 'item 2'] 2010-07-06 ['item 1'] >>> >>> for set in ...
[ "I think you're looking for something like this:\n>>> for a, b in a_list:\n print(a, b)\n\n\n2010-07-05 ['item 1', 'item 2']\n2010-07-06 ['item 1']\n\nAlso, note, set is a bad name for a variable as it shadows built-in.\n", "Mostly because they are completely different:\nIn the first loop, set is (date(2010, 7...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003180132_python.txt
Q: Python: **kargs instead of overloading? I have a conceptual Python design dilemma. Say I have a City class, which represents a city in the database. The City object can be initialized in two ways: An integer (actually, an ID of an existing city in a database) A list of properties (name, country, population, ...)...
Python: **kargs instead of overloading?
I have a conceptual Python design dilemma. Say I have a City class, which represents a city in the database. The City object can be initialized in two ways: An integer (actually, an ID of an existing city in a database) A list of properties (name, country, population, ...), which will generate a new city in the datab...
[ "How about:\nclass City(object):\n def __init__(self, name, description, country, populations):\n self.city_name = name\n # etc.\n\n @classmethod\n def from_id(cls, city_id):\n # initialise from DB \n\nThen you can do normal object creation:\n >>> c = City('Hollowberg', '', 'Densin', 3)\n >>> ...
[ 7, 4, 2 ]
[]
[]
[ "design_patterns", "overloading", "python" ]
stackoverflow_0003179460_design_patterns_overloading_python.txt
Q: Python, ConfigParser: What is 'magical interpolation' The documentation for ConfigParser in Python talks a lot about the so-called "magical interpolation" feature, but never explains what it actually does. I've tried searching for it, but haven't found any answers. A: bad_subj below would be parsed into 'Notify ...
Python, ConfigParser: What is 'magical interpolation'
The documentation for ConfigParser in Python talks a lot about the so-called "magical interpolation" feature, but never explains what it actually does. I've tried searching for it, but haven't found any answers.
[ "bad_subj below would be parsed into 'Notify [failure]'\nbad_subj: %(subj)s [failure]\nsubj: Notify\n\n" ]
[ 6 ]
[]
[]
[ "configparser", "python" ]
stackoverflow_0003180489_configparser_python.txt
Q: Does it make sense to check for identity in __eq__? When implementing a custom equality function for a class, does it make sense to check for identity first? An example: def __eq__(self, other): return (self is other) or (other criteria) This interesting is for cases when the other criteria may be more expens...
Does it make sense to check for identity in __eq__?
When implementing a custom equality function for a class, does it make sense to check for identity first? An example: def __eq__(self, other): return (self is other) or (other criteria) This interesting is for cases when the other criteria may be more expensive (e.g. comparing some long strings).
[ "It may be a perfectly reasonable shortcut to check for identity first, and in equality methods good shortcuts (for both equality and non equality) are what you should be looking for so that you can return as soon as possible.\nBut, on the other hand, it could also be a completely superfluous check if your test for...
[ 7, 3, 2, 1, 0 ]
[]
[]
[ "equality", "python" ]
stackoverflow_0003180004_equality_python.txt
Q: What should I use for the backend of a 'social' website? My two main requirements for the site are related to degrees of separation and graph matching (given two graphs, return some kind of similarity score). My first thought was to use MySql to do it, which would probably work out okay for storing how I want to m...
What should I use for the backend of a 'social' website?
My two main requirements for the site are related to degrees of separation and graph matching (given two graphs, return some kind of similarity score). My first thought was to use MySql to do it, which would probably work out okay for storing how I want to manage 'friends' (similar to Twitter), but I'm thinking if I wa...
[ "Python/Django provides with Pinax a good framework for social websites.\n", "MySQL is really your best choice for the database unless you want to go proprietary.\nAs for the actual language, pick whatever you are familiar with. While Youtube and Reddit are written in python, many of the other large sites use Rub...
[ 3, 2, 0, 0 ]
[]
[]
[ "database", "mysql", "python", "sql" ]
stackoverflow_0003126155_database_mysql_python_sql.txt
Q: Should I use Python or Assembly for a super fast copy program As a maintenance issue I need to routinely (3-5 times per year) copy a repository that is now has over 20 million files and exceeds 1.5 terabytes in total disk space. I am currently using RICHCOPY, but have tried others. RICHCOPY seems the fastest but...
Should I use Python or Assembly for a super fast copy program
As a maintenance issue I need to routinely (3-5 times per year) copy a repository that is now has over 20 million files and exceeds 1.5 terabytes in total disk space. I am currently using RICHCOPY, but have tried others. RICHCOPY seems the fastest but I do not believe I am getting close to the limits of the capabilit...
[ "Copying files is an I/O bound process. It is unlikely that you will see any speed up from rewriting it in assembly, and even multithreading may just cause things to go slower as different threads requesting different files at the same time will result in more disk seeks.\nUsing a standard tool is probably the best...
[ 42, 8, 8, 5, 4, 2, 2, 2, 1, 1, 0, 0, 0 ]
[]
[]
[ "assembly", "python" ]
stackoverflow_0002982829_assembly_python.txt
Q: Microsoft Powerpoint Python Parser I am looking for a python based microsoft office parser - specifically powerpoint. I want to be able to parse PPT in python and extract things like text and images from the powerpoint file. Is there a library available? A: I don't think there is such a library. What you can d...
Microsoft Powerpoint Python Parser
I am looking for a python based microsoft office parser - specifically powerpoint. I want to be able to parse PPT in python and extract things like text and images from the powerpoint file. Is there a library available?
[ "I don't think there is such a library.\nWhat you can do is use pywin32 package to access PowerPoint's COM.\nHere is a very nice introduction to using the win32com module to automate tasks in PowerPoint someone has written:\nhttp://www.s-anand.net/blog/automating-powerpoint-with-python/\n", "You might find such a...
[ 5, 3 ]
[]
[]
[ "parsing", "powerpoint", "python" ]
stackoverflow_0003181286_parsing_powerpoint_python.txt
Q: Parsing arbitrary number of arguments in Python OptParser How can I define an option with an arbitrary number of arguments in Python's OptParser? I'd like something like: python my_program.py --my-option X,Y # one argument passed, "X,Y" python my_prgoram.py --my-option X,Y Z,W # two arguments passed, "X,Y" and...
Parsing arbitrary number of arguments in Python OptParser
How can I define an option with an arbitrary number of arguments in Python's OptParser? I'd like something like: python my_program.py --my-option X,Y # one argument passed, "X,Y" python my_prgoram.py --my-option X,Y Z,W # two arguments passed, "X,Y" and "Z,W" the nargs= option of OptParser limits me to a defined n...
[ "The optarse module is deprecated in python 2.7 (which has just been released!). If you can upgrade, then you can use its replacement the argparse module. I think that has what you want. It supports a '*' value for nargs.\nhttp://docs.python.org/library/argparse.html#nargs\n", "Have you tried ommitting the n_args...
[ 3, 0 ]
[]
[]
[ "command_line", "optparse", "python" ]
stackoverflow_0003181360_command_line_optparse_python.txt
Q: Multiple application entry points Recently I was trying to add unit tests to an existing binary by creating a extra (DLLMain) entry point to an application that already has a main entry point (it is a console exe). The application seemed to compile correctly although I was unable to use it as a DLL from my python ...
Multiple application entry points
Recently I was trying to add unit tests to an existing binary by creating a extra (DLLMain) entry point to an application that already has a main entry point (it is a console exe). The application seemed to compile correctly although I was unable to use it as a DLL from my python unit test framework, all attempts to us...
[ "There are some problems which you should solve to implement what you want:\n\nThe exe must have relocation table (use linker switch /FIXED:NO)\nThe exe must exports at least one function - it's clear how to do this.\n\nI recommend use DUMPBIN.EXE with no some switches (/headers, /exports and without switches) to e...
[ 3, 1 ]
[]
[]
[ "c++", "dll", "python", "unit_testing", "windows" ]
stackoverflow_0003178877_c++_dll_python_unit_testing_windows.txt
Q: HTML Tag Cloud in Python I am looking for a simple library which can be given a set of items:value pair and which can generate a tag cloud as output. Library can preferably be in python A: Define font-sizes in your css-file. Use classes from size-0{ font-size: 11px; } size-1{ font-size: 12px; } etc. up...
HTML Tag Cloud in Python
I am looking for a simple library which can be given a set of items:value pair and which can generate a tag cloud as output. Library can preferably be in python
[ "Define font-sizes in your css-file. Use classes from \nsize-0{\n font-size: 11px;\n}\n\nsize-1{\n font-size: 12px;\n}\n\netc. up to the font-size you need. \nAnd then simply use this snippet:\nCSS_SIZES = range(1, 7) # 1,2...6 for use in your css-file size-1, size-2, etc.\n\nTAGS = {\n 'python' : 28059,\n ...
[ 5 ]
[]
[]
[ "html", "python", "tag_cloud" ]
stackoverflow_0003180779_html_python_tag_cloud.txt
Q: sqlalchemy's create_all doesn't create sequences automatically I am using SQLAlchemy 0.4.8 with Postgres in order to manage my datastore. Until now, it's been fairly easy to automatically deploy my database: I was using metadata.create_all(bind=engine) and everything worked just fine. But now I am trying to create...
sqlalchemy's create_all doesn't create sequences automatically
I am using SQLAlchemy 0.4.8 with Postgres in order to manage my datastore. Until now, it's been fairly easy to automatically deploy my database: I was using metadata.create_all(bind=engine) and everything worked just fine. But now I am trying to create a sequence that it's not being used by any table, so create_all() d...
[ "Could you call the create it by using its own Sequence.create method:\nmy_seq = Sequence('my_seq', metadata=myMetadata)\n# ...\nmetadata.create_all(bind=engine)\n# @note: create unused objects explicitly\nmy_seq.create(bind=engine)\n# ...\n\n" ]
[ 6 ]
[]
[]
[ "postgresql", "python", "sqlalchemy" ]
stackoverflow_0003175028_postgresql_python_sqlalchemy.txt
Q: Python boolean expression and or In python if you write something like foo==bar and spam or eggs python appears to return spam if the boolean statement is true and eggs otherwise. Could someone explain this behaviour? Why is the expression not being evaluated like one long boolean? Edit: Specifically, I'm trying ...
Python boolean expression and or
In python if you write something like foo==bar and spam or eggs python appears to return spam if the boolean statement is true and eggs otherwise. Could someone explain this behaviour? Why is the expression not being evaluated like one long boolean? Edit: Specifically, I'm trying to figure out the mechanism why 'spam'...
[ "The operators and and or are short-circuiting which means that if the result of the expression can be deduced from evaluating only the first operand, the second is not evaluated. For example if you have the expression a or b and a evaluates to true then it doesn't matter what b is, the result of the expression is ...
[ 20, 6, 3, 2 ]
[]
[]
[ "boolean_expression", "python", "syntax" ]
stackoverflow_0003181901_boolean_expression_python_syntax.txt