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: Does Ruby support conditional regular expressions Just a language feature question, I know there's plenty of ways to do this outside of regexes (or with multiple regexes). Does ruby support conditional regular expressions? Basically, an IF-THEN-ELSE branch inside a regular expression, where the predicate for the ...
Does Ruby support conditional regular expressions
Just a language feature question, I know there's plenty of ways to do this outside of regexes (or with multiple regexes). Does ruby support conditional regular expressions? Basically, an IF-THEN-ELSE branch inside a regular expression, where the predicate for the IF is the presence (or absense) of a captured group in ...
[ "No, ruby does not support that (neither in 1.8 nor 1.9).\n" ]
[ 4 ]
[ "FWIW, Python started to support this starting in 2.4:\nhttp://docs.python.org/library/re#regular-expression-syntax\n" ]
[ -1 ]
[ "conditional", "python", "regex", "ruby" ]
stackoverflow_0002208071_conditional_python_regex_ruby.txt
Q: Is there a better way to write this addition function? Can the following method be written any shorter (without semicolons) in Python in a way I have not seen? @staticmethod def __add(a, b): value = a + b if value > 1: integer = int(value) if value == integer: return 1.0 ...
Is there a better way to write this addition function?
Can the following method be written any shorter (without semicolons) in Python in a way I have not seen? @staticmethod def __add(a, b): value = a + b if value > 1: integer = int(value) if value == integer: return 1.0 return value - integer if value < 0: integer = ...
[ "return 1 - (-value%1) if value > 0 else value%1\n\n", "Why not:\nvalue = (a + b) % 1.0\nif (value == 0.0 and a + b > 0) value = 1.0\n\nI'm not sure why the a + b > 0 condition is necessary on the second line, but it matches the behavior in your code of returning 1 if a + b is a positive integer and 0 if a + b is...
[ 1, 0, 0 ]
[]
[]
[ "add", "addition", "python", "sum" ]
stackoverflow_0005054778_add_addition_python_sum.txt
Q: python list comprehension unzipping multiple returns anyone have any idea how to unpack the values in a tuple for a list comprehension? So a practical example: def func(x,y): return x*2, y*2 x = [1, 2, 3]; y = [1, 2, 3] a, b = [ func(i,j) for i, j in zip(x,y) ] Unfortunately, that gives me an error sayin' ...
python list comprehension unzipping multiple returns
anyone have any idea how to unpack the values in a tuple for a list comprehension? So a practical example: def func(x,y): return x*2, y*2 x = [1, 2, 3]; y = [1, 2, 3] a, b = [ func(i,j) for i, j in zip(x,y) ] Unfortunately, that gives me an error sayin' there are too many values to unpack... I've tried zip(*fu...
[ "Do you mean the following?:\na, b = zip(*[func(i,j) for i, j in zip(x,y)])\n\n", "for x1,y1 in [func(i,j) for i, j in zip(x,y)]:\n # do something with x1,y1\n\n", "The problem is that the list comprehension returns something like\n[(1,1), (4,4), (6,6),..]\n\nso the list contains more than just two elements...
[ 8, 1, 1 ]
[]
[]
[ "list", "list_comprehension", "python", "unzip" ]
stackoverflow_0005054836_list_list_comprehension_python_unzip.txt
Q: wxPython, Triggering an Event While Dragging I have a window, and when the window changes position I'd like an event to be triggered. How do I go about this in wxPython? A: You can do this by listening to the EVT_MOVE event. self.Bind(wx.EVT_MOVE, self.OnMove) and def OnMove(self, event): print event.GetP...
wxPython, Triggering an Event While Dragging
I have a window, and when the window changes position I'd like an event to be triggered. How do I go about this in wxPython?
[ "You can do this by listening to the EVT_MOVE event.\nself.Bind(wx.EVT_MOVE, self.OnMove)\n\nand\ndef OnMove(self, event):\n print event.GetPosition()\n\n" ]
[ 1 ]
[]
[]
[ "binding", "events", "python", "wxpython" ]
stackoverflow_0005054925_binding_events_python_wxpython.txt
Q: PYthon: How does this code work? def color(self): name_hash = hash(self.name) red = name_hash & 0xFF # What is this sort of operation? green = (name_hash << 0xFF) & 0xFF # What does 0xFF used for? blue = (name_hash << 0xFFFF) & 0xFF make_light_color = lambda x: x / 3 + 0x...
PYthon: How does this code work?
def color(self): name_hash = hash(self.name) red = name_hash & 0xFF # What is this sort of operation? green = (name_hash << 0xFF) & 0xFF # What does 0xFF used for? blue = (name_hash << 0xFFFF) & 0xFF make_light_color = lambda x: x / 3 + 0xAA # Why plux 0xAA? red = mak...
[ "This code is trying to convert a hash value to a color; parts of the computation are buggy. It takes the lowest 24 bits of name_hash, splits them into 3 bytes, makes those colors lighter, and then outputs that as a string. Going through the sections:\nred = name_hash & 0xFF\n\nGets the least significant 8 bits o...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005054946_python.txt
Q: Script system in application I'm developing a game and now I want to make script system for it. Now I have abstract class Object which is inherited by all game objects. I have to write a lot of technical code, add new object type into enum, register parser function for each object (that function parses object's pa...
Script system in application
I'm developing a game and now I want to make script system for it. Now I have abstract class Object which is inherited by all game objects. I have to write a lot of technical code, add new object type into enum, register parser function for each object (that function parses object's params from file). I don't want to m...
[ "Can you give us a rough idea of how large the game is going to be?\nIf you're not careful, you could give yourself a lot of extra work without much benefit, but with some planning it sounds like it might help. The important questions are \"What parts of the program do I want to simplify?\", \"Do I need a scripting...
[ 0 ]
[]
[]
[ "boost", "c++", "python", "system" ]
stackoverflow_0005050372_boost_c++_python_system.txt
Q: Formatted input in Python I have a file that has the following: A B C D 1 2 3 4 5 2 2 4 3 1 3 4 Note that 4 on line 2 is followed immediately by the new line. I want to make a dictionary that looks like this ['A']['1'] = 2, d['B']['1'] = 3, ..., d['D']['1'] = 5, d['B']['2'] = 2, etc The blanks should not a...
Formatted input in Python
I have a file that has the following: A B C D 1 2 3 4 5 2 2 4 3 1 3 4 Note that 4 on line 2 is followed immediately by the new line. I want to make a dictionary that looks like this ['A']['1'] = 2, d['B']['1'] = 3, ..., d['D']['1'] = 5, d['B']['2'] = 2, etc The blanks should not appear in the dictionary. What's...
[ "The data will all be single digits right? So it lines up with the column headers? In that case, you can do this:\nit = iter(datafile)\ncols = list(next(it)[2::2])\nd = {}\nfor row in it:\n for col, val in zip(cols, row[2::2]):\n if val != ' ':\n d.setdefault(col, {})[row[0]] = int(val)\n\n\n...
[ 3, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005037187_python.txt
Q: Most straightforward alternative to a while loop in python The general point of the program is to search for words and make sure that they occur in the right order. I am currently using the code while not corpus[index_F2-1] == corpus[index_B]: index_F2 = corpus.index(corpus[index_F2], index_F2+1) in order ...
Most straightforward alternative to a while loop in python
The general point of the program is to search for words and make sure that they occur in the right order. I am currently using the code while not corpus[index_F2-1] == corpus[index_B]: index_F2 = corpus.index(corpus[index_F2], index_F2+1) in order to search for a word, check to make sure that a given word appea...
[ "I think I might understand what you're looking for. It sounds like you want to have multiple nested loops, with an exit point within the innermost loop. The most obvious way to achieve this, in my mind, is to enclose the loops within a function. Since all this corpus stuff is confusing, I'll use a simple example: ...
[ 1 ]
[]
[]
[ "loops", "python", "search", "while_loop" ]
stackoverflow_0005055318_loops_python_search_while_loop.txt
Q: with curl, how do I post a form with a file and stream that file? I need to upload a file through a form. The form has other fields along with the file. Right now I have: class FileReader: def __init__(self, fp): self.fp = fp def read_callback(self, size): return self.fp.read(size) c = pyc...
with curl, how do I post a form with a file and stream that file?
I need to upload a file through a form. The form has other fields along with the file. Right now I have: class FileReader: def __init__(self, fp): self.fp = fp def read_callback(self, size): return self.fp.read(size) c = pycurl.Curl() c.setopt(pycurl.URL, url) c.setopt(pycurl.UPLOAD, 1) c.setop...
[ "Here's an example based on the source code of a pycurl test that may help:\nimport pycurl\n\nfields = [('field1', 'this is a test using httppost & stuff'),\n ('field2', (pycurl.FORM_FILE, 'file1.txt', pycurl.FORM_FILE, 'file2.txt')),\n ('field3', (pycurl.FORM_CONTENTS, 'this is wei\\000rd, but null-bytes are...
[ 2 ]
[]
[]
[ "pycurl", "python" ]
stackoverflow_0005055089_pycurl_python.txt
Q: How do I use the version of sqlite3 that comes with the Python installation with web.py? I'm going through the web.py 0.3 tutorials and once I get here I import sqlite3 and set dbn='sqlite3' but it won't work. Has anyone done this before? Edit - I figured it out. I used the code in the link posted by John and ma...
How do I use the version of sqlite3 that comes with the Python installation with web.py?
I'm going through the web.py 0.3 tutorials and once I get here I import sqlite3 and set dbn='sqlite3' but it won't work. Has anyone done this before? Edit - I figured it out. I used the code in the link posted by John and made the following script: import sqlite3 conn = sqlite3.connect('c:\users\user\py\database') c...
[ "Shouldn't it be just dbn='sqlite'?\n", "Google is your friend. Look at this. \n" ]
[ 2, 1 ]
[]
[]
[ "database", "python", "python_2.7", "sqlite", "web.py" ]
stackoverflow_0005055526_database_python_python_2.7_sqlite_web.py.txt
Q: Python 3, multithreading - getting data into main module as each thread finishes The following code executes two threads (multithread), each with different time delays so that each thread will finish at a different time. Once both threads are finished module display1.py issues a print statement saying they are BOT...
Python 3, multithreading - getting data into main module as each thread finishes
The following code executes two threads (multithread), each with different time delays so that each thread will finish at a different time. Once both threads are finished module display1.py issues a print statement saying they are BOTH finished. I would like module display1.py to issue a 'finished' statement for EACH t...
[ "What you have here (entering a very tight check loop in the main thread) is a very naive approach to threading in many languages, but especially in python where GIL contention will just slow the threads down a great bit.\nWhat is a better idea is instead using queue.Queue to push info when a thread is completed. T...
[ 2, 1, 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0005055389_class_python_variables.txt
Q: Django lighttpd FCGI error I am trying to deploy my django app via lighttpd + fcgi, but when I run the fcgi script, it gives me an error Here's the fcgi script itself: #!/usr/bin/python2.6 import sys, os # Add a custom Python path. sys.path.insert(0, "/home/wite") # Switch to the directory of your project. (Opti...
Django lighttpd FCGI error
I am trying to deploy my django app via lighttpd + fcgi, but when I run the fcgi script, it gives me an error Here's the fcgi script itself: #!/usr/bin/python2.6 import sys, os # Add a custom Python path. sys.path.insert(0, "/home/wite") # Switch to the directory of your project. (Optional.) os.chdir("/home/wite/dorm...
[ "There's more to this than meets the eye.\npayne is correct in that this fastcgi listener is using stdin as its socket for communication.\nHowever, this is just one of the ways to run a FastCGI responder. In fact, it's the incorrect way to run a responder for lighttpd, because lighttpd does not support talking to i...
[ 3, 1 ]
[]
[]
[ "django", "fastcgi", "lighttpd", "python" ]
stackoverflow_0004973723_django_fastcgi_lighttpd_python.txt
Q: Manipulate website dropdown menu in Python I've been searching the web for an answer to the following question, and my lack of success might have to do with my inexperience in web programming/html. If so and there's an obvious answer, sorry for bugging you all. I've been trying to parse a bunch of text from a web...
Manipulate website dropdown menu in Python
I've been searching the web for an answer to the following question, and my lack of success might have to do with my inexperience in web programming/html. If so and there's an obvious answer, sorry for bugging you all. I've been trying to parse a bunch of text from a website, and I found the python script html2text.py...
[ "Check out the xml libraries within python. You can take the raw html text and parse it into a Document Object Model (DOM) interface:\nhttp://docs.python.org/library/xml.dom.minidom.html\n", "What you are looking at is not a Drop Down menu, but a Select widget.\nYou should be able to parse this, and find all of t...
[ 1, 1 ]
[]
[]
[ "html", "python" ]
stackoverflow_0005055030_html_python.txt
Q: Is there an equivalent in Python to matlab's imtransform function? The documentation I'm trying to convert some matlab code to Python. I'm not sure what it does, but if I understood it correctly, it transforms an image into another, with the pixels in the images being the parameters. Is there anything equivalent I...
Is there an equivalent in Python to matlab's imtransform function?
The documentation I'm trying to convert some matlab code to Python. I'm not sure what it does, but if I understood it correctly, it transforms an image into another, with the pixels in the images being the parameters. Is there anything equivalent I could use for python in PIL, numpy, whichever library? I assume this mu...
[ "You may check scipy.ndimage. Perhaps not exact equivalent function to imtransformexists. But general transformation functionality do exists.\n", "The Python Image Library has a transform function that takes a matrix. I'm not sure if its exactly equivalent to the Matlab semantics:\n\nim.transform(size, AFFINE, da...
[ 1, 0 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0005055385_matlab_python.txt
Q: Task state not updating when using custom state I have a task like this: @task def test(): time.sleep(10) test.update_state(state="PROGRESS") time.sleep(10) return "done" I then run this: >>> from celery.execute import send_task >>> t = send_task("testcelery.test") >>> t.state 'PENDING' >>> t.stat...
Task state not updating when using custom state
I have a task like this: @task def test(): time.sleep(10) test.update_state(state="PROGRESS") time.sleep(10) return "done" I then run this: >>> from celery.execute import send_task >>> t = send_task("testcelery.test") >>> t.state 'PENDING' >>> t.state 'PROGRESS' I can see in the worker that the task h...
[ "You should upgrade to Celery 2.2.4 (released yesterday) as it fixes the bug that causes this.\nSee http://celeryq.org/docs/changelog.html\n", "It looks to me like CELERY_IGNORE_RESULT set would cause this behavior. What is t.ignore_result? If it is true then either change it or change the default. If you want...
[ 1, 0 ]
[]
[]
[ "celery", "python" ]
stackoverflow_0005054735_celery_python.txt
Q: Boost-python How to pass a c++ class instance to a python class I am new to boost python. I have to first init a cpp class instance in cpp code, and then pass this cpp instance to python code, use a python class instance to invoke it(the cpp instance). I have tried the Python/C API way, but failed, so I wonder how...
Boost-python How to pass a c++ class instance to a python class
I am new to boost python. I have to first init a cpp class instance in cpp code, and then pass this cpp instance to python code, use a python class instance to invoke it(the cpp instance). I have tried the Python/C API way, but failed, so I wonder how to pass a c++ class instance to a python class. The following is my...
[ "Pass the object pointer via boost::python::ptr to python. This will prevent the python interpreter from makeing a copy:\n#include <boost/python.hpp>\n#include <string>\n#include <iostream>\n\nusing namespace boost::python;\nusing namespace std;\n\nclass World\n{\nprivate:\n string name;\npublic:\n void set(s...
[ 17 ]
[]
[]
[ "boost_python", "c++", "python" ]
stackoverflow_0005055443_boost_python_c++_python.txt
Q: Removing a python module from $pythonpath Is there any way to 'uninstall' a module from the python path other than removing the files manually? Pip, easy_install, setuptools etc all have install options, but no remove options! I'm using Ubuntu 9.10 A: pip supports uninstall. pip is able to uninstall most instal...
Removing a python module from $pythonpath
Is there any way to 'uninstall' a module from the python path other than removing the files manually? Pip, easy_install, setuptools etc all have install options, but no remove options! I'm using Ubuntu 9.10
[ "pip supports uninstall.\n\npip is able to uninstall most installed packages with\n\npip uninstall package-name\n\n\nKnown exceptions include pure-distutils packages installed with python setup.py install (such packages leave behind no metadata allowing determination of what files were installed), and script wrappe...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0005056533_python.txt
Q: Python on Windows - subprocess.check_output with full-path works not? With args=['e:\\lynx\\lynx.exe','-dump',some_url], subprocess.check_output works fine if the current-directory is e:\lynx. Elsewhere, it fails with a CalledProcessException and retcode of -1. For now, I do not wish to add e:\lynx to PATH. Any t...
Python on Windows - subprocess.check_output with full-path works not?
With args=['e:\\lynx\\lynx.exe','-dump',some_url], subprocess.check_output works fine if the current-directory is e:\lynx. Elsewhere, it fails with a CalledProcessException and retcode of -1. For now, I do not wish to add e:\lynx to PATH. Any thoughts?
[ "Is there a problem in making the current directory e:\\\\lynx from withing python? That seems like a good solution to me.\n" ]
[ 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004075627_python_python_3.x.txt
Q: how to set the python framework path before building cxfreeze for python3 I m building a python script using a setup.py file. In building process, it links to python framework. I want to change the linking framework path as its linking to the wrong location. How to set the framework path before building the script...
how to set the python framework path before building cxfreeze for python3
I m building a python script using a setup.py file. In building process, it links to python framework. I want to change the linking framework path as its linking to the wrong location. How to set the framework path before building the script. Thanks in advance for sparring ur valuable time for this thread.
[ "Make sure your cxFreexe is installed with and run with the same python as you run the application you want to freeze. That way your PYTHONPATH should be set up correctly.\nThe exception is if the script you want to freeze itself modifies Python path. In that case you need to make the same modifications yourself be...
[ 0 ]
[]
[]
[ "build_process", "python", "python_3.x" ]
stackoverflow_0003179754_build_process_python_python_3.x.txt
Q: is there anyway of monitoring the transfer rate of a urllib2 transfer? Possible Duplicate: Python urllib2 Progress Hook I have a script which uploads a file with urllib2. I have the timeout set but i believe it wont go off if my transfer stalls. I'm wondering if there's anyway of monitoring the urllib2 transfer ...
is there anyway of monitoring the transfer rate of a urllib2 transfer?
Possible Duplicate: Python urllib2 Progress Hook I have a script which uploads a file with urllib2. I have the timeout set but i believe it wont go off if my transfer stalls. I'm wondering if there's anyway of monitoring the urllib2 transfer and make it abort if the transfer rate is below xx bytes/second. Right now...
[ "The transfer speed is not from your urllib2, it is the property of underlying network. You could use any of the standard operating system network monitoring tools (like ntop) and wrap it over subprocess to check for your network speed before you transfer it via urllib2. You can do it via multiple threads too, but ...
[ 0, 0 ]
[]
[]
[ "file_transfer", "python", "urllib2" ]
stackoverflow_0005054981_file_transfer_python_urllib2.txt
Q: Python module for implementing binary file formats? I frequently find myself needing to write code to interact with binary file formats for which there aren't existing tools. I'm looking for an easy way to implement readers/writers for structured binary formats -- ideally something that will let me create the rea...
Python module for implementing binary file formats?
I frequently find myself needing to write code to interact with binary file formats for which there aren't existing tools. I'm looking for an easy way to implement readers/writers for structured binary formats -- ideally something that will let me create the reader using some sort of simple declarative format. I've fo...
[ "Personally I'd use the bitstring module, but I may be biased as I wrote it. There's some simple code for reading/writing a binary format in the manual as an example.\nThis is one way to create via a binary format:\nfmt = 'sequence_header_code,\n uint:12=horizontal_size_value,\n uint:12=vertical_size_va...
[ 6, 4 ]
[]
[]
[ "binary", "python", "resources", "templates" ]
stackoverflow_0005055119_binary_python_resources_templates.txt
Q: LIst Comprehensions: References to the Components In sum: I need to write a List Comprehension in which i refer to list that is being created by the List Comprehension. This might not be something you need to do every day, but i don't think it's unusual either. Maybe there's no answer here--still, please don't tel...
LIst Comprehensions: References to the Components
In sum: I need to write a List Comprehension in which i refer to list that is being created by the List Comprehension. This might not be something you need to do every day, but i don't think it's unusual either. Maybe there's no answer here--still, please don't tell me i ought to use a for loop. That might be correct, ...
[ "I don't see why you need to do this in one go. Either iterate through the initial data first to eliminate duplicates - or, even better, convert it to a set as KennyTM suggests - then do your list comprehension.\nNote that even if you could reference the \"list under construction\", your approach would still fail b...
[ 3, 3, 2, 0 ]
[]
[]
[ "internals", "interpreter", "list_comprehension", "python" ]
stackoverflow_0005056297_internals_interpreter_list_comprehension_python.txt
Q: Decorating a DBUS method I'm trying to combine DBUS' asynchronous method calls with Twisted's Deferreds, but I'm encountering trouble in tweaking the usual DBUS service method decorator to do this. To use the DBUS async callbacks approach, you'd do: class Service(dbus.service.Object): @dbus.service.method(INT...
Decorating a DBUS method
I'm trying to combine DBUS' asynchronous method calls with Twisted's Deferreds, but I'm encountering trouble in tweaking the usual DBUS service method decorator to do this. To use the DBUS async callbacks approach, you'd do: class Service(dbus.service.Object): @dbus.service.method(INTERFACE, async_callbacks=('call...
[ "Why is it dumb? You're already assuming you know that the first positional argument (after self) is a Deferred. Why is it more dumb to assume that you know that the real first position argument is self?\nIf you also want to support free functions, then write another decorator and use that when you know there is ...
[ 0 ]
[]
[]
[ "dbus", "python", "twisted" ]
stackoverflow_0005056377_dbus_python_twisted.txt
Q: wxPython equivalent to Tkinter's protocol attribute? The protocol attribute in Tkinter allows one to run functions when the exit button of a window has been clicked (the button with the x on it, it's top right in Windows). I'd like to run a function when the user try's to exit my application. Is there a wxPython e...
wxPython equivalent to Tkinter's protocol attribute?
The protocol attribute in Tkinter allows one to run functions when the exit button of a window has been clicked (the button with the x on it, it's top right in Windows). I'd like to run a function when the user try's to exit my application. Is there a wxPython equivalent? snippet: self.protocol("WM_DELETE_WINDOW", sel...
[ "When you click on the close button you are producing an EVT_CLOSE event so if you bind this event to an onClose method then you can execute whatever you want before actually closing the application. A simple example:\nclass ChildFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n ...
[ 3 ]
[]
[]
[ "protocols", "python", "tkinter", "windows", "wxpython" ]
stackoverflow_0005056152_protocols_python_tkinter_windows_wxpython.txt
Q: How can I pass images in a server's response using JSON? Base64? In my android app, I show some users in a ListView. I want to display (user's pic, first_name, last_name). Right now, it works only with first_name and last_name. I want to add the picture. The data JSON I receive from my server (python) is like this...
How can I pass images in a server's response using JSON? Base64?
In my android app, I show some users in a ListView. I want to display (user's pic, first_name, last_name). Right now, it works only with first_name and last_name. I want to add the picture. The data JSON I receive from my server (python) is like this: [{"profil":"first_name": "Jim", "last_name": "Carrey"}}, "_id": {"$o...
[ "Technically it's perfectly ok to encode binary data as base64 string and include it in JSON.\nBut, as @servermanfail noted, you might be better off with embedding links to images into JSON and downloading them in the second step. \nThe added benefit would be size/speed of transfer, as base64 stream is 4/3 the size...
[ 12, 8 ]
[]
[]
[ "android", "base64", "image", "listview", "python" ]
stackoverflow_0005057828_android_base64_image_listview_python.txt
Q: Python 2.5 version of this method I have the below function running fine on python 2.6, but appengine's production environment is 2.5 and it blows up on: AttributeError: 'module' object has no attribute 'Mapping' Does anyone have a solution for 2.5? Thanks Chris import types, collections class AttrDict(dict): ...
Python 2.5 version of this method
I have the below function running fine on python 2.6, but appengine's production environment is 2.5 and it blows up on: AttributeError: 'module' object has no attribute 'Mapping' Does anyone have a solution for 2.5? Thanks Chris import types, collections class AttrDict(dict): '''AttrDict - dict with JS-like key=a...
[ "Try to replace\nisinstance(val, collections.Mapping)\n\nwith\nisinstance(val, dict)\n\n", "The function will never get a parameter that is an instance of Mapping because that class is not in python 2.5. Simply replace that line with return val.\nThis is assuming none of your other code uses Mapping or a subclas...
[ 3, 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005058039_google_app_engine_python.txt
Q: Fast way to convert directed to undirected graph (array of lists) in python? I'm trying to convert a set of arcs to a set of edges for some simple visualization work. my arc data currently looks like: ( ['A','B',2], ['B','A',3], ['A','C',4], ['B','C',2], ) I need to convert it to edges, so the directions ...
Fast way to convert directed to undirected graph (array of lists) in python?
I'm trying to convert a set of arcs to a set of edges for some simple visualization work. my arc data currently looks like: ( ['A','B',2], ['B','A',3], ['A','C',4], ['B','C',2], ) I need to convert it to edges, so the directions are combined, looking like this: ( ['A','B',5], ['A','C',4], ['B','C',2], ) ...
[ "Here's an approach using a dictionary where the keys are the ends of the arc in sorted order:\nimport collections\nd = collections.defaultdict(int)\nfor n1, n2, v in arcdata:\n d[min(n1, n2), max(n1, n2)] += v\nresult = [[k[0], k[1], v] for k, v in d.iteritems()]\n\n" ]
[ 6 ]
[]
[]
[ "data_visualization", "graph", "list", "python" ]
stackoverflow_0005058084_data_visualization_graph_list_python.txt
Q: How to copy and paste by using Keyboard in python? Also, are there any functions I can use keyboard to control in order to create a program more efficiently? Thanks A: Do you mean that you want to copy/paste source code/text in the Python command line? If you're on Windows, it works just like any DOS console. I ...
How to copy and paste by using Keyboard in python?
Also, are there any functions I can use keyboard to control in order to create a program more efficiently? Thanks
[ "Do you mean that you want to copy/paste source code/text in the Python command line?\nIf you're on Windows, it works just like any DOS console. I recommend you open your Python console, click on the left upper icon and select \"Properties\". Then, on the options tab, check the \"Insert mode\" and \"Quick Edit mode...
[ 38 ]
[]
[]
[ "copy_paste", "python" ]
stackoverflow_0005057923_copy_paste_python.txt
Q: How is __slots__ implemented in Python? How is __slots__ implemented in Python? Is this exposed in the C interface? How do I get __slots__ behaviour when defining a Python class in C via PyTypeObject? A: When creating Python classes, they by default have a __dict__ and you can set any attribute on them. The poin...
How is __slots__ implemented in Python?
How is __slots__ implemented in Python? Is this exposed in the C interface? How do I get __slots__ behaviour when defining a Python class in C via PyTypeObject?
[ "When creating Python classes, they by default have a __dict__ and you can set any attribute on them. The point of slots is to not create a __dict__ to save space. \nIn the C interface it's the other way around, an extension class has by default no __dict__, and you would instead explicitly have to add one and add ...
[ 18 ]
[]
[]
[ "descriptor", "python", "python_3.x", "python_c_api", "slots" ]
stackoverflow_0005057845_descriptor_python_python_3.x_python_c_api_slots.txt
Q: CSS file not loading for page with multiple arguments I am working with google app engine for a class, and while working on a project, I came across something strange that I can't figure out. When I load a site with multiple arguments, such as www.something.com/something/1, the css file doesn't affect the page. It...
CSS file not loading for page with multiple arguments
I am working with google app engine for a class, and while working on a project, I came across something strange that I can't figure out. When I load a site with multiple arguments, such as www.something.com/something/1, the css file doesn't affect the page. It does this even if I copy and paste the exact code from ano...
[ "You're not showing any code so it's hard to tell for sure, but my guess is that you are using relative references to your CSS files:\n<link rel=\"stylesheet\" href=\"styles.css\">\n\nthese will break when you're in a different directory. /something/1 will be interpreted by the browser as a different directory, so ...
[ 4 ]
[]
[]
[ "css", "google_app_engine", "html", "python" ]
stackoverflow_0005058377_css_google_app_engine_html_python.txt
Q: round function not working in python how do i round off a function. i have the following code in python def round(x,n): return round(x,n) i get the following error >>> round(3,98.9898, 2) Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> round(3,98.9898, 2) TypeError: round() takes...
round function not working in python
how do i round off a function. i have the following code in python def round(x,n): return round(x,n) i get the following error >>> round(3,98.9898, 2) Traceback (most recent call last): File "<pyshell#25>", line 1, in <module> round(3,98.9898, 2) TypeError: round() takes exactly 2 arguments (3 given) i think th...
[ "Two issues:\n\nround(3,98.9898, 2) is code that you enter. Omit the comma yourself and your problem goes away. Otherwise give us more info about your problem.\ndef round(x, n): return round(x, n)\nEven if you fix your function call, you'll most likely end up with RuntimeError due to maximum recursion. Rename your ...
[ 3, 2, 1, 1 ]
[]
[]
[ "python", "rounding" ]
stackoverflow_0004808694_python_rounding.txt
Q: Making smooth orbits in pygame How can i make a smooth circular orbit at a constant speed using pygame? How would i calculate x, y on a circle? A: Rotating about the 2d point center with the given radius and speed. The parameter t is the time in units of seconds. def circular_orbit(center, radius, speed, t): ...
Making smooth orbits in pygame
How can i make a smooth circular orbit at a constant speed using pygame? How would i calculate x, y on a circle?
[ "Rotating about the 2d point center with the given radius and speed.\nThe parameter t is the time in units of seconds.\ndef circular_orbit(center, radius, speed, t):\n theta = math.fmod(t * speed, math.PI * 2)\n c = math.cos(theta)\n s = math.sin(theta)\n return center[0] + radius * c, center[1] + radiu...
[ 4, 1 ]
[]
[]
[ "math", "pygame", "python" ]
stackoverflow_0005058591_math_pygame_python.txt
Q: AJAX post failing XMLHttpRequest check in Django view I have a simple html page which renders with a number of nearly identical forms for the user to submit. Upon submit, the view is intended to add a row to the database, recreate the list of forms with slightly updated data, and send it back to the browser ('/ro...
AJAX post failing XMLHttpRequest check in Django view
I have a simple html page which renders with a number of nearly identical forms for the user to submit. Upon submit, the view is intended to add a row to the database, recreate the list of forms with slightly updated data, and send it back to the browser ('/route/complete/' maps to add_completed_route_view in urls.py)...
[ "The problem is that once the Ajax is completed, it replaces the original form with a new one - and this one no longer has the javascript event handler attached, so the next time the form submits via the normal POST method.\nLuckily, jQuery has a couple of methods that handle this for you - live and delegate. So in...
[ 3 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0005058778_ajax_django_javascript_python.txt
Q: Why does the query display each letter of the first match? In Owner I have properties "owner" and "owner_tag". I query by owner and then try to print owner_tag for matching results. But what I get is each letter of the first match of owner_tag: So, in Owner owner: az@example.com has owner_tag: tag1, tag2, tag3. Th...
Why does the query display each letter of the first match?
In Owner I have properties "owner" and "owner_tag". I query by owner and then try to print owner_tag for matching results. But what I get is each letter of the first match of owner_tag: So, in Owner owner: az@example.com has owner_tag: tag1, tag2, tag3. The query matches "tag1" and loops through "t", "a", "g", "1". I d...
[ "get() always returns a single result or None, and when you iterate over a single string, each value's a character. fetch() works the way you think, with an optional offset argument so you can page through the results if you want to.\nfetch() makes sense if there are potentially tons of results that you might not ...
[ 5 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005058485_google_app_engine_python.txt
Q: Threads in Python again guys! My application is a bot. It simply receives a message, process it and returns result. But there are a lot of messages and I'm creating separate thread for processing each, but it makes an application slower (not a bit). So, Is it any way to reduce CPU usage by replacing threads with s...
Threads in Python again
guys! My application is a bot. It simply receives a message, process it and returns result. But there are a lot of messages and I'm creating separate thread for processing each, but it makes an application slower (not a bit). So, Is it any way to reduce CPU usage by replacing threads with something else?
[ "You probably want processes rather than threads. Spawn processes at startup, and use Pipes to talk to them.\nhttp://docs.python.org/dev/library/multiprocessing.html\n", "Threads and processes have the same speed.\nYour problem is not which one you use, but how many you use.\nThe answer is to only have a fixed co...
[ 3, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005058768_python.txt
Q: Use a color to create an alpha channel for a PNG? I have several images that claim to have a transparent background but are actually white. I'd like to use Python Image Library/PIL to set that white background color to actually be transparent. Since PNG uses an alpha channel, I'd love to create the alpha channel b...
Use a color to create an alpha channel for a PNG?
I have several images that claim to have a transparent background but are actually white. I'd like to use Python Image Library/PIL to set that white background color to actually be transparent. Since PNG uses an alpha channel, I'd love to create the alpha channel by finding contiguous areas of white from the edges of t...
[ "I'd guess you'd want to run across the image in a spiral from the outside, setting a pixel to transparent if it is white, and a pixel further towards the edge is also white transparent. Stop once you've done a whole circle without changing any pixels.\nShouldn't be too difficult to write such a loop.\nDo some kind...
[ 2 ]
[]
[]
[ "image", "python", "python_imaging_library", "transparency" ]
stackoverflow_0005059181_image_python_python_imaging_library_transparency.txt
Q: Is the model specific put() called for each entity when db.put() is called with a list of entities? I've got some models on my GAE app, and I've overriden put() on some of them. When I call db.put() with a list of these entites, is there a guarantee that the overriden put() on each entity will be called? What I'm...
Is the model specific put() called for each entity when db.put() is called with a list of entities?
I've got some models on my GAE app, and I've overriden put() on some of them. When I call db.put() with a list of these entites, is there a guarantee that the overriden put() on each entity will be called? What I'm seeing right now is that the entities are just getting saved without it being called. Is there any good ...
[ "No. You need to monkeypatch db.put() too. For a good example of this, check out Nick Johnson's excellent blog post on Pre- and post- put hooks for Datastore models.\nIf you look at the source code for the db module, you'll see that db.put() does not call the entity's put() function.\n", "You could try somethin...
[ 3, 0 ]
[]
[]
[ "bigtable", "google_app_engine", "python" ]
stackoverflow_0005040825_bigtable_google_app_engine_python.txt
Q: Read left and right soundcard channels separately in Python I wish to develop an application in python which is able to read in data from a soundcard (think engineering waveform analysis). I need to be able to read in the left channel and right channel in separately. Using pyAudio, we are able to either select mo...
Read left and right soundcard channels separately in Python
I wish to develop an application in python which is able to read in data from a soundcard (think engineering waveform analysis). I need to be able to read in the left channel and right channel in separately. Using pyAudio, we are able to either select mono or stereo: pa = pyaudio.PyAudio() _stream = pa.open(forma...
[ "I've only ever seen this done where both channels are read together as an interleaved stream, and then split. This is a common approach and easy to do, and I also can't quite imagine a good reason to do it any other way.\n" ]
[ 0 ]
[]
[]
[ "pyaudio", "python" ]
stackoverflow_0005058491_pyaudio_python.txt
Q: Make a python nested list for use in Django's unordered_list I've got a Django model with a self-referencing foreign key, so my model (as a class in its most basic form) looks like: class MyObj(object): def __init__(self, id, ttl, pid): self.id = id self.name = ttl self.parentid = pid ...
Make a python nested list for use in Django's unordered_list
I've got a Django model with a self-referencing foreign key, so my model (as a class in its most basic form) looks like: class MyObj(object): def __init__(self, id, ttl, pid): self.id = id self.name = ttl self.parentid = pid So a sample of my data might look like: nodes = [] nodes.append(My...
[ "Try\nlists = {}\nfor n in nodes:\n b = lists.setdefault(n.id, [])\n lists.setdefault(n.parentid, []).extend([n.name, b])\nprint lists[0]\n\nor, using collections.defaultdict\nlists = collections.defaultdict(list)\nfor n in nodes:\n lists[n.parentid] += [n.name, lists[n.id]]\nprint lists[0]\n\nboth of whic...
[ 1, 0 ]
[]
[]
[ "django", "django_templates", "python" ]
stackoverflow_0005059401_django_django_templates_python.txt
Q: Low Apache/mod_wsgi throughput I have a trivial WSGI app running on pesto, mod_wsgi and Apache: def viewData(request): return Response("aaaaaaaaaa" * 120000) # return 1,2MB of data On my test machine, I get about 100kb/s of throughput, meaning the request takes about 12 seconds to complete. Downloading static...
Low Apache/mod_wsgi throughput
I have a trivial WSGI app running on pesto, mod_wsgi and Apache: def viewData(request): return Response("aaaaaaaaaa" * 120000) # return 1,2MB of data On my test machine, I get about 100kb/s of throughput, meaning the request takes about 12 seconds to complete. Downloading static files from the same Apache instance...
[ "In WSGI the application or the framework should return an iterable. Don't know if that is what Pesto does.\nChange your code to:\ndef viewData(request):\n return Response([\"aaaaaaaaaa\" * 120000])\n\nAnd try again.\n" ]
[ 4 ]
[]
[]
[ "apache", "mod_wsgi", "python" ]
stackoverflow_0005052468_apache_mod_wsgi_python.txt
Q: Bearing between two points Ive been using the geopy package , which does a great job, however some of the results i get are inconsistant or come with a relatively large displacement, i suspect that the problem resides with my bearing calculation: def gb(x,y,center_x,center_y): dx=x-center_x dy=y-center_y if ((dy>=...
Bearing between two points
Ive been using the geopy package , which does a great job, however some of the results i get are inconsistant or come with a relatively large displacement, i suspect that the problem resides with my bearing calculation: def gb(x,y,center_x,center_y): dx=x-center_x dy=y-center_y if ((dy>=0)and((dx>0)or(dx<0))): retu...
[ "\nCan anyone point me to what might i be doing wrong?\n\n\nNot showing an example of your \"inconsistant or come with a relatively large displacement\" results nor your expected results; consequently answerers must rely on guesswork.\nNot saying what units your input (x, y, etc) is measured in, and how you get the...
[ 9, 2 ]
[]
[]
[ "bearing", "coordinates", "geopy", "gps", "python" ]
stackoverflow_0005058617_bearing_coordinates_geopy_gps_python.txt
Q: Python Help finding value of i What is the value of i at the end of the loop body when a is 6? def loopIdentification(): i=0 for a in range(2,8): i=i+a-3 return i A: 5 >>> def loopIdentification(): i=0 for a in range(2,8): i=i+a-3 print a, i return i >>> loopIdent...
Python Help finding value of i
What is the value of i at the end of the loop body when a is 6? def loopIdentification(): i=0 for a in range(2,8): i=i+a-3 return i
[ "5\n>>> def loopIdentification():\n i=0\n for a in range(2,8):\n i=i+a-3\n print a, i\n return i\n\n>>> loopIdentification()\n2 -1\n3 -1\n4 0\n5 2\n6 5\n7 9\n9\n\n" ]
[ 1 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0005060069_python_python_2.6.txt
Q: How do I add related data to a haystack model index? I have added haystack search to my fledgling django app and managed to create an index for a model, using the template feature. For some reason I am having trouble adding related data to this template index. I am trying the following: {{object.name}} {% for tag ...
How do I add related data to a haystack model index?
I have added haystack search to my fledgling django app and managed to create an index for a model, using the template feature. For some reason I am having trouble adding related data to this template index. I am trying the following: {{object.name}} {% for tag in object.tags.all %} {{tag.name}} {% endfor %} The index...
[ "I think the problem is in \"simple\" search backend. It's new and is only good for faking search functionality. Try with whoosh, sorl or xapian.\nI've looked at haystack/backends/simple.py. This backend is ORM-based and it has no in-memory search index. Only search by model fields will work.\n" ]
[ 1 ]
[]
[]
[ "django", "django_haystack", "python" ]
stackoverflow_0005059301_django_django_haystack_python.txt
Q: Pyparsing problem with operators I did a grammar with pyparsing, and I have a problem. The grammar tries to parse a search query (with operator precedence, parenthesis, etc), and I need for spaces to work like the and operator. For example, this works fine: (word and word) or word But this fails: (word word) or w...
Pyparsing problem with operators
I did a grammar with pyparsing, and I have a problem. The grammar tries to parse a search query (with operator precedence, parenthesis, etc), and I need for spaces to work like the and operator. For example, this works fine: (word and word) or word But this fails: (word word) or word And I want the second query to wo...
[ "One way to address your problem is to define AND as an Optional operator. If you do this, you'll have to take extra care that real keywords like 'and' and 'or' aren't misinterpreted as search words. Also, with Optional, you can add a default string, so that even if the \"and\" is missing in the original search qu...
[ 6 ]
[]
[]
[ "pyparsing", "python" ]
stackoverflow_0005059482_pyparsing_python.txt
Q: css first and last doesn't work in selenium rc I have a query: x= sel.is_element_present("css=div#result form[class*='result']:last") gives me false, but this: <td>storeElementPresent</td> <td>css=div#result form[class*='result']:last</td> <td>selFlightsFormCurrent</td> gives me true. Is there any bug with i...
css first and last doesn't work in selenium rc
I have a query: x= sel.is_element_present("css=div#result form[class*='result']:last") gives me false, but this: <td>storeElementPresent</td> <td>css=div#result form[class*='result']:last</td> <td>selFlightsFormCurrent</td> gives me true. Is there any bug with it?
[ "You might want to consider using an XPath selector to get your first and last items. I've found XPath to be a bit more flexible than CSS.\n" ]
[ 0 ]
[]
[]
[ "css", "python", "selenium", "selenium_rc" ]
stackoverflow_0005030590_css_python_selenium_selenium_rc.txt
Q: Order of files downloaded by a multithreaded program is not constant Im using the program from: here to download many urls at once. It works fine, but the order of the urls in the queue that is received is not the same as their order in the urls list, and its also not constant (changes from run to run). What can ...
Order of files downloaded by a multithreaded program is not constant
Im using the program from: here to download many urls at once. It works fine, but the order of the urls in the queue that is received is not the same as their order in the urls list, and its also not constant (changes from run to run). What can I do to either make their order constant or to know which url belongs to w...
[ "Change fetch to read like this:\ndef fetch(url):\n return (url, urllib2.urlopen(url).read())\n\nThe, instead of a queue full of strings, each one containing a result, you get a queue full of tuples, each tuple containing the url, then a result.\nYou aren't going to be able to get back a queue in which things ar...
[ 3, 1 ]
[]
[]
[ "multithreading", "python", "urllib2" ]
stackoverflow_0005060208_multithreading_python_urllib2.txt
Q: Can @staticmethod's be inherited? The question just about says it. I have an abstract class that calls a staticmethod in a helper function, and I want subclasses to simply define the staticmethod and run with it. Maybe I could use something along the lines of getattr? Should I use a @classmethod instead? A: So...
Can @staticmethod's be inherited?
The question just about says it. I have an abstract class that calls a staticmethod in a helper function, and I want subclasses to simply define the staticmethod and run with it. Maybe I could use something along the lines of getattr? Should I use a @classmethod instead?
[ "Something like this:\nclass A(object):\n def func(self):\n self.f()\n\nclass B(A):\n @staticmethod\n def f():\n print \"I'm B\"\n\nTesting:\n>>> a=x.A()\n>>> a.func()\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\n File \"x.py\", line 3, in func\n ...
[ 5, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005060172_python.txt
Q: Can't get ZeroMQ python bindings to receive messages over IPC I'm trying to achieve PUB/SUB over IPC. If I changed the code below so that the subscriber binds to "tcp://*:5000" and the publisher connects to "tcp://localhost:5000" it works, but I can't get it to work over IPC. What am I doing wrong? subscriber.py i...
Can't get ZeroMQ python bindings to receive messages over IPC
I'm trying to achieve PUB/SUB over IPC. If I changed the code below so that the subscriber binds to "tcp://*:5000" and the publisher connects to "tcp://localhost:5000" it works, but I can't get it to work over IPC. What am I doing wrong? subscriber.py import zmq, json def main(): context = zmq.Context() subscr...
[ "most likely cause is that you are running the publisher in a different directory. Try using absolute path for the pipe location: \"ipc:///tmp/test.pipe\". The way you are using it now makes it relative to current working directory.\n" ]
[ 27 ]
[]
[]
[ "ipc", "python", "zeromq" ]
stackoverflow_0005060508_ipc_python_zeromq.txt
Q: Manipulate MP3 programmatically: Muting certain parts? I'm trying to write a batch process that can take an MP3 file and mute certain parts of it, ideally in Python or Java. Take this example: Given a 2 minute MP3, I want to mute the time between 1:20 and 1:30. When saved back to a file, the rest of the MP3 will p...
Manipulate MP3 programmatically: Muting certain parts?
I'm trying to write a batch process that can take an MP3 file and mute certain parts of it, ideally in Python or Java. Take this example: Given a 2 minute MP3, I want to mute the time between 1:20 and 1:30. When saved back to a file, the rest of the MP3 will play normally -- only that portion will be silent. Any advice...
[ "SoX is a multi-platform sound editing tool and I've used it a lot in the past. More info at http://sox.sourceforge.net/\nI don't think you can mute a section of an MP3 file with a single command though. You could split the file into 3 parts, mute the middle part, then stitch them together again.\nHope that helps\n...
[ 2, 1, 0, 0 ]
[]
[]
[ "audio", "java", "mp3", "python" ]
stackoverflow_0001250086_audio_java_mp3_python.txt
Q: How can I focus on a subset of a list in python I run across this problem frequently suppose I have a text file that I have read in as as a list using file.readlines() suppose the file looks something like this stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff st...
How can I focus on a subset of a list in python
I run across this problem frequently suppose I have a text file that I have read in as as a list using file.readlines() suppose the file looks something like this stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff stuff #indeterminate number of line \ The t...
[ "I like stuff like this:\ndef findblock( lines, start, stop ):\n it = iter(lines)\n for line in it:\n if start in line:\n # now we are in the block, so yield till we find the end\n for line in it:\n if stop in line:\n # lets just look for one bloc...
[ 4, 2, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005060575_list_python.txt
Q: wxPython Binding Problem I'm playing with wxPython event bindings in order to make a dragging algorithm. However I've encountered a problem, when the mouse is not directly over my frame the event doesn't trigger. This becomes a problem while dragging seeing as if the mouse escapes the frame (like if the user move...
wxPython Binding Problem
I'm playing with wxPython event bindings in order to make a dragging algorithm. However I've encountered a problem, when the mouse is not directly over my frame the event doesn't trigger. This becomes a problem while dragging seeing as if the mouse escapes the frame (like if the user moved it quickly), the frame negle...
[ "When you start a drag, call CaptureMouse to keep the mouse locked to the window that you're dragging.\n", "Not tested but probably bind, EVT_LEAVE_WINDOW to trigger when mouse is outside window.\n" ]
[ 2, 0 ]
[]
[]
[ "binding", "events", "python", "wxpython" ]
stackoverflow_0004895919_binding_events_python_wxpython.txt
Q: Am I reading this documentation wrong for this Django app? MEDIASYNC = { 'AWS_KEY': AWS_ACCESSKEY, 'AWS_SECRET': AWS_SECRETKEY, 'AWS_BUCKET': "abc_media", 'BACKEND': 'mediasync.backends.s3', 'SERVE_REMOTE': True, 'AWS_BUCKET_CNAME': True, 'DOCTYPE': 'html4', 'USE_SSL': False, ...
Am I reading this documentation wrong for this Django app?
MEDIASYNC = { 'AWS_KEY': AWS_ACCESSKEY, 'AWS_SECRET': AWS_SECRETKEY, 'AWS_BUCKET': "abc_media", 'BACKEND': 'mediasync.backends.s3', 'SERVE_REMOTE': True, 'AWS_BUCKET_CNAME': True, 'DOCTYPE': 'html4', 'USE_SSL': False, 'PROCESSORS': ( 'mediasync.processors.slim.js_minifier',...
[ "I'm the maintain of django-mediasync. What you are doing SHOULD work. It's working in many of the sites that we've deployed. What version of mediasync are you using? A checkout of master from Github or the released 2.0 version?\nIf you are still having problems with this, please fill out a bug report on the Github...
[ 2, 0 ]
[]
[]
[ "django", "javascript", "jquery", "plugins", "python" ]
stackoverflow_0004809825_django_javascript_jquery_plugins_python.txt
Q: Assign to a slice of a Python list from a lambda I know that there are certain "special" methods of various objects that represent operations that would normally be performed with operators (i.e. int.__add__ for +, object.__eq__ for ==, etc.), and that one of them is list.__setitem, which can assign a value to a l...
Assign to a slice of a Python list from a lambda
I know that there are certain "special" methods of various objects that represent operations that would normally be performed with operators (i.e. int.__add__ for +, object.__eq__ for ==, etc.), and that one of them is list.__setitem, which can assign a value to a list element. However, I need a function that can assig...
[ "The line\nsome_list[2:4] = [2, 3]\n\nwill also call list.__setitem__(). Instead of an index, it will pass a slice object though. The line is equivalent to\nsome_list.__setitem__(slice(2, 4), [2, 3])\n\n", "It depends on the version of Python. For 3.2, __setitem__ does the job:\n\nNote Slicing is done exclusive...
[ 8, 0 ]
[]
[]
[ "lambda", "list", "python", "variable_assignment" ]
stackoverflow_0005060830_lambda_list_python_variable_assignment.txt
Q: How to determine the underlying URL of text file download On the page below there is ability to downlaod a txt file. I'm interested in the first file in the txt section. How do I get the URL. I can pull it. How I get the url that does not include java script with python. Today its: volume.20110218.txt. http:/...
How to determine the underlying URL of text file download
On the page below there is ability to downlaod a txt file. I'm interested in the first file in the txt section. How do I get the URL. I can pull it. How I get the url that does not include java script with python. Today its: volume.20110218.txt. http://www.optionsclearing.com/webapps/trade-volume-download
[ "You're question is a bit vague. It sounds like you'd like to do something with the urllib2 and BeautifulSoup modules.\nFetch the HTML from the base URL with urllib2's functions, parse it with BeautifulSoup and use the target (value of the src attribute) of the (first TXT?) anchor tag in the table to open another ...
[ 1, 1 ]
[]
[]
[ "javascript", "python", "url", "web_scraping" ]
stackoverflow_0005060632_javascript_python_url_web_scraping.txt
Q: Consume Python DAO from cocoa/objective c front end My plan is to develop a multi-tier, multi-platform database application. I would like to consume the data from cocoa/objective c apps, .net apps, and web browsers. I don’t really know where to start and have been looking a Python, but can’t find if cocoa/objectiv...
Consume Python DAO from cocoa/objective c front end
My plan is to develop a multi-tier, multi-platform database application. I would like to consume the data from cocoa/objective c apps, .net apps, and web browsers. I don’t really know where to start and have been looking a Python, but can’t find if cocoa/objective c apps can consume python data objects. Can anyone poin...
[ "You can make python and objective-c work together. Since you can use 100% normal C you can use the Python C interface. It's very tedious though. \nThere's also PyObjC. This acts as a bridge between Objective-C and Python. The documentation is pretty good and it will be much simpler than using the Python C int...
[ 0 ]
[]
[]
[ "cocoa", "dao", "data_access_object", "objective_c", "python" ]
stackoverflow_0005058328_cocoa_dao_data_access_object_objective_c_python.txt
Q: How do I write this Django query in regular SQL? results = Content.objects.filter(next_decay_at__lte=datetime.datetime.now()) A: The query that did the ORM of Django is equivalent (Django got the datetime directly from Python) to: SELECT field1, field2, fieldn FROM app_content WHERE next_decay_at <= NOW() NOW()...
How do I write this Django query in regular SQL?
results = Content.objects.filter(next_decay_at__lte=datetime.datetime.now())
[ "The query that did the ORM of Django is equivalent (Django got the datetime directly from Python) to:\nSELECT field1, field2, fieldn FROM app_content WHERE next_decay_at <= NOW()\n\nNOW() is a SQL function that provide the actual datetime.\nYou can get more info at:\nhttp://www.w3schools.com/sql/sql_func_now.asp\n...
[ 2, 1, 0 ]
[]
[]
[ "database", "django", "mysql", "python", "sql" ]
stackoverflow_0005060553_database_django_mysql_python_sql.txt
Q: Django: Uploading photo and word doc on same form not working correctly I have an upload form that will allow a user to upload a photo, a word doc, or both. I need help with the logic so that as long they have a photo OR a document selected for uploading, the form is valid and the upload will work. It always works...
Django: Uploading photo and word doc on same form not working correctly
I have an upload form that will allow a user to upload a photo, a word doc, or both. I need help with the logic so that as long they have a photo OR a document selected for uploading, the form is valid and the upload will work. It always works when I have BOTH a photo and doc, but appears to randomly work when it's jus...
[ "Do you really need to have two different forms? It seems like you may just want one form with two file fields.\nif request.method == 'POST':\n\n form = DocumentAndPhotoForm(request.POST, request.FILES)\n if form.is_valid():\n if form.cleaned_data.get('document'):\n\n post1 = Document(user =...
[ 0 ]
[]
[]
[ "django", "django_forms", "django_models", "python" ]
stackoverflow_0004791116_django_django_forms_django_models_python.txt
Q: How do I change the notification paging (or limit the number of pages) in this django plugin? https://github.com/pinax/django-notification In the "notices" in views.py, it should display a list of notices for the user. And I got it to work. The only problem is...it displays all the notices. It floods the page. ...
How do I change the notification paging (or limit the number of pages) in this django plugin?
https://github.com/pinax/django-notification In the "notices" in views.py, it should display a list of notices for the user. And I got it to work. The only problem is...it displays all the notices. It floods the page. How do I modify this function in views.py to set a limit to what should be displayed? I did setup....
[ "I believe you need to provide a custom notification/notices.html template in order to get the notices view working at all, so I'm assuming you've already created that yourself.\nIf you just want to arbitrarily limit the number of notifications a user gets per page, then in your template you probably want to do som...
[ 0 ]
[]
[]
[ "django", "installation", "notifications", "oop", "python" ]
stackoverflow_0004723021_django_installation_notifications_oop_python.txt
Q: Bundling Multiple Python Modules I have some Python modules, some of them require more than 20 others. My question is, if there a tool is which helps me to bundle some Python modules to one big file. Here a simple example: HelloWorld.py: import MyPrinter MyPrinter.displayMessage("hello") MyPrinter.py: def displa...
Bundling Multiple Python Modules
I have some Python modules, some of them require more than 20 others. My question is, if there a tool is which helps me to bundle some Python modules to one big file. Here a simple example: HelloWorld.py: import MyPrinter MyPrinter.displayMessage("hello") MyPrinter.py: def displayMessage(msg): print msg should b...
[ "Aassuming you are using Python 2.6 or later, you could package the scripts into a zip file, add a __main__.py and run the zip file directly.\nIf you really want to collapse everything down to a single file, I expect you're going to have to write it yourself. The source code transformation engine in lib2to3 may hel...
[ 3, 1, 0 ]
[]
[]
[ "module", "packaging", "python" ]
stackoverflow_0005060522_module_packaging_python.txt
Q: App Engine: prefetch_refprops-like function for resolving lists of keys When dealing with ReferenceProperties I often make use a function called prefetch_reprops to efficiently resolve references. However, I am currently dealing with a model that makes use of a list of db.Key instances. Does anyone have a prefetch...
App Engine: prefetch_refprops-like function for resolving lists of keys
When dealing with ReferenceProperties I often make use a function called prefetch_reprops to efficiently resolve references. However, I am currently dealing with a model that makes use of a list of db.Key instances. Does anyone have a prefetch_refprops-like function for dealing with lists of keys? Here is a better expl...
[ "Just call db.get on the list of keys, exactly as the prefetch_refprops function does.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005052273_google_app_engine_google_cloud_datastore_python.txt
Q: how to express @ sign in URl I was doing self.request.path and got the the path which is the email address, for example, example@hotmail.com, the it cant display it the way it was, it shows like example01_hotmail.com, all cgi.urlencode(), is there a way that the self.request.path could return the integral url? Th...
how to express @ sign in URl
I was doing self.request.path and got the the path which is the email address, for example, example@hotmail.com, the it cant display it the way it was, it shows like example01_hotmail.com, all cgi.urlencode(), is there a way that the self.request.path could return the integral url? Thank you
[ "URLEncode the \"@\" as %40. URL should look like:\nhttp://example.com/blah?email=example%40hotmail.com\n" ]
[ 1 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005061244_google_app_engine_python.txt
Q: Python's equivalent to Ruby's File.read method I'm trying to read the contents of a file in a single method call. I don't want to have to worry about opening the file, reading from the file, and then closing the file (3 method calls). I just want the content. In ruby, there is File.read("/path/to/file"), which ret...
Python's equivalent to Ruby's File.read method
I'm trying to read the contents of a file in a single method call. I don't want to have to worry about opening the file, reading from the file, and then closing the file (3 method calls). I just want the content. In ruby, there is File.read("/path/to/file"), which returns the contents of that file and properly closes i...
[ "You can concatenate two instructions to get the same behaviour :/. But then the file isn't properly closed.\nfile = open(\"/path/to/file\",\"r\").read()\n\nedit:\nBest option as far as I know leaves you needing 2/3 you mention. Just use the with statement so you don't have to worry about closing said file.\nwith o...
[ 4, 3, 2 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0005061330_file_io_python.txt
Q: How to get application root path in GAE I am using Jinja2 templates for my GAE Python application. Actually there are a couple of small applications inside one project. They are, for example, blog and site. So, the first one is for blog and the second one is for site =). I have this folders structure: / /apps ...
How to get application root path in GAE
I am using Jinja2 templates for my GAE Python application. Actually there are a couple of small applications inside one project. They are, for example, blog and site. So, the first one is for blog and the second one is for site =). I have this folders structure: / /apps /blog /site /templates /blog /site ...
[ "The easiest way to get the root path of your app is to put a module in the root of your app, which stores the result of os.path.dirname(__file__), then import that where needed. Alternately, call os.path.dirname(module.__file__) on a module that's in the root of your app.\n", "Why not put an os.path.abspath arou...
[ 15, 1, 1 ]
[]
[]
[ "google_app_engine", "path", "python" ]
stackoverflow_0005050615_google_app_engine_path_python.txt
Q: problem implementing get_filename() method for GtkFileChooser Button in glade and python? As a newbee I am trying to create a basic theme installer using Glade and python. Everything is working fine but i am not able to find anywhere how to use get_filename() method for gtkFileChooserButton. My Glade File Looks Li...
problem implementing get_filename() method for GtkFileChooser Button in glade and python?
As a newbee I am trying to create a basic theme installer using Glade and python. Everything is working fine but i am not able to find anywhere how to use get_filename() method for gtkFileChooserButton. My Glade File Looks Like this. <?xml version="1.0"?> <interface> <requires lib="gtk+" version="2.16"/> <!-- inter...
[ "I believe if you would get your GtkFileChooserButton object from the builder and save a reference to it as a member of workplz class you could query it in the add signal handler. See if script below would work for you:\nclass workplz(object):\n def __init__( self ):\n builder = gtk.Builder()\n bui...
[ 0 ]
[]
[]
[ "glade", "gtkbuilder", "pygtk", "python" ]
stackoverflow_0005058830_glade_gtkbuilder_pygtk_python.txt
Q: Cython bytes to C char* I am trying to write a Cython extension to CPython to wrap the mcrypt library, so that I can use it with Python 3. However, I am running into a problem where I segfault while trying to use one of the mcrypt APIs. The code that is failing is: def _real_encrypt(self, source): src_len = l...
Cython bytes to C char*
I am trying to write a Cython extension to CPython to wrap the mcrypt library, so that I can use it with Python 3. However, I am running into a problem where I segfault while trying to use one of the mcrypt APIs. The code that is failing is: def _real_encrypt(self, source): src_len = len(source) cdef char* cip...
[ "The first one is pointing the char* at the Python string. The second allocates memory, but then re-points the pointer to the Python string and ignores the newly allocated memory. You should be invoking the C library function strcpy from Cython, presumably; but I don't know the details.\n", "A few comments on you...
[ 4, 3, 2 ]
[]
[]
[ "cython", "python", "python_3.x", "python_bindings" ]
stackoverflow_0004436857_cython_python_python_3.x_python_bindings.txt
Q: Transform bits into byte series Given a Python integer which is within the size of 4 bits, how does one transform it – with bitwise arithmetic instead of string processing – into an integer within the size of 4 bytes, for which each bit in the original corresponds to a byte which is the bit repeated 8 times? For e...
Transform bits into byte series
Given a Python integer which is within the size of 4 bits, how does one transform it – with bitwise arithmetic instead of string processing – into an integer within the size of 4 bytes, for which each bit in the original corresponds to a byte which is the bit repeated 8 times? For example: 0b1011 should become 0b111111...
[ "With apologies to ncoghlan:\nexpanded_bits = [\n 0b00000000000000000000000000000000,\n 0b00000000000000000000000011111111,\n 0b00000000000000001111111100000000,\n 0b00000000000000001111111111111111,\n 0b00000000111111110000000000000000,\n 0b00000000111111110000000011111111,\n 0b000000001111111...
[ 4, 1, 0 ]
[]
[]
[ "bit_manipulation", "python" ]
stackoverflow_0005061737_bit_manipulation_python.txt
Q: element that appear more that once in the list in Python Please help (I know that it's a silly question): I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once? A: To exclude items from the list that appear more than once: d = [x for x in d if d...
element that appear more that once in the list in Python
Please help (I know that it's a silly question): I have a list d = [' ABA', ' AAB', ' BAA', ' BAA', ' AAB', ' ABA']. How can I exclude elements that appear more than once?
[ "To exclude items from the list that appear more than once:\nd = [x for x in d if d.count(x) == 1]\n\nFor the example provided above, d will bind to an empty list.\nOthers have posted good solutions to remove duplicates.\n", "Convert to a set then back again:\nlist(set(d))\n\nIf order matters, you can pass the va...
[ 14, 6, 0, 0, 0 ]
[ "If you shouldn't have done that already, make sure to read the python docs on itertools, especially product(), permutations() and combinations().\n" ]
[ -1 ]
[ "element", "list", "python" ]
stackoverflow_0005056064_element_list_python.txt
Q: Dynamic navigation in django I want to build a dynamic navigation menu that will fill in automatically based on the database, and will be on every page. For example, I have a Genre model. In this model there is a field called parent. If this is null, it is a top-level genre. Otherwise it holds the id of other genr...
Dynamic navigation in django
I want to build a dynamic navigation menu that will fill in automatically based on the database, and will be on every page. For example, I have a Genre model. In this model there is a field called parent. If this is null, it is a top-level genre. Otherwise it holds the id of other genre, and is a subgenre of this genre...
[ "You're talking about creating a hierarchy / tree, which is rather annoying to deal with.\nLook into Modified Preorder Tree Traversal, a method for dealing with trees like this.\nThere's a django app for it!\nhttp://django-mptt.github.com/django-mptt/\nI highly recommend using this instead of rolling your own.\nHer...
[ 3 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005061925_django_python.txt
Q: Windows Print Spool Location Variable My mom's printer acts strangely sometimes and screws up, won't print and then can't delete, stop, restart, or anything any documents in the spool. I wrote a python program that stops the print spooler service, empties the spool folder, and then turns print spooler service bac...
Windows Print Spool Location Variable
My mom's printer acts strangely sometimes and screws up, won't print and then can't delete, stop, restart, or anything any documents in the spool. I wrote a python program that stops the print spooler service, empties the spool folder, and then turns print spooler service back on. Currently the location of the print ...
[ "Looks like the spool directory is specific to each printer (and it can be changed). You can get it via GetPrinterData with SPLREG_DEFAULT_SPOOL_DIRECTORY.\n" ]
[ 0 ]
[]
[]
[ "printing", "python", "windows" ]
stackoverflow_0005061416_printing_python_windows.txt
Q: Merging 2d arrays Suppose I have two arrays: arrayOne = [["james", 35], ["michael", 28], ["steven", 23], ["jack", 18], ["robert", 12]] arrayTwo = [["charles", 45], ["james", 36], ["trevor", 24], ["michael", 17], ["steven", 4]] I want to merge them, so that I would have a single 2D array...
Merging 2d arrays
Suppose I have two arrays: arrayOne = [["james", 35], ["michael", 28], ["steven", 23], ["jack", 18], ["robert", 12]] arrayTwo = [["charles", 45], ["james", 36], ["trevor", 24], ["michael", 17], ["steven", 4]] I want to merge them, so that I would have a single 2D array, where the first eleme...
[ ">>> dict1 = dict(arrayOne)\n>>> dict2 = dict(arrayTwo)\n>>> keyset = set(dict1.keys() + dict2.keys())\n>>> [[key, dict1.get(key, 0), dict2.get(key, 0)] for key in keyset]\n[['james', 35, 36], ['robert', 12, 0], ['charles', 0, 45], \n ['michael', 28, 17], ['trevor', 0, 24], ['jack', 18, 0], \n ['steven', 23, 4]]\n\...
[ 4, 4 ]
[]
[]
[ "multidimensional_array", "python" ]
stackoverflow_0005062323_multidimensional_array_python.txt
Q: Iterating over a list of lists in Python I have this problem on my study guide that calls for a function that gets the average of two dimensional lists and prints them as one list. I don't really have experience messing with two dimensional lists therefore have no clue where to even begin attacking this problem. e...
Iterating over a list of lists in Python
I have this problem on my study guide that calls for a function that gets the average of two dimensional lists and prints them as one list. I don't really have experience messing with two dimensional lists therefore have no clue where to even begin attacking this problem. example of what it should do: avrg([[85, 23, 45...
[ "The 1st, 2nd, and 4th numbers are the average of the 1st, 2nd, and 4th lists, but the 3rd is not. I'll assume that's a typo, and you meant '69.666...'.\nYou went wrong in the 'L[i][j] / i' bit. You can think of that statement as computing a value, and then dropping it; you don't assign it to anything. You might wa...
[ 1, 1, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005061729_list_python.txt
Q: Hashtables over large natural language word sets I'm writing a program in python to do a unigram (and eventually bigram etc) analysis of movie reviews. The goal is to create feature vectors to feed into libsvm. I have 50,000 odd unique words in my feature vector (which seems rather large to me, but I ham relativ...
Hashtables over large natural language word sets
I'm writing a program in python to do a unigram (and eventually bigram etc) analysis of movie reviews. The goal is to create feature vectors to feed into libsvm. I have 50,000 odd unique words in my feature vector (which seems rather large to me, but I ham relatively sure I'm right about that). I'm using the python d...
[ "@ThatGuy has made the fix, but hasn't actually told you this: \nThe major cause of your slowdown is the line\nif word in hash.keys():\nwhich laboriously makes a list of all the keys so far, then laboriously searches that list for `word'. The time taken is proportional to the number of keys i.e. the number of uniqu...
[ 5, 0, 0 ]
[]
[]
[ "dictionary", "hashtable", "libsvm", "nlp", "python" ]
stackoverflow_0005061933_dictionary_hashtable_libsvm_nlp_python.txt
Q: Django: Facebook Connect Oauth2 Permissions In my Django project, I have set up pyfacebook & django-facebookconnect to let the user login with their Fb account. However I now need to get the right permissions to get the user's data & save it in my db. How do you add the permissions to pyfacebook & django-facebookc...
Django: Facebook Connect Oauth2 Permissions
In my Django project, I have set up pyfacebook & django-facebookconnect to let the user login with their Fb account. However I now need to get the right permissions to get the user's data & save it in my db. How do you add the permissions to pyfacebook & django-facebookconnect? In facebook.init.py there is this functi...
[ "Ultimately, I switched over to the django socialregistration module & that worked great.\n" ]
[ 0 ]
[]
[]
[ "django", "facebook", "facebook_graph_api", "oauth_2.0", "python" ]
stackoverflow_0005053080_django_facebook_facebook_graph_api_oauth_2.0_python.txt
Q: Error Installing MySqldb 1.2.3 with Python 2.6 Mac osx 10.6 I have installed XAMPP of PHP and Mysql 5.1, I had installed python 2.6 and now trying to install the MySqldb-1.2.3, But it is giving me following error. sudo python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.mac...
Error Installing MySqldb 1.2.3 with Python 2.6 Mac osx 10.6
I have installed XAMPP of PHP and Mysql 5.1, I had installed python 2.6 and now trying to install the MySqldb-1.2.3, But it is giving me following error. sudo python setup.py build running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.6-universal-2.6/MySQLdb running build_ext building '_mysql...
[ "Not sure what os you are running, but for solaris 11 try\npkg install header-math\n" ]
[ 0 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0004781454_mysql_python.txt
Q: Help correct existing regex to substitute a string value I am new to python and I have been trying to check and substitute a specific value for a string. To illustrate, let me paste the bit of code that I used:- var1 = re.sub(r'\$this->getSomething()->getSomethingElse()->(.*?)', r'\1', var1) What I am trying to...
Help correct existing regex to substitute a string value
I am new to python and I have been trying to check and substitute a specific value for a string. To illustrate, let me paste the bit of code that I used:- var1 = re.sub(r'\$this->getSomething()->getSomethingElse()->(.*?)', r'\1', var1) What I am trying to do here is to replace the entire string(var1) with the value ...
[ "Parentheses are metacharacters, used for grouping. You also want to match literal parentheses, which means you need to escape some instances. Try:\nvar1 = re.sub(r'\\$this->getSomething\\(\\)->getSomethingElse\\(\\)->(.*?)', r'\\1', var1)\n\nNote that this particular statement is equivalent to:\nvar1 = re.sub(r'\\...
[ 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005062663_python_regex.txt
Q: NPAPI for Python - Chrome Extension I am trying to develop a chrome extension in which i have coded all my logic in 'python' . Now on browser action i want to pass parameters and execute that .py file and return results to popup which will open on browser action. To call a .py file from JavaScript i know i will...
NPAPI for Python - Chrome Extension
I am trying to develop a chrome extension in which i have coded all my logic in 'python' . Now on browser action i want to pass parameters and execute that .py file and return results to popup which will open on browser action. To call a .py file from JavaScript i know i will need to code a NPAPI plugin. But am con...
[ "Well, Pyjamas Python Javascript Compiler will not be complete -- not all python features are available in javascript, so it's impossible to convert all python to javascript. This may or may not do what you want, but I don't think it happens \"on the fly\", I think you have to write things on the desktop and run i...
[ 5 ]
[]
[]
[ "firebreath", "google_chrome_extension", "npapi", "python" ]
stackoverflow_0005062444_firebreath_google_chrome_extension_npapi_python.txt
Q: comparing two dictionaries with list type values I'm trying to compare two dictionaries. My approach is to turn them into two separate lists of tuples and to then use the set module. Here is an illustration: dict = {'red':[1,2,3],'blue':[2,3,4],'green':[3,4,5]} dict1 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2...
comparing two dictionaries with list type values
I'm trying to compare two dictionaries. My approach is to turn them into two separate lists of tuples and to then use the set module. Here is an illustration: dict = {'red':[1,2,3],'blue':[2,3,4],'green':[3,4,5]} dict1 = {'green':[3,4,5],'yellow':[2,3,4],'red':[5,2,6]} intersection = set(set(dict.items()) & set(dict1...
[ "shared_keyvals = dict( (key, dict1[key])\n for key in (set(dict1) & set(dict2))\n if dict1[key] == dict2[key]\n )\n\nYou can even make this into a function:\ndef shared_keyvals(dict1, dict2):\n return dict( (key, dict1[key])\n for k...
[ 6, 2 ]
[]
[]
[ "compare", "dictionary", "list", "python", "tuples" ]
stackoverflow_0005062166_compare_dictionary_list_python_tuples.txt
Q: move to python? Need to know why would someone move to python, well may be for intrest of learning new thing ( i have that intrest) but what i will get if i learned python, why should i use python i am not starting a debate here on which is better language or anything like that. just need to know the speciality of...
move to python?
Need to know why would someone move to python, well may be for intrest of learning new thing ( i have that intrest) but what i will get if i learned python, why should i use python i am not starting a debate here on which is better language or anything like that. just need to know the speciality of python that makes it...
[ "Just read about it here: http://www.python.org/about/\nIn fact, your is a very subjective question and difficult to answer and it depends upon your application and it is your choice.\n", "Before I tried it, I thought Python was about as deep as the characters from its namesake \"Monty Python's Flying Circus\" ....
[ 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005063165_python.txt
Q: Problem with programmatic login using httplib2 Im using httplib2 library in python to do a programmatic login to a website. Below is my code: import urllib,httplib2 url='http://somesite.com' header_data={'Content-type': 'application/x-www-form-urlencoded', 'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; en-US; ...
Problem with programmatic login using httplib2
Im using httplib2 library in python to do a programmatic login to a website. Below is my code: import urllib,httplib2 url='http://somesite.com' header_data={'Content-type': 'application/x-www-form-urlencoded', 'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) ...
[ "How about this?\nfrom urllib import urlencode\nfrom ulrlib2 import Request, urlopen\n\nurl='http://somesite.com'\nheader_data={'Content-type': 'application/x-www-form-urlencoded',\n 'User-Agent':'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'}\nbody={...
[ 0 ]
[]
[]
[ "httplib2", "python" ]
stackoverflow_0004985789_httplib2_python.txt
Q: What's a good Flask/Python/WSGI analog to the PHP Apache shared memory stores like apc_store/apc_fetch? I've done a couple of years of large-scale game server development in PHP. A load balancer delegates incoming requests to one server in a cluster. In the name of better performance, we began caching all static...
What's a good Flask/Python/WSGI analog to the PHP Apache shared memory stores like apc_store/apc_fetch?
I've done a couple of years of large-scale game server development in PHP. A load balancer delegates incoming requests to one server in a cluster. In the name of better performance, we began caching all static data (essentially the game world's model objects) on each of the instances in that cluster, directly in Apac...
[ "I would think that even in this case you might want to consider having a centralized key/value store system rather than a series of independent ones on each server. Unless your load balancer always redirects the same users to the same servers you could run into a case where a user's requests are routed to differen...
[ 5, 2 ]
[]
[]
[ "apache", "flask", "memcached", "python", "wsgi" ]
stackoverflow_0004964944_apache_flask_memcached_python_wsgi.txt
Q: how to store huge strings in python I have to store huge string of size around 100 million bytes and more.How to handle this in python? A: 1 million bytes is not a huge string in modern terms: 1 thousand million bytes is still manageable. Just use a string and stop trying to pre-optimise your code. A: That siz...
how to store huge strings in python
I have to store huge string of size around 100 million bytes and more.How to handle this in python?
[ "1 million bytes is not a huge string in modern terms: 1 thousand million bytes is still manageable. Just use a string and stop trying to pre-optimise your code.\n", "That size string is not what one easily calls huge! Have you tried to use it? Why you belive that you need mmap?\n" ]
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005063699_python.txt
Q: Interruptible thread join in Python Is there any way to wait for termination of a thread, but still intercept signals? Consider the following C program: #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> void* server_thread(void* dummy) { ...
Interruptible thread join in Python
Is there any way to wait for termination of a thread, but still intercept signals? Consider the following C program: #include <signal.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <pthread.h> #include <stdlib.h> void* server_thread(void* dummy) { sleep(10); printf("Served\n"); ...
[ "Threads in Python are somewhat strange beasts given the global interpreter lock. You may not be able to achieve what you want without resorting to a join timeout and isAlive as eliben suggests.\nThere are two spots in the docs that give the reason for this (and possibly more).\nThe first:\nFrom http://docs.python....
[ 15, 6, 3, 1, 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0000631441_multithreading_python.txt
Q: Upgrading python 3.1 to 3.2 I'm upgrading from 3.1 to 3.2. Other than looking at 3.1's site-packages directory to see what packages I've been using so that I can install them for 3.2, are there other places I should check for things to install or other issues to look at? I'm not asking about changes to the langua...
Upgrading python 3.1 to 3.2
I'm upgrading from 3.1 to 3.2. Other than looking at 3.1's site-packages directory to see what packages I've been using so that I can install them for 3.2, are there other places I should check for things to install or other issues to look at? I'm not asking about changes to the language between 3.1 and 3.2. I just wa...
[ "No, installing the modules you have installed in 3.1 should be all you need to do. Also of course, if you are compiling from scratch, make sure you have all the libraries installed you have when you compiled 3.1, as some of the standard lib otherwise may be unavailable.\n", "You should be able to install 3.2 in ...
[ 1, 0 ]
[]
[]
[ "installation", "python", "python_3.x" ]
stackoverflow_0005061874_installation_python_python_3.x.txt
Q: Django Framework Test Failing I am using django-nonrel. When I run manage.py test over my project which contains only one very simple user defined test I get the following error in the output. Has anyone seen this before? What do I need to do to resolve the issue so that the test_shortcut_view (django.contrib.c...
Django Framework Test Failing
I am using django-nonrel. When I run manage.py test over my project which contains only one very simple user defined test I get the following error in the output. Has anyone seen this before? What do I need to do to resolve the issue so that the test_shortcut_view (django.contrib.contenttypes.tests.ContentTypesTests...
[ "Well the answer is in your trace back:\nself.assertEqual(\"http://example.com/users/john/\", response._headers.get(\"location\")[1])\nAssertionError: 'http://example.com/users/john/' != '/users/john/'\n\nchange the fist line in :\nself.assertEqual(\"/users/john/\", response._headers.get(\"location\")[1])\n\nthat s...
[ 1, 0 ]
[]
[]
[ "django", "django_nonrel", "python", "unit_testing" ]
stackoverflow_0004101511_django_django_nonrel_python_unit_testing.txt
Q: Is there an elegant way to create a dictionary of arrays? I frequently analyse data which has a parent child relationship: data = [ {'data': 'somedata', 'id': 1, 'parentId': 0}, {'data': 'somedata', 'id': 2, 'parentId': 1}, {'data': 'somedata', 'id': 3, 'parentId': 0}, {'data': 'somedata', 'id': 4,...
Is there an elegant way to create a dictionary of arrays?
I frequently analyse data which has a parent child relationship: data = [ {'data': 'somedata', 'id': 1, 'parentId': 0}, {'data': 'somedata', 'id': 2, 'parentId': 1}, {'data': 'somedata', 'id': 3, 'parentId': 0}, {'data': 'somedata', 'id': 4, 'parentId': 3}, {'data': 'somedata', 'id': 5, 'parentId': ...
[ "I don't know, what do you mean by more elegant. If you are writing some parsing script, than it seems that using built in structures is ok. So are you asking about used data structures or your code?\nOne thing I see is that you can use setdefault instead of checking if you have certain key in dictionary:\nfor item...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005064598_python.txt
Q: app engine python gql query not running results_patientalerts = db.GqlQuery("SELECT * FROM PatientAlerts WHERE patientinfo_ID=" + data_key + " AND alert_type!=3") patientinfo_ID is db.IntegerProperty() data_key is key which i got it from URL.... A: Inserting query arguments inline is generally a bad idea. A much...
app engine python gql query not running
results_patientalerts = db.GqlQuery("SELECT * FROM PatientAlerts WHERE patientinfo_ID=" + data_key + " AND alert_type!=3") patientinfo_ID is db.IntegerProperty() data_key is key which i got it from URL....
[ "Inserting query arguments inline is generally a bad idea. A much better way is to let the db library do this for you:\nresults_patientalerts = db.GqlQuery(\"SELECT * FROM PatientAlerts WHERE patientinfo_ID = :1 AND alert_type != :2\", data_key, 3)\nBy querying the database this way you avoid any query escaping, qu...
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005064866_google_app_engine_python.txt
Q: Correct way of implementing database-wide functionality I'm creating a small website with Django, and I need to calculate statistics with data taken from several tables in the database. For example (nothing to do with my actual models), for a given user, let's say I want all birthday parties he has attended, and p...
Correct way of implementing database-wide functionality
I'm creating a small website with Django, and I need to calculate statistics with data taken from several tables in the database. For example (nothing to do with my actual models), for a given user, let's say I want all birthday parties he has attended, and people he spoke with in said parties. For this, I would need a...
[ "I recommend extending Django's Model-Template-View approach with a controller. I usually have a controller.py within my apps which is the only interface to the data sources. So in your above case I'd have something like get_all_parties_and_people_for_user(user).\nThis is especially useful when your \"data taken fr...
[ 1, 0 ]
[]
[]
[ "coding_style", "database", "django", "django_models", "python" ]
stackoverflow_0005063658_coding_style_database_django_django_models_python.txt
Q: packaging common python namespaces I'm looking to package and upload a library I have to PyPI in the next few days, but I'm a little unsure about my approach to the namespace. I have a few otherwise unrelated projects with a similar approach and wanted to give them all the same namespace. For example: Library 1 n...
packaging common python namespaces
I'm looking to package and upload a library I have to PyPI in the next few days, but I'm a little unsure about my approach to the namespace. I have a few otherwise unrelated projects with a similar approach and wanted to give them all the same namespace. For example: Library 1 namespace: abc.seo Library 2 namespace: ...
[ "In each project base directory, create the following structure:\n/setup.py\n/abc/__init__.py\n/abc/seo/\n\n/abc/__init__.py contains :\n__import__('pkg_resources').declare_namespace(__name__)\n\nsetup.py contains :\nsetup(...,\n packages: ['abc', 'abc.seo'],\n namespace_packages = ['abc']\n ...\n)\n\nRefe...
[ 16 ]
[]
[]
[ "namespaces", "packaging", "pypi", "python" ]
stackoverflow_0005064951_namespaces_packaging_pypi_python.txt
Q: Python Fabric error when executing git archive command I'm running Fabric on a windows 7 machine, when I type: fab production setup I get the following error: [localhost] run: git archive --format=tar master > 20110221142115.tar Warning: local() encountered an error (return code 1) while executing 'git archi ve ...
Python Fabric error when executing git archive command
I'm running Fabric on a windows 7 machine, when I type: fab production setup I get the following error: [localhost] run: git archive --format=tar master > 20110221142115.tar Warning: local() encountered an error (return code 1) while executing 'git archi ve --format=tar master > 20110221142115.tar' the fabric file w...
[ "If the same script/command works on Windows XP, then did you check if Windows 7 firewall or any sort-of-protection is not allowing your connection to go through? Try if the following works on interactive prompt:\nfrom fabric.api import local\nlocal('git archive')\n\n" ]
[ 1 ]
[]
[]
[ "fabric", "git", "python" ]
stackoverflow_0005065353_fabric_git_python.txt
Q: Should i switch to Python? I recently have been considering switching to the Python programming language. Currently, Matlab is the language of choice in my department for rapid development and prototyping of code. It’s very good at this, but Mathworks (the company who produces Matlab) have been tinkering with th...
Should i switch to Python?
I recently have been considering switching to the Python programming language. Currently, Matlab is the language of choice in my department for rapid development and prototyping of code. It’s very good at this, but Mathworks (the company who produces Matlab) have been tinkering with the licencing terms, leading to ha...
[ "I have found python+numpy+scipy+matplotlib+IPython+[random sci/numerical packages] to be almost a complete replacement for matlab. There are certainly some packages missing, so if there is a specialized set of tools that are available in matlab but not in python, this might be an issue, but otherwise, I haven't lo...
[ 23, 11, 7, 4, 3, 2 ]
[]
[]
[ "matlab", "numpy", "python", "scipy" ]
stackoverflow_0005063037_matlab_numpy_python_scipy.txt
Q: Python - Listing files in folders - path names with a variable I'm very very new to this. I'm using python and I want to list files in a number of different folders (using windows) In my first go I had loads of path variables. Each path had its own variable. It worked but this seemed like a long winded way of d...
Python - Listing files in folders - path names with a variable
I'm very very new to this. I'm using python and I want to list files in a number of different folders (using windows) In my first go I had loads of path variables. Each path had its own variable. It worked but this seemed like a long winded way of doing it. As the paths are all the same apart from the folder name, ...
[ "Something like this perhaps?\nfolders = [\"folderA\", \"folderB\", \"folderC\", \"folderD\"]\ndef list_sp_files():\n for folder in folders:\n path = '//server/files/%s/data' % (folder)\n for filename in os.listdir(path):\n print path, filename\n\n", "Try changing your path1 to somethi...
[ 4, 1 ]
[]
[]
[ "path", "python" ]
stackoverflow_0005065797_path_python.txt
Q: What are the PYTHONPATH and PYTHON_LIBRARY_PATH? I have installed a package and cannot get it to work. I know that one of the possible reasons of this problem is incorrect (or not existing) values of certain environment variables. In particular, I know that I need to set PYTHONPATH and PYTHON_LIBRARY_PATH. To set...
What are the PYTHONPATH and PYTHON_LIBRARY_PATH?
I have installed a package and cannot get it to work. I know that one of the possible reasons of this problem is incorrect (or not existing) values of certain environment variables. In particular, I know that I need to set PYTHONPATH and PYTHON_LIBRARY_PATH. To set the correct values for these variables I need to know...
[ "\nPYTHONPATH is documented \nPYTHON_LIBRARY_PATH is something I never heard of. That variable is not set in my environment and is not mentioned in the entire documentation. I also searched the entire python source code and that string is also not mentioned there. Where did you see about this variable? Maybe it is ...
[ 3 ]
[]
[]
[ "environment_variables", "import", "path", "python", "pythonpath" ]
stackoverflow_0005066035_environment_variables_import_path_python_pythonpath.txt
Q: Python/Flask Server Side - Java/HttpURLConnection Client - REST Implementation Am currently implementing a REST interface to my web application from a desktop application that compliments the service. We are using Python with Flask for the REST server implementation. We have a situation where the Java client will ...
Python/Flask Server Side - Java/HttpURLConnection Client - REST Implementation
Am currently implementing a REST interface to my web application from a desktop application that compliments the service. We are using Python with Flask for the REST server implementation. We have a situation where the Java client will request a POST and the python server-side will process the post just fine up until i...
[ "Here is the code on the python server side that works, but not sure if it's the 'right' way to do it....\n@app.route(\"/update_project/<project_data>\", methods=['GET','POST'])\ndef updateWPProject(project_data):\n \"\"\"project_data = user+++++pw+++++pj_jsondoc.\n This will update an existing project data o...
[ 2 ]
[]
[]
[ "flask", "httpurlconnection", "java", "post", "python" ]
stackoverflow_0005060294_flask_httpurlconnection_java_post_python.txt
Q: Efficiently creating a database to analyze relationships between information So I am trying to take a large number of xml files (None are that big in particular and I can split them up as I see fit.) In all there is about 70GB worth of data. For the sake of reference the loading script is written in python and use...
Efficiently creating a database to analyze relationships between information
So I am trying to take a large number of xml files (None are that big in particular and I can split them up as I see fit.) In all there is about 70GB worth of data. For the sake of reference the loading script is written in python and uses psycopg2 to interface with a postgres table. Anyway, what I am trying to do is ...
[ "If I understand this \"...I have been iterating over the update methods\" it sounds like you are updating the database rows as you go? If this is so, consider writing some code that passes the XML, accumulates the totals you are tracking, outputs them to a file, and then loads that file with COPY.\nIf you are upd...
[ 3 ]
[]
[]
[ "database_design", "postgresql", "psycopg2", "python" ]
stackoverflow_0005066569_database_design_postgresql_psycopg2_python.txt
Q: configuring development eggs in zc.buildout I am new to zc.buildout and am looking to get started with it. I was looking over the concept of configuring eggs as parts and modules being developed as develop-eggs in the cfg file. I am having trouble figuring out how I should go about configuring an external dependen...
configuring development eggs in zc.buildout
I am new to zc.buildout and am looking to get started with it. I was looking over the concept of configuring eggs as parts and modules being developed as develop-eggs in the cfg file. I am having trouble figuring out how I should go about configuring an external dependency for my module being developed. I figured that ...
[ "I suggest using the mr.developer extension for zc.buildout:\nhttp://pypi.python.org/pypi/mr.developer\nThe auto-checkout option can be used to perform checkout of the packages from a repository that are actually needed for development. The dependencies specs in your setup.py file have basically nothing to do with ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0005066658_python.txt
Q: Python alternative to csvfix sorry for bad English. I am working in sales and processing many prices. Most of the problems i have been solved (scheduling, processing queue, storing, converting from Excel 2003/2007 or Access, encoding etc...). One of the unresolved problem is processing csv files. I need tool with ...
Python alternative to csvfix
sorry for bad English. I am working in sales and processing many prices. Most of the problems i have been solved (scheduling, processing queue, storing, converting from Excel 2003/2007 or Access, encoding etc...). One of the unresolved problem is processing csv files. I need tool with many configuration options. Most o...
[ "Do you want a programmable tool or a finished application? If the latter, take a look at csved. It offers lots of configuration and filtering options and handles non-ASCII data well (there also is a Unicode variant available. And it's cardware (free, but the author asks for a postcard).\n" ]
[ 1 ]
[]
[]
[ "csv", "python", "text", "text_processing" ]
stackoverflow_0005066811_csv_python_text_text_processing.txt
Q: Pylons - how to use an old project in a new environment? I have an old project, it written under Python 2.5/2.6, Windows. We had Python 2.6/Win7/x64 now, and I tried to start it. I got the old project that running nondebug mode in a server, and copied into local folder. When I tried to yesterday start it, I go...
Pylons - how to use an old project in a new environment?
I have an old project, it written under Python 2.5/2.6, Windows. We had Python 2.6/Win7/x64 now, and I tried to start it. I got the old project that running nondebug mode in a server, and copied into local folder. When I tried to yesterday start it, I got this error: 15:44:58,038 DEBUG [pylons.configuration] Loade...
[ "might be obvious but did you run \"python setup.py develop\" on the application package so that the dependencies could be installed?\n" ]
[ 1 ]
[]
[]
[ "project", "pylons", "python", "upgrade" ]
stackoverflow_0005066530_project_pylons_python_upgrade.txt
Q: How to pack arbitrary bit sequence in Python? I want to encode/compress some binary image data as a sequence if bits. (This sequence will, in general, have a length that does not fit neatly in a whole number of standard integer types.) How can I do this without wasting space? (I realize that, unless the sequence...
How to pack arbitrary bit sequence in Python?
I want to encode/compress some binary image data as a sequence if bits. (This sequence will, in general, have a length that does not fit neatly in a whole number of standard integer types.) How can I do this without wasting space? (I realize that, unless the sequence of bits has a "nice" length, there will always hav...
[ "There's nothing very convenient built in but there are third-party modules such as bitstring and bitarray which are designed for this. \nfrom bitstring import BitArray\ns = BitArray('0b11011')\ns += '0b100'\ns += 'uint:5=9'\ns += [0, 1, 1, 0, 1]\n...\ns.tobytes()\n\nTo join together a sequence of 3-bit numbers (i....
[ 6, 3, 2 ]
[]
[]
[ "bit_packing", "memory", "python" ]
stackoverflow_0005066119_bit_packing_memory_python.txt
Q: Getting a Caught NoReverseMatch error in django I have a view called edit_order, and I have another view called client_items. def edit_order(request, order_no) change_item = order.contact.client def client_items(request, client_id = 0): client = None items = None try: client = models.Clien...
Getting a Caught NoReverseMatch error in django
I have a view called edit_order, and I have another view called client_items. def edit_order(request, order_no) change_item = order.contact.client def client_items(request, client_id = 0): client = None items = None try: client = models.Client.objects.get(pk = client_id) items = client....
[ "Well, how are you passing the order_no parameter? And what does your urls.py look like? In your modified template you are not passing an order_no to the {% url %} tag. If your URL regexp requires both parameters (client_id and order_no) then it won't find a matching URL. You could try something like this in urls.p...
[ 1 ]
[]
[]
[ "django", "html", "python", "url", "views" ]
stackoverflow_0005066337_django_html_python_url_views.txt
Q: os.rename() works on open files in Mac. what is the alternative? I needed a mechanism in Python using which I could detect whether a file is open by some other application or not. For Windows, a solution which worked for me was trying to rename the file. Windows doesn't allow you to rename a file if its still open...
os.rename() works on open files in Mac. what is the alternative?
I needed a mechanism in Python using which I could detect whether a file is open by some other application or not. For Windows, a solution which worked for me was trying to rename the file. Windows doesn't allow you to rename a file if its still open by some other application. Unfortunately this didn't work on a Mac. ...
[ "Try os.open with O_EXLOCK flag.\nThis might be not a general solution, but it should work on Unix like systems, including Mac.\n", "There is no general solution to this problem. If you have control over the other applications using the file, you can use some kind of lock files. But if you just want to know if ...
[ 1, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0005067230_macos_python.txt