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: Problem when using MemoryDC Why does my code print the lines gray instead of black? import wx class MyFrame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.panel=wx.Panel(self,-1,size=(1000,1000)) self.Bind(wx.EVT_PAINT, self.on_paint) ...
Problem when using MemoryDC
Why does my code print the lines gray instead of black? import wx class MyFrame(wx.Frame): def __init__(self,*args,**kwargs): wx.Frame.__init__(self,*args,**kwargs) self.panel=wx.Panel(self,-1,size=(1000,1000)) self.Bind(wx.EVT_PAINT, self.on_paint) self.Bind(wx.EVT_SIZE, self.on_si...
[ "Beside the frame/panel paint problem already pointed out the color problem is due to the alpha channel of the 32 bit bitmap.\nI remember having read to use wx.GCDC instead of wx.DC.\n", "Ok I tested with newer version of wx(2.8.9.2) \nand Now I wonder why it is even working on your side.\nyou are trying to paint...
[ 1, 0 ]
[]
[]
[ "graphics", "python", "wxpython" ]
stackoverflow_0000845071_graphics_python_wxpython.txt
Q: Why can't I pass a direct reference to a dictionary value to a function? Earlier today I asked a question about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never answered. So my follow up is why can't...
Why can't I pass a direct reference to a dictionary value to a function?
Earlier today I asked a question about passing dictionary values to a function. While I understand now how to accomplish what I was trying to accomplish the why question (which was not asked) was never answered. So my follow up is why can't I def myFunction(newDict['bubba']): some code to process the parameter ...
[ "Yes, the parser will reject this code.\nParameter lists are used in function definitions to bind identifiers within the function to arguments that are passed in from the outside on invocation.\nSince newDict['bubba'] is not a valid identifier, this doesn't make any sense -- you need to provide it as an invocation ...
[ 6, 2, 2 ]
[]
[]
[ "dictionary", "function", "parameters", "python" ]
stackoverflow_0000855514_dictionary_function_parameters_python.txt
Q: Is this Python producer-consumer lockless approach thread-safe? I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a l...
Is this Python producer-consumer lockless approach thread-safe?
I recently wrote a program that used a simple producer/consumer pattern. It initially had a bug related to improper use of threading.Lock that I eventually fixed. But it made me think whether it's possible to implement producer/consumer pattern in a lockless manner. Requirements in my case were simple: One producer th...
[ "Trickery will bite you. Just use Queue to communicate between threads.\n", "Yes this will work in the way that you described:\n\nThat the producer may produce a skippable element.\nThat the consumer may consume the same element.\n\n\nBut I also know that del x operation isn't atomic when x implements del method...
[ 6, 2, 1, 0, 0, 0 ]
[]
[]
[ "locking", "producer_consumer", "python", "thread_safety" ]
stackoverflow_0000854906_locking_producer_consumer_python_thread_safety.txt
Q: A ListView of checkboxes in PyQt I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this? Thanks ...
A ListView of checkboxes in PyQt
I want to display a QListView where each item is a checkbox with some label. The checkboxes should be visible at all times. One way I can think of is using a custom delegate and QAbstractListModel. Are there simpler ways? Can you provide the simplest snippet that does this? Thanks in advance
[ "I ended up using the method provided by David Boddie in the PyQt mailing list. Here's a working snippet based on his code:\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport sys\nfrom random import randint\n\n\napp = QApplication(sys.argv)\n\nmodel = QStandardItemModel()\n\nfor n in range(10): ...
[ 23, 13 ]
[]
[]
[ "pyqt", "python", "qitemdelegate", "qlistview", "qt" ]
stackoverflow_0000846684_pyqt_python_qitemdelegate_qlistview_qt.txt
Q: launch a process off a mysql row insert I need to launch a server side process off a mysql row insert. I'd appreciate some feedback/suggestions. So far I can think of three options: 1st (least attractive): My preliminary understanding is that I can write a kind of "custom trigger" in C that could fire off a row ...
launch a process off a mysql row insert
I need to launch a server side process off a mysql row insert. I'd appreciate some feedback/suggestions. So far I can think of three options: 1st (least attractive): My preliminary understanding is that I can write a kind of "custom trigger" in C that could fire off a row insert. In addition to having to renew my C s...
[ "Write an insert trigger which duplicates inserted rows to a secondary table. Periodically poll the secondary table for rows with an external application/cronjob; if any rows are in the table, delete them and do your processing (or set a 'processing started' flag and only delete from the secondary table upon succes...
[ 4, 0 ]
[]
[]
[ "linux", "mysql", "perl", "python" ]
stackoverflow_0000856173_linux_mysql_perl_python.txt
Q: Is there a "one-liner" way to get a list of keys from a dictionary in sorted order? The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedic...
Is there a "one-liner" way to get a list of keys from a dictionary in sorted order?
The list sort() method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: for k in somedictionary.keys().sort(): dosomething() Instead, I must: keys = somedictionary.keys() keys.sort() for k in keys: dosomething() Is there a pretty way to ite...
[ "for k in sorted(somedictionary.keys()):\n doSomething(k)\n\nNote that you can also get all of the keys and values sorted by keys like this:\nfor k, v in sorted(somedictionary.iteritems()):\n doSomething(k, v)\n\n", "Can I answer my own question?\nI have just discovered the handy function \"sorted\" which do...
[ 20, 8, 7 ]
[]
[]
[ "iterator", "python", "syntactic_sugar" ]
stackoverflow_0000327191_iterator_python_syntactic_sugar.txt
Q: how are exceptions compared in an except clause In the following code segment: try: raise Bob() except Fred: print "blah" How is the comparison of Bob and Fred implemented? From playing around it seems to be calling isinstance underneath, is this correct? I'm asking because I am attempting to subvert the ...
how are exceptions compared in an except clause
In the following code segment: try: raise Bob() except Fred: print "blah" How is the comparison of Bob and Fred implemented? From playing around it seems to be calling isinstance underneath, is this correct? I'm asking because I am attempting to subvert the process, specifically I want to be able to construct ...
[ "I believe that your guess is correct in how the comparison works, and the only way to intercept that is to add Fred as a base class to Bob. For example:\n# Assume both Bob and Fred are derived from Exception\n>>> class Bob(Bob, Fred):\n... pass\n... \n>>> try:\n... raise Bob()\n... except Fred:\n... pr...
[ 6, 1, 1, 1, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0000851012_exception_python.txt
Q: Subclassing ctypes - Python This is some code I found on the internet. I'm not sure how it is meant to be used. I simply filled members with the enum keys/values and it works, but I'm curious what this metaclass is all about. I am assuming it has something to do with ctypes, but I can't find much information on su...
Subclassing ctypes - Python
This is some code I found on the internet. I'm not sure how it is meant to be used. I simply filled members with the enum keys/values and it works, but I'm curious what this metaclass is all about. I am assuming it has something to do with ctypes, but I can't find much information on subclassing ctypes. I know Enumerat...
[ "A metaclass is a class used to create classes. Think of it this way: all objects have a class, a class is also an object, therefore, it makes sense that a class can have a class.\nhttp://www.ibm.com/developerworks/linux/library/l-pymeta.html\nTo understand what this is doing, you can look at a few points in the co...
[ 4, 3 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0000855941_ctypes_python.txt
Q: Getting local dictionary for function scope only in Python I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python? A bit more about why I want to ...
Getting local dictionary for function scope only in Python
I keep ending up at this situation where I want to use a dictionary very much like the one 'locals' gives back, but that only contains the variables in the limited scope of the function. Is there a way to do this in python? A bit more about why I want to do this: I'm playing with Django and when I go to give my templa...
[ "I'm not sure I agree that making a dictionary is a violation of DRY, but if you really don't want to repeat anything at all, you could just define a 'context' dictionary at the top of the view and use dictionary keys instead of variables throughout the view.\ndef my_view(request):\n context = {}\n context['i...
[ 5, 4, 2, 2 ]
[]
[]
[ "django", "django_views", "locals", "python", "scope" ]
stackoverflow_0000855259_django_django_views_locals_python_scope.txt
Q: Running django on OSX I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache. I'm running OSX 10.5 and ha...
Running django on OSX
I've just completed the very very nice django tutorial and it all went swimmingly. One of the first parts of the tutorial is that it says not to use their example server thingie in production, my first act after the tutorial was thus to try to run my app on apache. I'm running OSX 10.5 and have the standard apache (whi...
[ "You probably won't find much joy using .htaccess to configure Django through Apache (though I confess you probably could do it if you're determined enough... but for production I suspect it will be more complicated than necessary). I develop and run Django in OS X, and it works quite seamlessly.\nThe secret is tha...
[ 5, 5, 3, 2 ]
[]
[]
[ "django", "macos", "python" ]
stackoverflow_0000855408_django_macos_python.txt
Q: How do I upload a files to google app engine app when field name is not known I have tried a few options, none of which seem to work (if I have a simple multipart form with a named field, it works well, but when I don't know the name I can't just grab all files in the request...). I have looked at Upload files in...
How do I upload a files to google app engine app when field name is not known
I have tried a few options, none of which seem to work (if I have a simple multipart form with a named field, it works well, but when I don't know the name I can't just grab all files in the request...). I have looked at Upload files in Google App Engine and it doesn't seem suitable (or to actually work, as someone me...
[ "Check out the documentation on the Webob request object. File uploads are treated the same as other form fields, except they're a file upload object, rather than a string - so you can iterate over the available fields the same as any other POST.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0000855667_google_app_engine_python.txt
Q: Does python have a call_user_func() like PHP? Does python have a function like call_user_func() in PHP? PHP Version: call_user_func(array($object,$methodName),$parameters) How do I achieve the above in Python? A: I don't see the problem, unless methodName is a string. In that case getattr does the job: >>> ...
Does python have a call_user_func() like PHP?
Does python have a function like call_user_func() in PHP? PHP Version: call_user_func(array($object,$methodName),$parameters) How do I achieve the above in Python?
[ "I don't see the problem, unless methodName is a string. In that case getattr does the job:\n>>> class A:\n... def func(self, a, b):\n... return a + b\n... \n>>> a = A()\n>>> getattr(a, 'func')(2, 3)\n5\n\nIf object is also a string, then this would work, using globals or locals (but then you may have o...
[ 10, 4, 2, 1, 0 ]
[]
[]
[ "php", "python" ]
stackoverflow_0000856992_php_python.txt
Q: Infinite recursion trying to check all elements of a TreeCtrl I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData. I thought the following code would solve the probl...
Infinite recursion trying to check all elements of a TreeCtrl
I have a TreeCtrl in which more than one Item can be assigned the same object as PyData. When the object is updated, I want to update all of the items in the tree which have that object as their PyData. I thought the following code would solve the problem quite neatly, but for some reason the logical test (current != s...
[ "How is the \"next\" item ever going to be the first item? \nThis appears to be a tautology. The next is never the first.\n current = self.GetNextVisible(current)\n\n current != self.GetFirstVisibleItem()\n\nIt doesn't appear that next wraps around to the beginning. It appears that next should return an in...
[ 3, 1, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0000857560_python_wxpython.txt
Q: List Element without iteration I want to know how to find an element in list without iteration A: The mylist.index("blah") method of a list will return the index of the first occurrence of the item "blah": >>> ["item 1", "blah", "item 3"].index("blah") 1 >>> ["item 1", "item 2", "blah"].index("blah") 2 It will ...
List Element without iteration
I want to know how to find an element in list without iteration
[ "The mylist.index(\"blah\") method of a list will return the index of the first occurrence of the item \"blah\":\n>>> [\"item 1\", \"blah\", \"item 3\"].index(\"blah\")\n1\n>>> [\"item 1\", \"item 2\", \"blah\"].index(\"blah\")\n2\n\nIt will raise ValueError if it cannot be found:\n>>> [\"item 1\", \"item 2\", \"it...
[ 9, 5, 4 ]
[]
[]
[ "find", "iteration", "list", "python" ]
stackoverflow_0000858109_find_iteration_list_python.txt
Q: Dead-simple web authentication for a single user I wrote a small internal web app using (a subset of) pylons. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes. What is the simplest way I ...
Dead-simple web authentication for a single user
I wrote a small internal web app using (a subset of) pylons. As it turns out, I now need to allow a user to access it from the web. This is not an application that was written to be web facing, and it has a bunch of gaping security holes. What is the simplest way I can make sure this site is securely available to that ...
[ "if there's only a single user, using a certificate would probably be easiest.\n", "How about VPN? There should be plenty of user-friendly VPN clients. He might already be familiar with the technology since many corporations use them to grant workers access to internal network while on the road.\n", "Basic HTTP...
[ 8, 4, 2 ]
[]
[]
[ "authentication", "python", "security", "web_applications" ]
stackoverflow_0000858149_authentication_python_security_web_applications.txt
Q: Datetime issue in Django I am trying to add the datetime object of a person. Whenever the birth year is less than year 1942, I get a strange error DataError: unable to parse time when reading the data back from the DB. class Person(models.Model): """A simple class to hold the person info """ name = mod...
Datetime issue in Django
I am trying to add the datetime object of a person. Whenever the birth year is less than year 1942, I get a strange error DataError: unable to parse time when reading the data back from the DB. class Person(models.Model): """A simple class to hold the person info """ name = models.CharField(max_length=100) ...
[ "The only thing I could come up with here can be found in the PostgreSQL docs. My guess is that Django is storing your date in a \"reltime\" field, which can only go back 68 years. My calculator verifies that 2009-68 == 1941, which seems very close to what you reported. \nI would recommend looking over the schema o...
[ 6 ]
[]
[]
[ "datetime", "django", "postgresql", "python" ]
stackoverflow_0000858470_datetime_django_postgresql_python.txt
Q: How to recognize whether a script is running on a tty? I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command). How do I recognize which of these two happen in a Python script? Example of such behavior in exist...
How to recognize whether a script is running on a tty?
I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command). How do I recognize which of these two happen in a Python script? Example of such behavior in existing program: grep --color=auto highlights matches when runni...
[ "import os, sys\nos.isatty(sys.stdout.fileno())\n\nor\nsys.stdout.isatty()\n\n" ]
[ 87 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0000858623_python_shell.txt
Q: getopts Values class and Template.Substitute don't (immediately) work together I have python code something like: from string import Template import optparse def main(): usage = "usage: %prog options outputname" p = optparse.OptionParser(usage) p.add_option('--optiona', '-a', default="") p.add_option('--o...
getopts Values class and Template.Substitute don't (immediately) work together
I have python code something like: from string import Template import optparse def main(): usage = "usage: %prog options outputname" p = optparse.OptionParser(usage) p.add_option('--optiona', '-a', default="") p.add_option('--optionb', '-b', default="") options, arguments = p.parse_args() t = Template('Opt...
[ "OptionParser.parse_args returns an object with the option variable names as attributes, rather than as dictionary keys. The error you're getting means that options does not support subscripting, which it would normally do by implementing __getitem__.\nSo, in other words, your options are at:\noptions.optiona\nopti...
[ 6, 4 ]
[]
[]
[ "getopts", "python", "templates" ]
stackoverflow_0000858784_getopts_python_templates.txt
Q: How to redirect python warnings to a custom stream? Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that? A: Try reassigning warnings.showwarning i.e. #!/sw/bin/python2.5 import warnings, sys def customwarn(message, category, ...
How to redirect python warnings to a custom stream?
Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that?
[ "Try reassigning warnings.showwarning i.e.\n#!/sw/bin/python2.5\n\nimport warnings, sys\n\ndef customwarn(message, category, filename, lineno, file=None, line=None):\n sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))\n\nwarnings.showwarning = customwarn\nwarnings.warn(\"test warning\...
[ 20, 0, 0 ]
[]
[]
[ "io", "python", "warnings" ]
stackoverflow_0000858916_io_python_warnings.txt
Q: Getting pdb-style caller information in python Let's say I have the following method (in a class or a module, I don't think it matters): def someMethod(): pass I'd like to access the caller's state at the time this method is called. traceback.extract_stack just gives me some strings about the call stack. I'd ...
Getting pdb-style caller information in python
Let's say I have the following method (in a class or a module, I don't think it matters): def someMethod(): pass I'd like to access the caller's state at the time this method is called. traceback.extract_stack just gives me some strings about the call stack. I'd like something like pdb in which I can set a breakpo...
[ "I figured it out:\nimport inspect\n\ndef callMe():\n tag = ''\n frame = inspect.currentframe()\n try:\n tag = frame.f_back.f_locals['self']._tag\n finally:\n del frame\n\n return tag\n\n" ]
[ 1 ]
[]
[]
[ "pdb", "python", "stack" ]
stackoverflow_0000859280_pdb_python_stack.txt
Q: whoami in python What is the best way to find out the user that a python process is running under? I could do this: name = os.popen('whoami').read() But that has to start a whole new process. os.environ["USER"] works sometimes, but sometimes that environment variable isn't set. A: import getpass print(getpass...
whoami in python
What is the best way to find out the user that a python process is running under? I could do this: name = os.popen('whoami').read() But that has to start a whole new process. os.environ["USER"] works sometimes, but sometimes that environment variable isn't set.
[ "import getpass\nprint(getpass.getuser())\n\nSee the documentation of the getpass module.\n\ngetpass.getuser()\nReturn the “login name” of the user. Availability: Unix, Windows.\nThis function checks the environment variables LOGNAME, USER,\nLNAME and USERNAME, in order, and\nreturns the value of the first one\nwhi...
[ 94, 20 ]
[]
[]
[ "posix", "python" ]
stackoverflow_0000860140_posix_python.txt
Q: How do I GROUP BY on every given increment of a field value? I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names o...
How do I GROUP BY on every given increment of a field value?
I have a Python application. It has an SQLite database, full of data about things that happen, retrieved by a Web scraper from the Web. This data includes time-date groups, as Unix timestamps, in a column reserved for them. I want to retrieve the names of organisations that did things and count how often they did them,...
[ "Create a table listing all weeks since the epoch, and JOIN it to your table of events.\nCREATE TABLE Weeks (\n week INTEGER PRIMARY KEY\n);\n\nINSERT INTO Weeks (week) VALUES (200919); -- e.g. this week\n\nSELECT w.week, e.org, COUNT(*)\nFROM Events e JOIN Weeks w ON (w.week = strftime('%Y%W', e.time))\nGROUP BY ...
[ 1, 1, 1 ]
[]
[]
[ "increment", "iteration", "python", "sql", "sqlite" ]
stackoverflow_0000859489_increment_iteration_python_sql_sqlite.txt
Q: How to debug a weird threaded open fifo issue? A web service is configured to expose some of its data when receiving a USR1 signal. The signal will be sent by a xinetd server when it receives a request from a remote client, e.g. nc myserver 50666. When the web server receives USR1 signal, it opens a dedicated fifo...
How to debug a weird threaded open fifo issue?
A web service is configured to expose some of its data when receiving a USR1 signal. The signal will be sent by a xinetd server when it receives a request from a remote client, e.g. nc myserver 50666. When the web server receives USR1 signal, it opens a dedicated fifo pipe, writes its data to the pipe, and then close t...
[ "If you get two copies of splitter.py running at the same time, there will be trouble and almost anything that happens to you is legal. Try adding a process id value to webserver.py, ie:\npipe.write(str(os.getpid()) + i + '\\n')\nThat might be illuminating.\n", "There isn't enough to debug here. You don't show...
[ 0, 0, 0 ]
[]
[]
[ "fifo", "inetd", "multithreading", "python", "stream" ]
stackoverflow_0000667500_fifo_inetd_multithreading_python_stream.txt
Q: Emacs function to add symbol to __all__ in Python mode? Is there an existing Emacs function that adds the symbol currently under the point to __all__ when editing Python code? E.g., say the cursor was on the first o in foo: # v---- cursor is on that 'o' def foo(): return 42 If you did M-x python-add-to-all...
Emacs function to add symbol to __all__ in Python mode?
Is there an existing Emacs function that adds the symbol currently under the point to __all__ when editing Python code? E.g., say the cursor was on the first o in foo: # v---- cursor is on that 'o' def foo(): return 42 If you did M-x python-add-to-all (or whatever) it would add 'foo' to __all__. I didn't see on...
[ "Not being a python programmer, I'm not sure this covers all the cases, but works for me in a simple case. It'll add the symbol to the array if the array exists, and create __all__ if it doesn't exist. Note: it does not parse the array to avoid double insertion.\n(defun python-add-to-all ()\n \"take the symbol u...
[ 10 ]
[]
[]
[ "emacs", "python" ]
stackoverflow_0000860357_emacs_python.txt
Q: How use __setattr__ & __getattr__ for map INI values? I want to map a INI file as a python object. So if the file have: [UserOptions] SampleFile = sample.txt SamplePort = 80 SampleInt = 1 Sample = Aja SampleDate = 10/02/2008 Then I want: c = Configuration('sample.ini') c.UserOptions.SamplePort = 90 I'm looking ...
How use __setattr__ & __getattr__ for map INI values?
I want to map a INI file as a python object. So if the file have: [UserOptions] SampleFile = sample.txt SamplePort = 80 SampleInt = 1 Sample = Aja SampleDate = 10/02/2008 Then I want: c = Configuration('sample.ini') c.UserOptions.SamplePort = 90 I'm looking to setattr but I get a recursion error. This is what I have...
[ "You are trying to get the sections on request. But it is much easier to iterate over sections and options and add them as attribute in __init__. I edited my example to support setattr as well. You problem is explained here you are assigning the attributes in __setattr__ while you should use __dict__ instead\nfrom ...
[ 4, 4 ]
[]
[]
[ "configuration_files", "python" ]
stackoverflow_0000860744_configuration_files_python.txt
Q: Lay out import pathing in Python, straight and simple? If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax? Does java-style reference work in Python also? I.e., do directories correspond to dots? What...
Lay out import pathing in Python, straight and simple?
If a group of Python developers wants to put their shared code somewhere, in a hierarchical structure, what's the structure, and what's the related "import" syntax? Does java-style reference work in Python also? I.e., do directories correspond to dots? What is standard setup for an internal-use-only library of Pytho...
[ "What we do.\nDevelopment\n\nc:\\someroot\\project\\thing__init__.py # makes thing a package\nc:\\someroot\\project\\thing\\foo.py\nc:\\someroot\\project\\thing\\bar.py\n\nOur \"environment\" (set in a variety of ways\nSET PYTHONPATH=\"C:\\someroot\\project\"\n\nSome file we're working on\n import thing.foo\n impor...
[ 7, 3 ]
[]
[]
[ "import", "python" ]
stackoverflow_0000860672_import_python.txt
Q: Is there a Python equivalent to Java's AWT Robot class? Does anyone know of a Python class similar to Java Robot? Specifically I would like to perform a screen grab in Ubuntu, and eventually track mouse clicks and keyboard presses (although that's a slightly different question). A: If you have GTK, then you can...
Is there a Python equivalent to Java's AWT Robot class?
Does anyone know of a Python class similar to Java Robot? Specifically I would like to perform a screen grab in Ubuntu, and eventually track mouse clicks and keyboard presses (although that's a slightly different question).
[ "If you have GTK, then you can use the gtk.gdk.Display class to do most of the work. It controls the keyboard/mouse pointer grabs a set of gtk.gdk.Screen objects.\n", "Check out GNU LDTP:\n\nGNU/Linux Desktop Testing Project (GNU\n LDTP) is aimed at producing high\n quality test automation framework\n [...]\n\...
[ 6, 3, 0 ]
[ "Check out the RobotFramework. I do not know if it will do the same things as JavaRobot, or if it will do more. But it is easy and very flexible to use.\n" ]
[ -1 ]
[ "automation", "awtrobot", "linux", "python", "screenshot" ]
stackoverflow_0000860013_automation_awtrobot_linux_python_screenshot.txt
Q: How do capture groups work? (wrt python regular expressions) While using regex to help solve a problem in the Python Challenge, I came across some behaviour that confused me. from here: (...) Matches whatever regular expression is inside the parentheses. and '+' Causes the resulting RE to match 1 or more repetiti...
How do capture groups work? (wrt python regular expressions)
While using regex to help solve a problem in the Python Challenge, I came across some behaviour that confused me. from here: (...) Matches whatever regular expression is inside the parentheses. and '+' Causes the resulting RE to match 1 or more repetitions of the preceding RE. So this makes sense: >>>import re >>>re.f...
[ "Because you only have one capturing group, but it's \"run\" repeatedly, the new matches are repeatedly entered into the \"storage space\" for that group. In other words, the 1s were lost when they were \"overwritten\" by subsequent 1s and eventually the 2.\n", "You are repeating the group itself by appending '+...
[ 10, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0000861060_python_regex.txt
Q: How can I find the locations of an item in a Python list of lists? I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example: list = [['1', '2', '4', '6'], ['7', '0', '1', '4']]...
How can I find the locations of an item in a Python list of lists?
I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example: list = [['1', '2', '4', '6'], ['7', '0', '1', '4']] getPosition('1') #returns [(0, 0), (1, 2)] and getPosition('7') #retur...
[ "If you want something that will both \n\nfind duplicates and \nhandle nested lists (lists of lists of lists of ...)\n\nyou can do something like the following:\ndef get_positions(xs, item):\n if isinstance(xs, list):\n for i, it in enumerate(xs):\n for pos in get_positions(it, item):\n ...
[ 8, 6, 4, 3, 3, 1, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000853023_python.txt
Q: A class method which behaves differently when called as an instance method? I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method. For example, as a skills-improvement project, I'm writing a Matrix class (yes, I know there are...
A class method which behaves differently when called as an instance method?
I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method. For example, as a skills-improvement project, I'm writing a Matrix class (yes, I know there are perfectly good matrix classes already out there). I've created a class method fo...
[ "Questionably useful Python hacks are my forte.\nfrom types import *\n\nclass Foo(object):\n def __init__(self):\n self.bar = methodize(bar, self)\n self.baz = 999\n\n @classmethod\n def bar(cls, baz):\n return 2 * baz\n\n\ndef methodize(func, instance):\n return MethodType(func, in...
[ 39, 7, 7, 3, 2 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0000861055_class_methods_python.txt
Q: Is python automagically parallelizing IO- and CPU- or memory-bound sections? This is a follow-up questions on a previous one. Consider this code, which is less toyish than the one in the previous question (but still much simpler than my real one) import sys data=[] for line in open(sys.argv[1]): data.append(l...
Is python automagically parallelizing IO- and CPU- or memory-bound sections?
This is a follow-up questions on a previous one. Consider this code, which is less toyish than the one in the previous question (but still much simpler than my real one) import sys data=[] for line in open(sys.argv[1]): data.append(line[-1]) print data[-1] Now, I was expecting a longer run time (my benchmark fil...
[ "\nObviously data.append() is happening in parallel with the IO.\n\nI'm afraid not. It is possible to parallelize IO and computation in Python, but it doesn't happen magically.\nOne thing you could do is use posix_fadvise(2) to give the OS a hint that you plan to read the file sequentially (POSIX_FADV_SEQUENTIAL)....
[ 8, 1, 1, 1, 1 ]
[]
[]
[ "linux", "performance", "python", "text_files" ]
stackoverflow_0000860893_linux_performance_python_text_files.txt
Q: django and mod_wsgi having database connection issues I've noticed that whenever I enable the database settings on my django project (starting to notice a trend in my questions?) it gives me an internal server error. Setting the database settings to be blank makes the error go away. Here are the apache error logs ...
django and mod_wsgi having database connection issues
I've noticed that whenever I enable the database settings on my django project (starting to notice a trend in my questions?) it gives me an internal server error. Setting the database settings to be blank makes the error go away. Here are the apache error logs that it outputs. mod_wsgi (pid=770): Exception occurred pro...
[ "You need to set the PYTHON_EGG_CACHE environment variable. Apache/mod_wsgi is trying to extract the egg into a directory that Apache doesn't have write access to....or that doesn't exist.\nIt's explained in the Django docs here.\nDoes /Library/WebServer/.python-eggs exist? What does your Apache config file look ...
[ 8 ]
[]
[]
[ "django", "mod_wsgi", "python" ]
stackoverflow_0000860169_django_mod_wsgi_python.txt
Q: Decoding problems in Django and lxml I have a strange problem with lxml when using the deployed version of my Django application. I use lxml to parse another HTML page which I fetch from my server. This works perfectly well on my development server on my own computer, but for some reason it gives me UnicodeDecod...
Decoding problems in Django and lxml
I have a strange problem with lxml when using the deployed version of my Django application. I use lxml to parse another HTML page which I fetch from my server. This works perfectly well on my development server on my own computer, but for some reason it gives me UnicodeDecodeError on the server. ('utf8', "\x85why he...
[ "\"\\x85why hello there!\" is not a utf-8 encoded string. You should try decoding the webpage before passing it to lxml. Check what encoding it uses by looking at the http headers when you fetch the page maybe you find the problem there.\n", "Doesn't syntax such as u\"\\x85why hello there!\" help? \nYou may find ...
[ 3, 0 ]
[ "Since modifying site.py is not an ideal solution try this at the start of your program:\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\n" ]
[ -2 ]
[ "decoding", "django", "lxml", "python", "utf_8" ]
stackoverflow_0000808275_decoding_django_lxml_python_utf_8.txt
Q: tokenize module Please help There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc. >>> import cStringIO >>> import tokenize >>> source = "{'test':'123','hehe':['hooray',0x10]}" >>> src = cStringIO.StringIO(source).readline >>> src = tokenize.generate_tokens(src) >>> src <generator object at...
tokenize module
Please help There are many tokens in module tokenize like STRING,BACKQUOTE,AMPEREQUAL etc. >>> import cStringIO >>> import tokenize >>> source = "{'test':'123','hehe':['hooray',0x10]}" >>> src = cStringIO.StringIO(source).readline >>> src = tokenize.generate_tokens(src) >>> src <generator object at 0x00BFBEE0> >>> src....
[ "The various AMPER, BACKQUOTE etc values correspond to the token number of the appropriate symbol for python tokens / operators. ie AMPER = & (ampersand), AMPEREQUAL = \"&=\".\nHowever, you don't actually have to care about these. They're used by the internal C tokeniser, but the python wrapper simplifies the out...
[ 4, 3, 2 ]
[]
[]
[ "python", "tokenize" ]
stackoverflow_0000856769_python_tokenize.txt
Q: Extracting bitmap from a file given a somewhat complex file of unknown specification that among other things contains an uncompressed bitmap file (.BMP), how would you extract it in Python? Scan for the "BM" tag and see if the following bytes "resemble" a BMP header? A: I'd use the Python Imaging Library PIL and...
Extracting bitmap from a file
given a somewhat complex file of unknown specification that among other things contains an uncompressed bitmap file (.BMP), how would you extract it in Python? Scan for the "BM" tag and see if the following bytes "resemble" a BMP header?
[ "I'd use the Python Imaging Library PIL and have it a go at the data. If it can parse it, then it's a valid image. When it throws an exception, then it isn't.\nYou need to search for the begining of the image; if you're lucky, the image reader will ignore garbage after the image data. When it doesn't, use a binary ...
[ 4, 4 ]
[]
[]
[ "heuristics", "python" ]
stackoverflow_0000862487_heuristics_python.txt
Q: Pointers in Python on variables with None value I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side. I want to refactor this code, so that I first see on which side I have to insert my element,...
Pointers in Python on variables with None value
I have a method that creates a new node in a tree - either left or right. If the value is lower than my current value it is inserted on the left, otherwise on the right side. I want to refactor this code, so that I first see on which side I have to insert my element, and then insert it. Before I implemented this twice:...
[ "In Python variables are names not locations. For example:\n>>> a = 1\n>>> b = a\n>>> a = 2\n>>> print b\n1\n\nIn your code you're simply rebinding the name child to a different value (your new node) and that has no affect on the previously bound value (None).\nHere's a reworking of your code that should do what y...
[ 2, 0, 0 ]
[]
[]
[ "python", "reference" ]
stackoverflow_0000862652_python_reference.txt
Q: Txt file parse to get a list of .o file names I have a txt file like : test.txt Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | ...
Txt file parse to get a list of .o file names
I have a txt file like : test.txt Symbols from __ctype_tab.o: Name Value Class Type Size Line Section __ctype |00000000| D | OBJECT|00000004| |.data __ctype_tab |00000000| r | OBJECT|00000101| |.rodata Symbols from _ashl...
[ "I would use regular expressions with capture groups for the different kinds of interesting lines in your file; I'd go through the file line by line, and as I found an interesting line (i.e. matched the regex), I'd process the captured data from the regex appropriately.\nAfter having built up dictionaries etc., ans...
[ 1, 1, 1 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0000862203_parsing_python.txt
Q: Python Module by Path I am writing a minimal replacement for mod_python's publisher.py The basic premise is that it is loading modules based on a URL scheme: /foo/bar/a/b/c/d Whereby /foo/ might be a directory and 'bar' is a method ExposedBar in a publishable class in /foo/index.py. Likewise /foo might map to /fo...
Python Module by Path
I am writing a minimal replacement for mod_python's publisher.py The basic premise is that it is loading modules based on a URL scheme: /foo/bar/a/b/c/d Whereby /foo/ might be a directory and 'bar' is a method ExposedBar in a publishable class in /foo/index.py. Likewise /foo might map to /foo.py and bar is a method in...
[ "\nCan I load a module by it's absolute\n path into a module object? Without\n modification of sys.path. I can't find\n any docs on __import__ or new.module()\n for this.\n\nimport imp\nimport os\n\ndef module_from_path(path):\n filename = os.path.basename(path)\n modulename = os.path.splitext(filename)[0...
[ 3 ]
[]
[]
[ "mod_python", "python" ]
stackoverflow_0000863234_mod_python_python.txt
Q: Which PEP governs the ordering of dict.values()? When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict simply states that the ordering is "arbitrary". I remember reading ...
Which PEP governs the ordering of dict.values()?
When you call dict.values() the order of the returned items is dependent on the has value of the keys. This seems to be very consistent in all versions of cPython, however the python manual for dict simply states that the ordering is "arbitrary". I remember reading somewhere that there is actually a PEP which specifica...
[ "From http://docs.python.org/library/stdtypes.html:\n\nKeys and values are listed in an\n arbitrary order which is non-random,\n varies across Python implementations,\n and depends on the dictionary’s\n history of insertions and deletions.\n\n", "I suppose PEP-3106 is as close as it gets:\n\nThe specification...
[ 7, 6, 2 ]
[]
[]
[ "dictionary", "python" ]
stackoverflow_0000863446_dictionary_python.txt
Q: Ordering a list of dictionaries in python I've got a python list of dictionaries: mylist = [ {'id':0, 'weight':10, 'factor':1, 'meta':'ABC'}, {'id':1, 'weight':5, 'factor':1, 'meta':'ABC'}, {'id':2, 'weight':5, 'factor':2, 'meta':'ABC'}, {'id':3, 'weight':1, 'factor':1, 'meta':'ABC'} ] Whats the most efficient/cl...
Ordering a list of dictionaries in python
I've got a python list of dictionaries: mylist = [ {'id':0, 'weight':10, 'factor':1, 'meta':'ABC'}, {'id':1, 'weight':5, 'factor':1, 'meta':'ABC'}, {'id':2, 'weight':5, 'factor':2, 'meta':'ABC'}, {'id':3, 'weight':1, 'factor':1, 'meta':'ABC'} ] Whats the most efficient/cleanest way to order that list by weight then fa...
[ "mylist.sort(key=lambda d: (d['weight'], d['factor']))\n\nor\nimport operator\nmylist.sort(key=operator.itemgetter('weight', 'factor'))\n\n", "Something along the lines of the following ought to work:\ndef cmp_dict(x, y):\n weight_diff = y['weight'] - x['weight']\n if weight_diff == 0:\n return y['fa...
[ 23, 1, 1 ]
[ "decoratedlist = [(item[weight], item) for item in mylist]\ndecoratedlist.sort()\nresults = [item for (key, item) in decoratedlist]\n\n" ]
[ -1 ]
[ "dictionary", "list", "python" ]
stackoverflow_0000861190_dictionary_list_python.txt
Q: Python: adding namespaces in lxml I'm trying to specify a namespace using lxml similar to this example (taken from here): <TreeInventory xsi:noNamespaceSchemaLocation="Trees.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </TreeInventory> I'm not sure how to add the Schema instance to use and also the...
Python: adding namespaces in lxml
I'm trying to specify a namespace using lxml similar to this example (taken from here): <TreeInventory xsi:noNamespaceSchemaLocation="Trees.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> </TreeInventory> I'm not sure how to add the Schema instance to use and also the Schema location. The documentation got...
[ "In some more steps, for clarity:\n>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'\n\nAs far as I can see, it is the attribute noNamespaceSchemaLocation that you want namespaced, not the TreeInventory element. So:\n>>> location_attribute = '{%s}noNamespaceSchemaLocation' % NS # f-string doesn't work in this...
[ 10 ]
[]
[]
[ "lxml", "python", "xml_namespaces" ]
stackoverflow_0000863183_lxml_python_xml_namespaces.txt
Q: Python While Loop Condition Evaluation Say I have the following loop: i = 0 l = [0, 1, 2, 3] while i < len(l): if something_happens: l.append(something) i += 1 Will the len(i) condition being evaluated in the while loop be updated when something is appended to l? A: Yes it will. A: Your code ...
Python While Loop Condition Evaluation
Say I have the following loop: i = 0 l = [0, 1, 2, 3] while i < len(l): if something_happens: l.append(something) i += 1 Will the len(i) condition being evaluated in the while loop be updated when something is appended to l?
[ "Yes it will.\n", "Your code will work, but using a loop counter is often not considered very \"pythonic\". Using for works just as well and eliminates the counter:\n>>> foo = [0, 1, 2]\n>>> for bar in foo:\n if bar % 2: # append to foo for every odd number\n foo.append(len(foo))\n print...
[ 14, 3 ]
[]
[]
[ "python", "while_loop" ]
stackoverflow_0000864603_python_while_loop.txt
Q: Beginning Windows Mobile 6.1 Development With Python I've wanted to get into Python development for awhile and most of my programming experience has been in .NET and no mobile development. I recently thought of a useful app to make for my windows mobile phone and thought this could be a great first Python project...
Beginning Windows Mobile 6.1 Development With Python
I've wanted to get into Python development for awhile and most of my programming experience has been in .NET and no mobile development. I recently thought of a useful app to make for my windows mobile phone and thought this could be a great first Python project. I did a little research online and found PyCe which I ...
[ "Can't help you much with Python\\CE but if you want a great db for mobile devices SQLLite will do the job for you. If you do a quick google you'll find there are libraries for connecting to SQLLite with Python too.\n" ]
[ 1 ]
[]
[]
[ "mobile_phones", "python", "windows_mobile" ]
stackoverflow_0000864887_mobile_phones_python_windows_mobile.txt
Q: Python os.forkpty why can't I make it work import pty import os import sys import time pid, fd = os.forkpty() if pid == 0: # Slave os.execlp("su","su","MYUSERNAME","-c","id") # Master print os.read(fd, 1000) os.write(fd,"MYPASSWORD\n") time.sleep(1) print os.read(fd, 1000) os.waitpid(pid,0) print "Why h...
Python os.forkpty why can't I make it work
import pty import os import sys import time pid, fd = os.forkpty() if pid == 0: # Slave os.execlp("su","su","MYUSERNAME","-c","id") # Master print os.read(fd, 1000) os.write(fd,"MYPASSWORD\n") time.sleep(1) print os.read(fd, 1000) os.waitpid(pid,0) print "Why have I not seen any output from id?"
[ "You are sleeping for too long. Your best bet is to start reading as soon as you can one byte at a time.\n#!/usr/bin/env python\n\nimport os\nimport sys\n\npid, fd = os.forkpty()\n\nif pid == 0:\n # child\n os.execlp(\"ssh\",\"ssh\",\"hostname\",\"uname\")\nelse:\n # parent\n print os.read(fd, 1000)\n ...
[ 5 ]
[]
[]
[ "pty", "python" ]
stackoverflow_0000864826_pty_python.txt
Q: How can I get the name of a python class? When I have an object foo, I can get it's class object via str(foo.__class__) What I would need however is only the name of the class ("Foo" for example), the above would give me something along the lines of "<class 'my.package.Foo'>" I know I can get it quite easily wi...
How can I get the name of a python class?
When I have an object foo, I can get it's class object via str(foo.__class__) What I would need however is only the name of the class ("Foo" for example), the above would give me something along the lines of "<class 'my.package.Foo'>" I know I can get it quite easily with a regexp, but I would like to know if there'...
[ "Try\n__class__.__name__\n\n", "foo.__class__.__name__ should give you result you need.\n", "Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> class foo:\n... x = 1\n...\n>>> f = foo()\n>...
[ 4, 3, 1 ]
[]
[]
[ "inspection", "python", "reflection" ]
stackoverflow_0000865384_inspection_python_reflection.txt
Q: how to isinstance(x, module)? I need to test if a variable is a module or not. How to do this in the cleanest way? I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument. A: >>> import os, types >>> isinstance(os, types.ModuleType) True ...
how to isinstance(x, module)?
I need to test if a variable is a module or not. How to do this in the cleanest way? I need this for initializing some dispatcher function and I want that the function can accept either dict or module as an argument.
[ ">>> import os, types\n>>> isinstance(os, types.ModuleType)\nTrue\n\n(It also works for your own Python modules, as well as built-in ones like os.)\n", "I like to use this so you don't have to import the types module:\nisinstance(amodule, __builtins__.__class__)\n\n" ]
[ 38, 6 ]
[]
[]
[ "python" ]
stackoverflow_0000865503_python.txt
Q: How can I perform divison on a datetime.timedelta in python? I'd like to be able to do the following: num_intervals = (cur_date - previous_date) / interval_length or print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' but the divisio...
How can I perform divison on a datetime.timedelta in python?
I'd like to be able to do the following: num_intervals = (cur_date - previous_date) / interval_length or print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' but the division operation is unsupported on timedeltas. Is there a way that I ca...
[ "Division and multiplication by integers seems to work out of the box:\n>>> from datetime import timedelta\n>>> timedelta(hours=6)\ndatetime.timedelta(0, 21600)\n>>> timedelta(hours=6) / 2\ndatetime.timedelta(0, 10800)\n\n", "Sure, just convert to a number of seconds (minutes, milliseconds, hours, take your pick ...
[ 16, 11, 4 ]
[]
[]
[ "date", "datetime", "division", "python", "timedelta" ]
stackoverflow_0000865618_date_datetime_division_python_timedelta.txt
Q: Can I get rows from SQLAlchemy that are plain arrays, rather than dictionaries? I'm trying to optimize some Python code. The profiler tells me that SQLAlchemy's _get_col() is what's killing performance. The code looks something like this: lots_of_rows = get_lots_of_rows() for row in lots_of_rows: if row.x == r...
Can I get rows from SQLAlchemy that are plain arrays, rather than dictionaries?
I'm trying to optimize some Python code. The profiler tells me that SQLAlchemy's _get_col() is what's killing performance. The code looks something like this: lots_of_rows = get_lots_of_rows() for row in lots_of_rows: if row.x == row.y: print row.z I was about to go through the code and make it more like t...
[ "Forgive the obvious answer, but why isn't row.x == row.y in your query? For example:\nmytable.select().where(mytable.c.x==mytable.c.y)\n\nShould give you a huge performance boost. Read the rest of the documentation.\n", "I think row.items() is what you're looking for. It returns a list of (key, value) tuples fo...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000656050_python_sqlalchemy.txt
Q: Converting an ImageMagick FX operator to pure Python code with PIL I'm trying to port some image processing functionality from an Image Magick command (using the Fx Special Effects Image Operator) to Python using PIL. My issue is that I'm not entirely understanding what this fx operator is doing: convert input.pn...
Converting an ImageMagick FX operator to pure Python code with PIL
I'm trying to port some image processing functionality from an Image Magick command (using the Fx Special Effects Image Operator) to Python using PIL. My issue is that I'm not entirely understanding what this fx operator is doing: convert input.png gradient.png -fx "v.p{0,u*v.h}" output.png From a high level, this co...
[ "I know it's been about a month and you might has already figured it out. But here is the answer.\nFrom ImageMagicK documentation I was able to understand what the effect is actually doing.\nconvert input.png gradient.png -fx \"v.p{0,u*v.h}\" output.png\n\nv is the second image (gradient.png)\nu is the first image ...
[ 1 ]
[]
[]
[ "imagemagick", "python", "python_imaging_library" ]
stackoverflow_0000789401_imagemagick_python_python_imaging_library.txt
Q: Elixir (SqlAlchemy): relations between 3 tables with composite primary keys I've 3 tables: A Company table with (company_id) primary key A Page table with (company_id, url) primary key & a foreign key back to Company An Attr table with (company_id, attr_key) primary key & a foreign key back to Company. My questi...
Elixir (SqlAlchemy): relations between 3 tables with composite primary keys
I've 3 tables: A Company table with (company_id) primary key A Page table with (company_id, url) primary key & a foreign key back to Company An Attr table with (company_id, attr_key) primary key & a foreign key back to Company. My question is how to construct the ManyToOne relation from Attr back to Page using the ex...
[ "Yes you can do this. Elixir doesn't have a built in way to do this, but because it's a thin wrapper on SQLAlchemy you can convince it to do this. Because Elixir doesn't have a concept of a many-to-one relation that reuses existing columns you need to use the GenericProperty with the SQLAlchemy relation property an...
[ 2 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0000835834_python_python_elixir_sqlalchemy.txt
Q: How to generate XML documents with namespaces in Python I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom: import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'el') doc.appendChild(el) print(doc.toprettyxml()) The ...
How to generate XML documents with namespaces in Python
I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom: import xml.dom.minidom doc = xml.dom.minidom.Document() el = doc.createElementNS('http://example.net/ns', 'el') doc.appendChild(el) print(doc.toprettyxml()) The namespace is saved (doc.childNodes[0].namespaceURI is 'http:/...
[ "createElementNS() is defined as:\ndef createElementNS(self, namespaceURI, qualifiedName):\n prefix, localName = _nssplit(qualifiedName)\n e = Element(qualifiedName, namespaceURI, prefix)\n e.ownerDocument = self\n return e\n\nso…\nimport xml.dom.minidom\ndoc = xml.dom.minidom.Document()\nel = doc.creat...
[ 21, 5 ]
[]
[]
[ "dom", "namespaces", "python", "xml" ]
stackoverflow_0000863774_dom_namespaces_python_xml.txt
Q: In Django, how can you change the User class to work with a different db table? We're running django alongside - and sharing a database with - an existing application. And we want to use an existing "user" table (not Django's own) to store user information. It looks like it's possible to change the name of the ta...
In Django, how can you change the User class to work with a different db table?
We're running django alongside - and sharing a database with - an existing application. And we want to use an existing "user" table (not Django's own) to store user information. It looks like it's possible to change the name of the table that Django uses, in the Meta class of the User definition. But we'd prefer not ...
[ "You might find it useful to set up your old table as an alternative authentication source and sidestep all these issues. \nAnother option is to subclass the user and have the subclass point to your user-model. Override the save function to ensure that everything you need to do to preserve your old functionality is...
[ 6 ]
[]
[]
[ "django", "django_models", "monkeypatching", "python" ]
stackoverflow_0000866418_django_django_models_monkeypatching_python.txt
Q: Algorithm: How to Delete every other file I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)? Thx A: To delete half the N images you cannot...
Algorithm: How to Delete every other file
I have a folder with thousands of images. I want to delete every other image. What is the most effective way to do this? Going through each one with i%2==0 is still O(n). Is there a fast way to do this (preferably in Python)? Thx
[ "To delete half the N images you cannot be faster than O(N)! You do know that the O() notation means (among other things) that constant multiplicative factors are irrelevant, yes?\n", "import os\nl = os.listdir('/some/dir/with/files')\n\nfor n in l[::2]:\n os.unlink(n)\n\n", "\nGoing through each one with i...
[ 21, 13, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0000865973_algorithm_python.txt
Q: Defining a table with sqlalchemy with a mysql unix timestamp Background, there are several ways to store dates in MySQ. As a string e.g. "09/09/2009". As integer using the function UNIX_TIMESTAMP() this is supposedly the traditional unix time representation (you know seconds since the epoch plus/minus leap second...
Defining a table with sqlalchemy with a mysql unix timestamp
Background, there are several ways to store dates in MySQ. As a string e.g. "09/09/2009". As integer using the function UNIX_TIMESTAMP() this is supposedly the traditional unix time representation (you know seconds since the epoch plus/minus leap seconds). As a MySQL TIMESTAMP, a mysql specific data type not the same ...
[ "I think there is a couple of issues with the type decorator you showed.\n\nimpl should be sqlalchemy.types.Integer instead of DateTime.\nThe decorator should allow nullable columns.\n\nHere's the what I have in mind:\n\nimport datetime, time\nfrom sqlalchemy.types import TypeDecorator, DateTime, Integer\n\nclass I...
[ 8, 3 ]
[]
[]
[ "mysql", "python", "sqlalchemy" ]
stackoverflow_0000762750_mysql_python_sqlalchemy.txt
Q: Python: File IO - Disable incremental flush Kind of the opposite of this question. Is there a way to tell Python "Do not write to disk until I tell you to." (by closing or flushing the file)? I'm writing to a file on the network, and would rather write the entire file at once. In the meantime, I'm writing to a St...
Python: File IO - Disable incremental flush
Kind of the opposite of this question. Is there a way to tell Python "Do not write to disk until I tell you to." (by closing or flushing the file)? I'm writing to a file on the network, and would rather write the entire file at once. In the meantime, I'm writing to a StringIO buffer, and then writing that to the disk ...
[ "No, a glance at the python manual does not indicate an option to set the buffer size to infinity. \nYour current solution is basically the same concept.\nYou could use Alex's idea, but I would hazard against it for the following reasons:\n\nThe buffer size on open is limited to 2^31-1 or 2 gigs. Any larger will re...
[ 3, 3, 1 ]
[]
[]
[ "file_io", "python" ]
stackoverflow_0000865957_file_io_python.txt
Q: Need Help Understanding how to use less complex regex in Python I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results missi...
Need Help Understanding how to use less complex regex in Python
I am trying to learn more about regular expressions I have one below that I believe finds cases where there is a missing close paren on a number up to 999 billion. The one below it I thought should do the same but I do not get similar results missingParenReg=re.compile(r"^\([$]*[0-9]{1,3}[,]?[0-9]{0,3}[,]?[0-9]{0,3}...
[ "Are there nested parentheses (your regexps assume there are not)? If not:\nwhether_paren_is_missing = (astring[0] == '(' and not astring[-1] == ')')\n\nTo validate a dollar amount part:\nimport re\n\ncents = r\"(?:\\.\\d\\d)\" # cents \nre_dollar_amount = re.compile(r\"\"\"(?x)\n ^ # match at the ...
[ 4, 3, 0 ]
[ "One difference I see at a glance is that your regex will not find strings like:\n(123,,,\n\nThat's because the corrected version requires at least one digit between commas. (A reasonable requirement, I'd say.) \n" ]
[ -1 ]
[ "python", "regex" ]
stackoverflow_0000361443_python_regex.txt
Q: keyerror inside django model class __init__ Here's a Django model class I wrote. This class gets a keyerror when I call get_object_or_404 from Django (I conceive that keyerror is raised due to no kwargs being passed to __init__ by the get function, arguments are all positional). Interestingly, it does not get an e...
keyerror inside django model class __init__
Here's a Django model class I wrote. This class gets a keyerror when I call get_object_or_404 from Django (I conceive that keyerror is raised due to no kwargs being passed to __init__ by the get function, arguments are all positional). Interestingly, it does not get an error when I call get_object_or_404 from console. ...
[ "self.user = kwargs['user'].pop()\nself.event_type = kwargs['event_type'].pop()\n\nYou're trying to retrieve an entry from the dictionary, and then call its pop method. If you want to remove and return an object from a dictionary, call dict.pop():\nself.user = kwargs.pop('user')\n\nOf course, this will fail with a ...
[ 7, 2, 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0000866399_django_django_models_python.txt
Q: db connection in python I am writing a code in python in which I established a connection with database. I have queries in a loop. While queries being executed in the loop , If i unplug the network cable it should stop with an exception. But this not happens, When i again plug yhe network cabe after 2 minutes it s...
db connection in python
I am writing a code in python in which I established a connection with database. I have queries in a loop. While queries being executed in the loop , If i unplug the network cable it should stop with an exception. But this not happens, When i again plug yhe network cabe after 2 minutes it starts again from where it end...
[ "Your database connection will almost certainly be based on a TCP socket. TCP sockets will hang around for a long time retrying before failing and (in python) raising an exception. Not to mention and retries/automatic reconnection attempts in the database layer.\n", "As Douglas's answer said, it won't raise excep...
[ 2, 2, 1 ]
[]
[]
[ "database_connection", "python", "tcp" ]
stackoverflow_0000867175_database_connection_python_tcp.txt
Q: Numbers Comparison - Python Bug? Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that: if t.index_value < len(work_list): ... do stuff ... else:...
Numbers Comparison - Python Bug?
Deep inside my code, in a nested if inside a nested for inside a class method, I'm comparing a certain index value to the length of a certain list, to validate I can access that index. The code looks something like that: if t.index_value < len(work_list): ... do stuff ... else: ... print some error ... For cla...
[ "In my experience, what is the type of \"t.index_value\"? Maybe it is a string \"3\".\n>>> print '3' < 4\nFalse\n\n", "To display values which might be of different types than you expect (e.g. a string rather than a number, as kcwu suggests), use repr(x) and the like.\n" ]
[ 8, 2 ]
[]
[]
[ "numbers", "python" ]
stackoverflow_0000867436_numbers_python.txt
Q: python dealing with Nonetype before cast\addition I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (TypeError: unsupported operand type(s) for +: 'NoneType' and 'int') Right now, with each field...
python dealing with Nonetype before cast\addition
I'm pulling a row from a db and adding up the fields (approx 15) to get a total. But some field values will be Null, which causes an error in the addition of the fields (TypeError: unsupported operand type(s) for +: 'NoneType' and 'int') Right now, with each field, I get the field value and set it to 'x#', then check ...
[ "You can do it easily like this:\nresult = sum(field for field in row if field)\n\n", "Another (better?) option is to do this in the database. You can alter your db query to map NULL to 0 using COALESCE.\nSay you have a table with integer columns named col1, col2, col3 that can accept NULLs.\nOption 1:\nSELECT co...
[ 13, 1, 0, 0 ]
[]
[]
[ "python", "types" ]
stackoverflow_0000866208_python_types.txt
Q: What host to use when making a UDP socket in python? I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python: import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, s...
What host to use when making a UDP socket in python?
I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python: import socket import sys HOST = ??????? PORT = 80 # SOCK_DGRAM is the socket type to use for UDP sockets sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((HOST,PORT)) data,addr = soc...
[ "The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run som...
[ 10, 3, 3 ]
[]
[]
[ "python", "sockets", "udp" ]
stackoverflow_0000868173_python_sockets_udp.txt
Q: How to catch str exception? import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch ...
How to catch str exception?
import sys try: raise "xxx" except str,e: print "1",e except: print "2",sys.exc_type,sys.exc_value In the above code a string exception is raised which though deprecated but still a 3rd party library I use uses it. So how can I catch such exception without relying on catch all, which could be bad. except s...
[ "The generic except: clause is the only way to catch all str exceptions.\nstr exceptions are a legacy Python feature. In new code you should use raise Exception(\"xxx\") or raise your own Exception subclass, or assert 0, \"xxx\".\n", "Here is the solution from python mailing list, not very elegant but will work i...
[ 6, 4, 2, 2 ]
[]
[]
[ "exception", "python", "string" ]
stackoverflow_0000867522_exception_python_string.txt
Q: Loading files into variables I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace. I tried using this in a file: import cPickle # # Load if neccesary # def loadfile(variable, filename): if variable not in gl...
Loading files into variables
I am trying to write a small function that gets a variable name, check if it exists, and if not loads it from a file (using pickle) to the global namespace. I tried using this in a file: import cPickle # # Load if neccesary # def loadfile(variable, filename): if variable not in globals(): cmd = "%s = cPick...
[ "You could alway avoid exec entirely:\n\n\nimport cPickle\n\n#\n# Load if neccesary\n#\ndef loadfile(variable, filename):\n g=globals()\n if variable not in g:\n g[variable]=cPickle.load(file(filename,'r'))\n\n\n\nEDIT: of course that only loads the globals into the current module's globals.\nIf you wa...
[ 2, 2 ]
[]
[]
[ "namespaces", "pickle", "python" ]
stackoverflow_0000868112_namespaces_pickle_python.txt
Q: Python Newbie: Returning Multiple Int/String Results in Python I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. In C/C++ I would use @ ...
Python Newbie: Returning Multiple Int/String Results in Python
I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's ...
[ "python has a return statement, which allows you to do the follwing:\ndef func(input):\n # do calculation on input\n return result\n\ns = \"hello goodbye\"\nres = func(s) # res now a result dictionary\n\nbut you don't need to have result at all, you can return a few values like so:\ndef func(input):\n ...
[ 18, 3, 1, 0 ]
[]
[]
[ "parameters", "python", "reference" ]
stackoverflow_0000868325_parameters_python_reference.txt
Q: On GAE, how may I show a date according to right client TimeZone? On my Google App Engine application, i'm storing an auto-updated date/time in my model like that : class MyModel(db.Model): date = db.DateTimeProperty(auto_now_add=True) But, that date/time is the local time on server, according to it's time zon...
On GAE, how may I show a date according to right client TimeZone?
On my Google App Engine application, i'm storing an auto-updated date/time in my model like that : class MyModel(db.Model): date = db.DateTimeProperty(auto_now_add=True) But, that date/time is the local time on server, according to it's time zone. So, when I would like to display it on my web page, how may I format...
[ "With respect to the second part of your question:\nPython time() returns UTC regardless of what time zone the server is in. timezone() and tzname() will give you, respectively, the offset to local time on the server and the name of the timezone and the DST timezone as a tuple. GAE uses Python 2.5.x as of the tim...
[ 5, 2, 1 ]
[]
[]
[ "django", "google_app_engine", "python", "timezone" ]
stackoverflow_0000868708_django_google_app_engine_python_timezone.txt
Q: Writing Digg like system in django/python I am tying to write a digg , hackernews , http://collectivesys.com/ like application where users submit something and other users can vote up or down , mark items as favorite ect . I was just wondering if there are some open source implementations django/python that i co...
Writing Digg like system in django/python
I am tying to write a digg , hackernews , http://collectivesys.com/ like application where users submit something and other users can vote up or down , mark items as favorite ect . I was just wondering if there are some open source implementations django/python that i could use as starting point , instead of reinvent...
[ "Check out Pinax and Django Pluggables for some pre-made Django apps to help you out.\n", "reddit is open source, written mostly in python. Apart from the code, there might be some algorithms you may find helpful.\n", "I'd recommend taking a close look at the django-voting project on Google Code.\nThey claim to...
[ 6, 5, 3, 1 ]
[]
[]
[ "digg", "django", "python" ]
stackoverflow_0000867251_digg_django_python.txt
Q: HTML Newbie Question: Colored Background for Characters in Django HttpResponse I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. For simplification, let's assume I can only have shades of green in the backgrou...
HTML Newbie Question: Colored Background for Characters in Django HttpResponse
I would like to generate an HttpResponse that contains a certain string. For each of the characters in the string I have a background color I want to use. For simplification, let's assume I can only have shades of green in the background, and that the "background colors" data represents "level of brightness" in the gr...
[ "It could be something like this:\naString = 'abcd'\nnewString =''\ncolors= [0.0, 1.0, 0.5, 1.0]\nfor i in aString:\n newString = newString + '<span style=\"background-color: rgb(0,%s,0)\">%s</span>'%(colors.pop(0)*255,i)\n\n\n\nresponse = HttpResponse(newString)\n\nuntested\n", "you can use something like thi...
[ 3, 2, 1 ]
[]
[]
[ "colors", "django", "html", "python" ]
stackoverflow_0000868871_colors_django_html_python.txt
Q: Downloading file using post method and python I need a little help getting a tar file to download from a website. The website is set up as a form where you pick the file you want and click submit and then the download windows opens up for you to pick the location. I'm trying to do the same thing in code (so I don'...
Downloading file using post method and python
I need a little help getting a tar file to download from a website. The website is set up as a form where you pick the file you want and click submit and then the download windows opens up for you to pick the location. I'm trying to do the same thing in code (so I don't have to manual pick each file). So far I have got...
[ "Append this:\nmyfile = open('myfile.tar', 'wb')\nshutil.copyfileobj(response.fp, myfile)\nmyfile.close()\n\nresponse.fp is a file-like object that you can read from, just like an open file. shutil.copyfileobj() is a simple function that reads from one file-like object and writes its contents to another.\n" ]
[ 2 ]
[]
[]
[ "python", "urllib2" ]
stackoverflow_0000869679_python_urllib2.txt
Q: Running unittest.main() from a module? I wrote a little function that dynamically defines unittest.TestCase classes (trivial version below). When I moved it out of the same source file into its own module, I can't figure out how to get unittest to discover the new classes. Calling unittest.main() from either file ...
Running unittest.main() from a module?
I wrote a little function that dynamically defines unittest.TestCase classes (trivial version below). When I moved it out of the same source file into its own module, I can't figure out how to get unittest to discover the new classes. Calling unittest.main() from either file doesn't execute any tests. factory.py: impor...
[ "The general idea (what unittest.main does for you) is:\nsuite = unittest.TestLoader().loadTestsFromTestCase(SomeTestCase)\nunittest.TextTestRunner(verbosity=2).run(suite)\n\nas per http://docs.python.org/library/unittest.html?highlight=unittest#module-unittest . Your test cases are hidden in globals() by the test...
[ 9, 8 ]
[]
[]
[ "python", "unit_testing" ]
stackoverflow_0000869519_python_unit_testing.txt
Q: How do I disassemble a Python script? Earlier today, I asked a question about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples. I'd like to know more. How can I disassemble my own Python code? A: Look at the dis module: def myfunc(alist): retu...
How do I disassemble a Python script?
Earlier today, I asked a question about the way Python handles certain kinds of loops. One of the answers contained disassembled versions of my examples. I'd like to know more. How can I disassemble my own Python code?
[ "Look at the dis module:\ndef myfunc(alist):\n return len(alist)\n\n>>> dis.dis(myfunc)\n 2 0 LOAD_GLOBAL 0 (len)\n 3 LOAD_FAST 0 (alist)\n 6 CALL_FUNCTION 1\n 9 RETURN_VALUE\n\n", "Besides using dis as module, you can als...
[ 13, 3, 2 ]
[]
[]
[ "debugging", "python", "reverse_engineering" ]
stackoverflow_0000869586_debugging_python_reverse_engineering.txt
Q: Help translation PYTHON to VB.NET I am coding an application in VB.NET that sends sms. Would you please post PYTHON->VB.NET translation of this code and/or guidelines? Thanks in advance!!! import threading class MessageThread(threading.Thread): def __init__(self,msg,no): threading.Thread.__init__(self...
Help translation PYTHON to VB.NET
I am coding an application in VB.NET that sends sms. Would you please post PYTHON->VB.NET translation of this code and/or guidelines? Thanks in advance!!! import threading class MessageThread(threading.Thread): def __init__(self,msg,no): threading.Thread.__init__(self) self.msg = msg # text messag...
[ "This code creates a thread for every msg/no tuple and calls sendmsg. The first \"for each ... each.start()\" starts the thread (which only calls sendmsg) and the second \"for each ... each.join()\" waits for each thread to complete. Depending on the number of records, this could create a significant number of thre...
[ 1, 0 ]
[]
[]
[ "multithreading", "python", "translation", "vb.net" ]
stackoverflow_0000870116_multithreading_python_translation_vb.net.txt
Q: AuthSub with Text_db in google app engine I am trying to read a spreadsheet from app engine using text_db and authsub. I read http://code.google.com/appengine/articles/gdata.html and got it to work. Then I read http://code.google.com/p/gdata-python-client/wiki/AuthSubWithTextDB and I tried to merge the two in the ...
AuthSub with Text_db in google app engine
I am trying to read a spreadsheet from app engine using text_db and authsub. I read http://code.google.com/appengine/articles/gdata.html and got it to work. Then I read http://code.google.com/p/gdata-python-client/wiki/AuthSubWithTextDB and I tried to merge the two in the file below (step4.py) but when I run it locally...
[ "As always, I figure out the answer only after giving up and asking for help.\nwe need to add two more calls to run_on_appengine (to register the two clients that the text_db client has):\ngdata.alt.appengine.run_on_appengine(client)\ngdata.alt.appengine.run_on_appengine(client._GetDocsClient())\ngdata.alt.appengin...
[ 1 ]
[]
[]
[ "authentication", "gdata_api", "google_app_engine", "python" ]
stackoverflow_0000870192_authentication_gdata_api_google_app_engine_python.txt
Q: How do languages such as Python overcome C's Integral data limits? While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact: In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 dig...
How do languages such as Python overcome C's Integral data limits?
While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact: In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified here. In Python, I can find the factorial of a number ...
[ "It's called Arbitrary Precision Arithmetic. There's more here: http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic\n", "Looking at the Python source code, it seems the long type (at least in pre-Python 3 code) is defined in longintrepr.h like this -\n/* Long integer representation.\n The absolute value...
[ 9, 6, 4, 3, 1 ]
[]
[]
[ "c", "integer", "python", "types" ]
stackoverflow_0000867393_c_integer_python_types.txt
Q: SOAPpy - reserved word in named parameter list I'm using SOAPpy to access a SOAP Webservice. This call to the function findPathwaysByText works just fine: server.findPathwaysByText (query= 'WP619', species = 'Mus musculus') However, this call to the function login does not: server.login (user='amarillion', pass='...
SOAPpy - reserved word in named parameter list
I'm using SOAPpy to access a SOAP Webservice. This call to the function findPathwaysByText works just fine: server.findPathwaysByText (query= 'WP619', species = 'Mus musculus') However, this call to the function login does not: server.login (user='amarillion', pass='*****') Because pass is a reserved word, python won...
[ "You could try:\nd = {'user':'amarillion', 'pass':'*****' }\nserver.login(**d)\n\nThis passes in the given dictionary as though they were keyword arguments (the **)\n", "You can say\nserver.login(user='amarillion', **{'pass': '*****'})\n\nThe double-asterix syntax here applies keyword arguments. Here's a simple ...
[ 5, 1 ]
[]
[]
[ "python", "reserved_words", "soap", "soappy" ]
stackoverflow_0000870455_python_reserved_words_soap_soappy.txt
Q: How the method resolution and invocation works internally in Python? How the methods invocation works in Python? I mean, how the python virtual machine interpret it. It's true that the python method resolution could be slower in Python that in Java. What is late binding? What are the differences on the reflection ...
How the method resolution and invocation works internally in Python?
How the methods invocation works in Python? I mean, how the python virtual machine interpret it. It's true that the python method resolution could be slower in Python that in Java. What is late binding? What are the differences on the reflection mechanism in these two languages? Where to find good resources explaining ...
[ "Method invocation in Python consists of two distinct separable steps. First an attribute lookup is done, then the result of that lookup is invoked. This means that the following two snippets have the same semantics:\nfoo.bar()\n\nmethod = foo.bar\nmethod()\n\nAttribute lookup in Python is a rather complex process...
[ 8, 4, 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0000852308_java_python.txt
Q: How to generate a file with DDL in the engine's SQL dialect in SQLAlchemy? Suppose I have an engine pointing at MySQL database: engine = create_engine('mysql://arthurdent:answer42@localhost/dtdb', echo=True) I can populate dtdb with tables, FKs, etc by: metadata.create_all(engine) Is there an easy way to generat...
How to generate a file with DDL in the engine's SQL dialect in SQLAlchemy?
Suppose I have an engine pointing at MySQL database: engine = create_engine('mysql://arthurdent:answer42@localhost/dtdb', echo=True) I can populate dtdb with tables, FKs, etc by: metadata.create_all(engine) Is there an easy way to generate the SQL file that contains all the DDL statements instead of actually applying...
[ "The quick answer is in the SQLAlchemy 0.8 FAQ.\nIn SQLAlchemy 0.8 you need to do\nengine = create_engine(\n'mssql+pyodbc://./MyDb',\nstrategy='mock',\nexecutor= lambda sql, *multiparams, **params: print (sql.compile(dialect=engine.dialect)))\n\nIn SQLAlchemy 0.9 the syntax is simplified.\nengine = create_engine(\n...
[ 15 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0000870925_python_sqlalchemy.txt
Q: Python: Elegant way of dual/multiple iteration over the same list I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration? jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_i...
Python: Elegant way of dual/multiple iteration over the same list
I've written a bit of code like the following to compare items with other items further on in a list. Is there a more elegant pattern for this sort of dual iteration? jump_item_iter = (j for j in items if some_cond) try: jump_item = jump_item_iter.next() except StopIteration: return for item in items: if j...
[ "As far as I can see any of the existing solutions work on a general one shot, possiboly infinite iterator, all of them seem to require an iterable.\nHeres a solution to that.\ndef batch_by(condition, seq):\n it = iter(seq)\n batch = [it.next()]\n for jump_item in it:\n if condition(jump_item):\n ...
[ 4, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0000867936_iterator_python.txt
Q: "else" considered harmful in Python? In an answer (by S.Lott) to a question about Python's try...else statement: Actually, even on an if-statement, the else: can be abused in truly terrible ways creating bugs that are very hard to find. [...] Think twice about else:. It is generally a problem. Avoid it ex...
"else" considered harmful in Python?
In an answer (by S.Lott) to a question about Python's try...else statement: Actually, even on an if-statement, the else: can be abused in truly terrible ways creating bugs that are very hard to find. [...] Think twice about else:. It is generally a problem. Avoid it except in an if-statement and even then ...
[ "S.Lott has obviously seen some bad code out there. Haven't we all? I do not consider else harmful, though I've seen it used to write bad code. In those cases, all the surrounding code has been bad as well, so why blame poor else?\n", "No it is not harmful, it is necessary.\nThere should always be a catch-all sta...
[ 31, 15, 7, 7, 6, 4, 3, 3, 2, 1, 1, 0, 0 ]
[]
[]
[ "if_statement", "python" ]
stackoverflow_0000865741_if_statement_python.txt
Q: Production ready Python implementations besides CPython? Except for CPython, which other Python implementations are currently usable for production systems? The questions What are the pros and cons of the various Python implementations? I have been trying to wrap my head around the PyPy project. So, fast-foward ...
Production ready Python implementations besides CPython?
Except for CPython, which other Python implementations are currently usable for production systems? The questions What are the pros and cons of the various Python implementations? I have been trying to wrap my head around the PyPy project. So, fast-foward 5-10 years in the future what will PyPy have to offer over CPy...
[ "CPython\nUsed in many, many products and production systems\nJython\nI am aware of production systems and products (a transactional integration engine) based on Jython. In the latter case the product has been on the market since the early 2000's. Jython is a bit stagnant (although it seems to have picked up a bi...
[ 10, 3, 0, 0 ]
[]
[]
[ "cpython", "ironpython", "jython", "pypy", "python" ]
stackoverflow_0000852049_cpython_ironpython_jython_pypy_python.txt
Q: XPath - How can I query for a parent node satisfying an attribute presence condition? I need to query a node to determine if it has a parent node that contains a specified attribute. For instance: <a b="value"> <b/> </a> From b as my focus element, I'd like to execute an XPath query: ..[@b] that would return...
XPath - How can I query for a parent node satisfying an attribute presence condition?
I need to query a node to determine if it has a parent node that contains a specified attribute. For instance: <a b="value"> <b/> </a> From b as my focus element, I'd like to execute an XPath query: ..[@b] that would return element a. The returned element must be the parent node of a, and should not contain any o...
[ "You can't combine the . or .. shorthands with a predicate. Instead, you'll need to use the full parent:: axis. The following should work for you:\nparent::*[@b]\n\nThis will select the parent node (regardless of its local name), IFF it has a \"b\" attribute.\n", "I don't know about the lxml.etree library but ....
[ 4, 1 ]
[]
[]
[ "python", "xml", "xpath" ]
stackoverflow_0000871188_python_xml_xpath.txt
Q: Indentation in a Python GUI As I write code in Python and suddenly feel like adding a new block in front of the code I have already written... the indentation of the complete code is affected... It is a very tedious process to move to each line and change the indentation...is there a way to do auto indent or somet...
Indentation in a Python GUI
As I write code in Python and suddenly feel like adding a new block in front of the code I have already written... the indentation of the complete code is affected... It is a very tedious process to move to each line and change the indentation...is there a way to do auto indent or something? For example: def somefuncti...
[ "I don't know what wacky planets everyone is coming from, but in most editors that don't date back to the stone age, indenting blocks of code typically only requires that a block of text be selected and Tab be pressed. On the flip side, Shift+Tab usually UNdents the block.\nThis is true for Visual Studio, Notepad2...
[ 5, 3, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "indentation", "python", "user_interface" ]
stackoverflow_0000869975_indentation_python_user_interface.txt
Q: Can I segment a document in BeautifulSoup before converting it to text based on my analysis of the document? I have some html files that I want to convert to text. I have played around with BeautifulSoup and made some progress on understanding how to use the instructions and can submit html and get back text. H...
Can I segment a document in BeautifulSoup before converting it to text based on my analysis of the document?
I have some html files that I want to convert to text. I have played around with BeautifulSoup and made some progress on understanding how to use the instructions and can submit html and get back text. However, my files have a lot of text that is formatted using table structures. For example I might have a paragrap...
[ "Man I love this stuff\nAssuming in a naive case that I want to delete all of the tables that have any rows with a column length greater than 3 My answer is \nfor table in soup.findAll('table'):\n rows=[]\n for row in table.findAll('tr'):\n columns=0\n for column in row.findAll('td'):\n ...
[ 0 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0000866772_beautifulsoup_python.txt
Q: Simple List of All Java Standard Classes and Methods? I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. When I encounter a word or a set of two words separated by a dot ("word.word")...
Simple List of All Java Standard Classes and Methods?
I'm building a very simple Java parser, to look for some specific usage models. This is in no way lex/yacc or any other form of interpreter/compiler for puposes of running the code. When I encounter a word or a set of two words separated by a dot ("word.word"), I would like to know if that's a standard Java class (and...
[ "What's wrong with the javadoc? The index lists all classes, methods, and static variables. You can probably grep for parenthesis.\n", "To get all classes and methods you can look at the index on\nhttp://java.sun.com/javase/6/docs/api/index-files/index-1.html\nThis will be 10's of thousands classes and method whi...
[ 1, 1, 1, 1, 1, 0 ]
[]
[]
[ "java", "parsing", "python" ]
stackoverflow_0000871812_java_parsing_python.txt
Q: Google App Engine--Dynamically created templates I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accompli...
Google App Engine--Dynamically created templates
I'm trying to build an a simple CRUD admin section of my application. Basically, for a given Model, I want to have a template loop through the model's attributes into a simple table (once I do this, I can actually implement the CRUD part). A possible way to accomplish this is to dynamically generate a template with all...
[ "I saw this open source project a while back: \nhttp://code.google.com/p/gae-django-dbtemplates/\nUsing a template to generate a template should be fine. Just render the template to a string. Here some code i use so i can stick some xml into memecache\npath = os.path.join(os.path.dirname(__file__), 'line_chart.xm...
[ 1, 1, 0 ]
[]
[]
[ "django_templates", "google_app_engine", "python", "templates" ]
stackoverflow_0000744828_django_templates_google_app_engine_python_templates.txt
Q: Creating a new terminal/shell window to simply display text I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython i...
Creating a new terminal/shell window to simply display text
I want to pipe [edit: real-time text] the output of several subprocesses (sometimes chained, sometimes parallel) to a single terminal/tty window that is not the active python shell (be it an IDE, command-line, or a running script using tkinter). IPython is not an option. I need something that comes with the standard in...
[ "A good solution in Unix would be named pipes. I know you asked about Windows, but there might be a similar approach in Windows, or this might be helpful for someone else.\non terminal 1:\nmkfifo /tmp/display_data\nmyapp >> /tmp/display_data\n\non terminal 2 (bash):\ntail -f /tmp/display_data\n\nEdit: changed term...
[ 2, 0, 0 ]
[]
[]
[ "python", "shell" ]
stackoverflow_0000866737_python_shell.txt
Q: Using exec() with recursive functions I want to execute some Python code, typed at runtime, so I get the string and call exec(pp, globals(), locals()) where pp is the string. It works fine, except for recursive calls, e. g., for example, this code is OK: def horse(): robot.step() robot.step() robot.t...
Using exec() with recursive functions
I want to execute some Python code, typed at runtime, so I get the string and call exec(pp, globals(), locals()) where pp is the string. It works fine, except for recursive calls, e. g., for example, this code is OK: def horse(): robot.step() robot.step() robot.turn(-1) robot.step() while True: h...
[ "This surprised me too at first, and seems to be an odd corner case where exec is acting neither quite like a top-level definition, or a definition within an enclosing function. It looks like what is happening is that the function definition is being executed in the locals() dict you pass in. However, the defined...
[ 6, 5, 3, 0 ]
[]
[]
[ "exec", "python", "recursion" ]
stackoverflow_0000871887_exec_python_recursion.txt
Q: Sorting a list of objects by attribute I am trying to sort a list of objects in python, however this code will not work: import datetime class Day: def __init__(self, date, text): self.date = date self.text = text def __cmp__(self, other): return cmp(self.date, other.date) mylist...
Sorting a list of objects by attribute
I am trying to sort a list of objects in python, however this code will not work: import datetime class Day: def __init__(self, date, text): self.date = date self.text = text def __cmp__(self, other): return cmp(self.date, other.date) mylist = [Day(datetime.date(2009, 01, 02), "Jan 2"...
[ "mylist.sort() returns nothing, it sorts the list in place. Change it to \nmylist.sort()\nprint mylist\n\nto see the correct result. \nSee http://docs.python.org/library/stdtypes.html#mutable-sequence-types note 7.\n\nThe sort() and reverse() methods\n modify the list in place for economy\n of space when sorting ...
[ 5, 2 ]
[]
[]
[ "python", "python_2.x" ]
stackoverflow_0000872181_python_python_2.x.txt
Q: numpy linear algebra basic help This is what I need to do- I have this equation- Ax = y Where A is a rational m*n matrix (m<=n), and x and y are vectors of the right size. I know A and y, I don't know what x is equal to. I also know that there is no x where Ax equals exactly y. I want to find the vector x' such th...
numpy linear algebra basic help
This is what I need to do- I have this equation- Ax = y Where A is a rational m*n matrix (m<=n), and x and y are vectors of the right size. I know A and y, I don't know what x is equal to. I also know that there is no x where Ax equals exactly y. I want to find the vector x' such that Ax' is as close as possible to y. ...
[ "The updated documentation may be a bit more helpful... looks like you want\nnumpy.linalg.lstsq(A, y)\n\n", "SVD is for the case of m < n, because you don't really have enough degrees of freedom.\nThe docs for lstsq don't look very helpful. I believe that's least square fitting, for the case where m > n.\nIf m <...
[ 2, 0, 0 ]
[]
[]
[ "linear_algebra", "numpy", "python", "scipy", "svd" ]
stackoverflow_0000872376_linear_algebra_numpy_python_scipy_svd.txt
Q: What's wrong with this Python code? I'm very new so just learning, so go easy please! start = int(input('How much did you start with?:' )) if start < 0: print("That's impossible! Try again.") print(start = int(input('How much did you start with:' ))) if start >= 0: print(inorout = raw_input('Cool! No...
What's wrong with this Python code?
I'm very new so just learning, so go easy please! start = int(input('How much did you start with?:' )) if start < 0: print("That's impossible! Try again.") print(start = int(input('How much did you start with:' ))) if start >= 0: print(inorout = raw_input('Cool! Now have you put money in or taken it out?:...
[ "\nYou can't assign to variables in expressions in Python, like in C: print (start=int(input('blah'))) isn't correct. Do the assignment first in a separate statement.\nThe first line musn't be indented, but that might just be a copy and paste error.\nThe word in is a reserved word so you can't use it for variable n...
[ 7, 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000872119_python.txt
Q: Most Efficient Way to Find Whether a Large List Contains a Specific String (Python) I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list). What would be the most eff...
Most Efficient Way to Find Whether a Large List Contains a Specific String (Python)
I have a file containing roughly all the words in English (~60k words, ~500k characters). I want to test whether a certain word I receive as input is "in English" (i.e. if this exact word is in the list). What would be the most efficient way to do this in Python? The trivial solution is to load the file into a list and...
[ "The python Set is what you should try.\n\nA set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. \n\n", "A Trie stru...
[ 24, 4, 4, 2, 2, 2, 2, 1, 1 ]
[]
[]
[ "python", "string" ]
stackoverflow_0000872290_python_string.txt
Q: Python program using os.pipe and os.fork() issue I've recently needed to write a script that performs an os.fork() to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with os.pipe(). The child closes the 'r' end of the pipe and the...
Python program using os.pipe and os.fork() issue
I've recently needed to write a script that performs an os.fork() to split into two processes. The child process becomes a server process and passes data back to the parent process using a pipe created with os.pipe(). The child closes the 'r' end of the pipe and the parent closes the 'w' end of the pipe, as usual. I co...
[ "Are you using read() without specifying a size, or treating the pipe as an iterator (for line in f)? If so, that's probably the source of your problem - read() is defined to read until the end of the file before returning, rather than just read what is available for reading. That will mean it will block until th...
[ 13, 6, 5 ]
[ "The \"parent\" vs. \"child\" part of fork in a Python application is silly. It's a legacy from 16-bit unix days. It's an affectation from a day when fork/exec and exec were Important Things to make the most of a tiny little processor.\nBreak your Python code into two separate parts: parent and child.\nThe parent...
[ -10 ]
[ "fork", "pipe", "python" ]
stackoverflow_0000871447_fork_pipe_python.txt
Q: Some help with some Python code Can anyone tell me why num_chars and num_rows have to be the same? from ctypes import * num_chars = 8 num_rows = 8 num_cols = 6 buffer = create_string_buffer (num_chars*num_rows*num_cols+num_chars) for char in range(num_chars): for row in range(num_rows): ...
Some help with some Python code
Can anyone tell me why num_chars and num_rows have to be the same? from ctypes import * num_chars = 8 num_rows = 8 num_cols = 6 buffer = create_string_buffer (num_chars*num_rows*num_cols+num_chars) for char in range(num_chars): for row in range(num_rows): for col in range(num_cols): ...
[ "You said you are using ctypes because you want mutable char buffer for this. But you can get the output you want from list comprehension\nnum_chars = 5\nnum_rows = 8\nempty = ['.' * num_chars]\nfull = ['*' * num_chars]\nprint '\\n'.join(\n '|'.join(empty * (i + 1) + (num_rows - i - 1) * full)\n for i in xran...
[ 5, 1 ]
[]
[]
[ "ctypes", "python" ]
stackoverflow_0000872566_ctypes_python.txt
Q: Python generates an IO error while interleaving open/close/readline/write on the same file I'm learning Python-this gives me an IO error- f = open('money.txt') while True: currentmoney = float(f.readline()) print(currentmoney, end='') if currentmoney >= 0: howmuch = (float(input('How much did y...
Python generates an IO error while interleaving open/close/readline/write on the same file
I'm learning Python-this gives me an IO error- f = open('money.txt') while True: currentmoney = float(f.readline()) print(currentmoney, end='') if currentmoney >= 0: howmuch = (float(input('How much did you put in or take out?:'))) now = currentmoney + howmuch print(now) str...
[ "The while True is going to loop forever unless you break it with break.\nThe I/O error is probably because when you have run through the loop once the last thing you do is f.close(), which closes the file. When execution continues with the loop in the line currentmoney = float(f.readline()): f will be a closed fil...
[ 3, 2, 0, 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0000872680_python_python_3.x.txt
Q: Pythonic Way to Initialize (Complex) Static Data Members I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this: def generate_data(): ... do some analysis and return complex object e.g. list ... class Coo: ...
Pythonic Way to Initialize (Complex) Static Data Members
I have a class with a complex data member that I want to keep "static". I want to initialize it once, using a function. How Pythonic is something like this: def generate_data(): ... do some analysis and return complex object e.g. list ... class Coo: data_member = generate_data() ... rest of class code ... ...
[ "You're right on all counts. data_member will be created once, and will be available to all instances of coo. If any instance modifies it, that modification will be visible to all other instances.\nHere's an example that demonstrates all this, with its output shown at the end:\ndef generate_data():\n print \"G...
[ 18, 13, 6 ]
[]
[]
[ "class", "python" ]
stackoverflow_0000872973_class_python.txt
Q: pycurl: RETURNTRANSFER option doesn't exist I'm using pycurl to access a JSON web API, but when I try to use the following: ocurl.setopt(pycurl.URL, gaurl) # host + endpoint ocurl.setopt(pycurl.RETURNTRANSFER, 1) ocurl.setopt(pycurl.HTTPHEADER, gaheader) # Send extra headers ocurl.setopt(pycurl.CUSTOMREQUES...
pycurl: RETURNTRANSFER option doesn't exist
I'm using pycurl to access a JSON web API, but when I try to use the following: ocurl.setopt(pycurl.URL, gaurl) # host + endpoint ocurl.setopt(pycurl.RETURNTRANSFER, 1) ocurl.setopt(pycurl.HTTPHEADER, gaheader) # Send extra headers ocurl.setopt(pycurl.CUSTOMREQUEST, "POST") # HTTP POST req ocurl.setopt(pycurl.CO...
[ "The manual shows the usage being something like this:\n>>> import pycurl\n>>> import StringIO\n>>> b = StringIO.StringIO()\n>>> conn = pycurl.Curl()\n>>> conn.setopt(pycurl.URL, 'http://www.example.org')\n>>> conn.setopt(pycurl.WRITEFUNCTION, b.write)\n>>> conn.perform()\n>>> print b.getvalue()\n<HTML>\n<HEAD>\n ...
[ 7, 5, 0 ]
[]
[]
[ "attributeerror", "curl", "libcurl", "pycurl", "python" ]
stackoverflow_0000872844_attributeerror_curl_libcurl_pycurl_python.txt
Q: Converting to safe unicode in python I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error. Incorrect string value: '\xEF\xBF\xBDs m...' My guess is that the string is no...
Converting to safe unicode in python
I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error. Incorrect string value: '\xEF\xBF\xBDs m...' My guess is that the string is not being properly converted to unicode? He...
[ "What is the original encoding? I'm assuming \"cp1252\", from pixelbeat's answer. In that case, you can do\n>>> orig # Byte string, encoded in cp1252\n'Fabulous home on one of Decatur\\x92s most' \n\n>>> uni = orig.decode('cp1252')\n>>> uni # Unicode string\nu'Fabulous home on one of Decatur\\u2019s most'\n\n>>> s ...
[ 5, 3, 1 ]
[]
[]
[ "django", "python", "unicode" ]
stackoverflow_0000873419_django_python_unicode.txt
Q: How to install cogen python coroutine framework on Mac OS X I did sudo easy_install cogen and got : Searching for cogen Best match: cogen 0.2.1 Processing cogen-0.2.1-py2.5.egg cogen 0.2.1 is already the active version in easy-install.pth Using /Library/Python/2.5/site-packages/cogen-0.2.1-py2.5.egg Processing...
How to install cogen python coroutine framework on Mac OS X
I did sudo easy_install cogen and got : Searching for cogen Best match: cogen 0.2.1 Processing cogen-0.2.1-py2.5.egg cogen 0.2.1 is already the active version in easy-install.pth Using /Library/Python/2.5/site-packages/cogen-0.2.1-py2.5.egg Processing dependencies for cogen Searching for py-kqueue>=2.0 Reading http...
[ "It seems to be some problem with setuptools -- the dependencies are compiled succesfully but not installed. FWIW it works for me (OSX 10.5.6, MacPython 2.5). \nI would try reinstalling setuptools, and if that fails downloading and \"python setup.py install\"ing cogen and py-kqueue manually. \n", "Try downloading...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0000873577_python.txt
Q: port python code to javascript indices[i:] = indices[i+1:] + indices[i:i+1] Hope someone helps. A: I'm fairly new to Python but if I understand the code correctly, it reconstructs a list from a given offset into every item following offset+1 and the item at the offset. Running it seems to confirm this: >>> indi...
port python code to javascript
indices[i:] = indices[i+1:] + indices[i:i+1] Hope someone helps.
[ "I'm fairly new to Python but if I understand the code correctly, it reconstructs a list from a given offset into every item following offset+1 and the item at the offset.\nRunning it seems to confirm this:\n>>> indices = ['one','two','three','four','five','six']\n>>> i = 2\n>>> indices[i:] = indices[i+1:] + indice...
[ 6, 1 ]
[]
[]
[ "javascript", "porting", "python" ]
stackoverflow_0000872366_javascript_porting_python.txt
Q: How would one make Python objects persistent in a web-app? I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's ...
How would one make Python objects persistent in a web-app?
I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with...
[ "Be cautious of premature optimization.\nAddition: The \"Python backend runs an algorithm whose state...\" is the session in the web framework. That's it. Let the Django framework maintain session state in cache. Period. \n\"The algorithm's per-user state undergoes many small changes as a user works with the ap...
[ 8, 4, 2, 2, 2, 1 ]
[]
[]
[ "concurrency", "persistence", "python", "web_applications" ]
stackoverflow_0000330367_concurrency_persistence_python_web_applications.txt
Q: mod_php vs mod_python Why mod_python is oop but mod_php is not ? Example :We go to www.example.com/dir1/dir2 if you use mod_python apache opens www/dir1.py and calls dir2 method but if you use php module apache opens www/dir1/dir2/index.php A: Let's talk about mod_python vs. mod_php. Since the Python language is...
mod_php vs mod_python
Why mod_python is oop but mod_php is not ? Example :We go to www.example.com/dir1/dir2 if you use mod_python apache opens www/dir1.py and calls dir2 method but if you use php module apache opens www/dir1/dir2/index.php
[ "Let's talk about mod_python vs. mod_php.\nSince the Python language is NOT specifically designed for serving web pages, mod_python must do some additional work. \nSince the PHP language IS specifically designed to serve web pages, mod_php simply starts a named PHP module.\nIn the case of mod_python (different fro...
[ 8, 4, 4, 0 ]
[ "Perhaps I misunderstand your question, but both Python and PHP support both procedural and object-oriented programming. (Though one could argue that Python's support for OO is the stronger of the two.)\n", "See Class and Objects in PHP 5\n" ]
[ -1, -1 ]
[ "mod_python", "php", "python" ]
stackoverflow_0000872695_mod_python_php_python.txt