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: Pagination of Date-Based Generic Views in Django I have a pretty simple question. I want to make some date-based generic views on a Django site, but I also want to paginate them. According to the documentation the object_list view has page and paginate_by arguments, but the archive_month view does not. What's the ...
Pagination of Date-Based Generic Views in Django
I have a pretty simple question. I want to make some date-based generic views on a Django site, but I also want to paginate them. According to the documentation the object_list view has page and paginate_by arguments, but the archive_month view does not. What's the "right" way to do it?
[ "I created a template tag to do template-based pagination on collections passed to the templates that aren't already paginated. Copy the following code to an app/templatetags/pagify.py file.\nfrom django.template import Library, Node, Variable\nfrom django.core.paginator import Paginator\nimport settings\n\nregist...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "django", "pagination", "python" ]
stackoverflow_0000669903_django_pagination_python.txt
Q: R or Python for file manipulation I have 4 reasonably complex r scripts that are used to manipulate csv and xml files. These were created by another department where they work exclusively in r. My understanding is that while r is very fast when dealing with data, it's not really optimised for file manipulation....
R or Python for file manipulation
I have 4 reasonably complex r scripts that are used to manipulate csv and xml files. These were created by another department where they work exclusively in r. My understanding is that while r is very fast when dealing with data, it's not really optimised for file manipulation. Can I expect to get significant speed...
[ "I write in both R and Python regularly. I find Python modules for writing, reading and parsing information easier to use, maintain and update. Little niceties like the way python lets you deal with lists of items over R's indexing make things much easier to read.\nI highly doubt you will gain any significant spe...
[ 11, 2, 1, 1, 0, 0 ]
[]
[]
[ "file", "performance", "python", "r" ]
stackoverflow_0002770030_file_performance_python_r.txt
Q: Python: Why do some packages get installed as eggs and some as "egg folders"? I maintain a few Python packages. I have a very similar setup.py file for each of them. However, when doing setup.py install, one of my packages gets installed as an egg, while the others get installed as "egg folders", i.e. folders with...
Python: Why do some packages get installed as eggs and some as "egg folders"?
I maintain a few Python packages. I have a very similar setup.py file for each of them. However, when doing setup.py install, one of my packages gets installed as an egg, while the others get installed as "egg folders", i.e. folders with an extension of "egg". What is the difference between them that causes this differ...
[ "The Internal Structure of Python Eggs, Zip Support Metadata :\n\nIf zip-safe exists, it means that the project will work properly when installed as an .egg zipfile, and conversely the existence of not-zip-safe means the project should not be installed as an .egg file [ie. as an .egg directory]. The zip_safe option...
[ 28, 5 ]
[]
[]
[ "egg", "packaging", "python", "setuptools" ]
stackoverflow_0002798451_egg_packaging_python_setuptools.txt
Q: How do I pass a Python Variable to Bash? How would I pass a Python variable to the Bash shell? It should work like this: foo="./RetVar.py 42" Replace the double-quotes with `s I have tried printing and sys.exiting the result, but to no avail. How would I accomplish my goal? A: foo="$(scriptthatprintssomething)" ...
How do I pass a Python Variable to Bash?
How would I pass a Python variable to the Bash shell? It should work like this: foo="./RetVar.py 42" Replace the double-quotes with `s I have tried printing and sys.exiting the result, but to no avail. How would I accomplish my goal?
[ "foo=\"$(scriptthatprintssomething)\"\n\nThat's it. print. Or sys.stdout.write(). Or the like. If the script isn't executable then you'll need to specify the interpreter explicitly.\nfoo=\"$(python scriptthatprintssomething.py)\"\n\n", "In bash both ``cmd\\ and $(cmd) will be replaced by the output of the command...
[ 9, 1, 0 ]
[]
[]
[ "bash", "linux", "python", "unix" ]
stackoverflow_0002796932_bash_linux_python_unix.txt
Q: Starting an http request, but dropping out if no response after a certain time I'm trying to write a python script that does the following from within a minutely cronjob: tries to execute a url after 10 seconds if there is no response yet, abandon the response and immediately issue a command via os.system to rest...
Starting an http request, but dropping out if no response after a certain time
I'm trying to write a python script that does the following from within a minutely cronjob: tries to execute a url after 10 seconds if there is no response yet, abandon the response and immediately issue a command via os.system to restart the webserver. The problem is that when my server crashes, it doesn't return a ...
[ "From Python 2.6 on you can use the following, provide the timeout in seconds in the call to urlopen:\nurllib2.urlopen(url[, data][, timeout])\n\nThis sets the timeout only for this request, not globally like with socket.settimeout. But for older versions of Python that is probably your only option.\n", "Use set...
[ 3, 2, 2 ]
[]
[]
[ "benchmarking", "python" ]
stackoverflow_0002798264_benchmarking_python.txt
Q: How to enable i18n from within setup_app in websetup.py ? (formatted resend) From within the setup_app function (websetup.py) of a pylons i18n application, which is making use of a db, I was trying to initiate multilingual content to be inserted into the db. To do so the idea was something like: #necessary imports...
How to enable i18n from within setup_app in websetup.py ? (formatted resend)
From within the setup_app function (websetup.py) of a pylons i18n application, which is making use of a db, I was trying to initiate multilingual content to be inserted into the db. To do so the idea was something like: #necessary imports here def setup_app(command, conf, vars): .... for lang in langs: ...
[ "Apologies, I'm not familiar with i18n together with Pylons... \nThat said, you need to track down what 'path' is, and what its relative to. The error is because path is expected to be a string, but instead is set to None... causing the exception because the code is attempting a string operation 'path.endswith()' ...
[ 1 ]
[]
[]
[ "internationalization", "pylons", "python" ]
stackoverflow_0002798517_internationalization_pylons_python.txt
Q: cd Terminal at a given directory after running a Python script? I'm working on a simple Python script that can use subprocess and/or os to execute some commands, which is working fine. However, when the script exits I'd like to cd the actual Terminal (in this case OS X) so on exit, the new files are ready to use i...
cd Terminal at a given directory after running a Python script?
I'm working on a simple Python script that can use subprocess and/or os to execute some commands, which is working fine. However, when the script exits I'd like to cd the actual Terminal (in this case OS X) so on exit, the new files are ready to use in the directory where the have been created. All the following (subpr...
[ "Sadly, no. Processes are not allowed to change the environment of their parent process, and in this case your Python script is a child process of the shell. You could \"fake\" it by having your Python process set up a new shell - call subprocess to open a shell process and present it to the user, inheriting the ...
[ 10, 4, 1 ]
[]
[]
[ "bash", "directory", "python", "shell", "terminal" ]
stackoverflow_0002799256_bash_directory_python_shell_terminal.txt
Q: Why does py2exe remove `help` and `license`? I packaged my Python app with py2exe. My app is a wxPython GUI, in which there is an interactive Python shell. I noticed that I can't do help(whatever) in the shell. I investigated a bit and discovered that after the py2exe process, 3 items were missing from __builtin__...
Why does py2exe remove `help` and `license`?
I packaged my Python app with py2exe. My app is a wxPython GUI, in which there is an interactive Python shell. I noticed that I can't do help(whatever) in the shell. I investigated a bit and discovered that after the py2exe process, 3 items were missing from __builtin__. These are help, license, and another one I haven...
[ "Reason: These are added by the site module. I believe that py2exe doesn't package that.\nFix: Either explicitly import site or reimplement help (trivial).\nSee also: http://docs.python.org/library/constants.html#constants-added-by-the-site-module\n" ]
[ 2 ]
[]
[]
[ "packaging", "py2exe", "python" ]
stackoverflow_0002799473_packaging_py2exe_python.txt
Q: How can I dispatch Firefox or Google Chrome with Python? How can I do this with Firefox or Google Chrome? ie = win32com.client.Dispatch('InternetExplorer.Application') ie.visible = 1 ie.navigate('http://google.com') Is there a way to do it? ps: I need to use the ReadyState with it... for example while (ie.ReadySt...
How can I dispatch Firefox or Google Chrome with Python?
How can I do this with Firefox or Google Chrome? ie = win32com.client.Dispatch('InternetExplorer.Application') ie.visible = 1 ie.navigate('http://google.com') Is there a way to do it? ps: I need to use the ReadyState with it... for example while (ie.ReadyState != 4):, or in other words, I need some command that wait u...
[ "Firefox does not expose a COM object; this is not possible. (AFAIK)\nYou can use the webbrowser module to open a URL in the user's default browser.\n", "Have a look at the webbrowser module in the Python standard library.\n" ]
[ 3, 1 ]
[]
[]
[ "firefox", "python", "windows" ]
stackoverflow_0002799535_firefox_python_windows.txt
Q: Difference in regex between Python and Rubular? In Rubular, I have created a regular expression: (Prerequisite|Recommended): (\w|-| )* It matches the bolded: Recommended: good comfort level with computers and some of the arts. Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor...
Difference in regex between Python and Rubular?
In Rubular, I have created a regular expression: (Prerequisite|Recommended): (\w|-| )* It matches the bolded: Recommended: good comfort level with computers and some of the arts. Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degr...
[ "You want to use re.search() because it scans the string. You don't want re.match() because it tries to apply the pattern at the start of the string.\n>>> import re\n>>> s = \"\"\"Summer. 2 credits. Prerequisite: pre-freshman standing or permission of instructor. Credit may not be applied toward engineering degree....
[ 2 ]
[]
[]
[ "python", "regex", "rubular" ]
stackoverflow_0002799418_python_regex_rubular.txt
Q: Django admin page dropdowns I am building a high school team application using Django. Here is my working models file: class Directory(models.Model): school = models.CharField(max_length=60) website = models.URLField() district = models.SmallIntegerField() conference = models.ForeignKey(Conference)...
Django admin page dropdowns
I am building a high school team application using Django. Here is my working models file: class Directory(models.Model): school = models.CharField(max_length=60) website = models.URLField() district = models.SmallIntegerField() conference = models.ForeignKey(Conference) class Conference(models.Model): ...
[ "Try this:\nclass Conference(models.Model):\n conference_name = models.CharField(max_length=50)\n url = models.URLField()\n\n def __unicode__(self):\n return self.conference_name\n\n class Meta:\n ordering = ['conference_name']\n\nThis will say to the framework how to convert Conference in...
[ 0 ]
[]
[]
[ "admin", "django", "drop_down_menu", "python" ]
stackoverflow_0002799553_admin_django_drop_down_menu_python.txt
Q: Named semaphores in Python? I have a script in python which uses a resource which can not be used by more than a certain amount of concurrent scripts running. Classically, this would be solved by a named semaphores but I can not find those in the documentation of the multiprocessing module or threading . Am I miss...
Named semaphores in Python?
I have a script in python which uses a resource which can not be used by more than a certain amount of concurrent scripts running. Classically, this would be solved by a named semaphores but I can not find those in the documentation of the multiprocessing module or threading . Am I missing something or are named semaph...
[ "I suggest a third party extension like these, ideally the posix_ipc one -- see in particular the sempahore section in the docs.\nThese modules are mostly about exposing the \"system V IPC\" (including semaphores) in a unixy way, but at least one of them (posix_ipc specifically) is claimed to work with Cygwin on Wi...
[ 4, 0 ]
[]
[]
[ "cross_process", "multithreading", "python", "semaphore" ]
stackoverflow_0002798727_cross_process_multithreading_python_semaphore.txt
Q: Google Appengine: Java or Python Possible Duplicate: Choosing Java vs Python on Google App Engine We are going to use Google Appengine platform for our next big web project.But we are not sure which flavour to use: Java or Python. Could you please, advise on cons and pros of each approach? Which is the best way...
Google Appengine: Java or Python
Possible Duplicate: Choosing Java vs Python on Google App Engine We are going to use Google Appengine platform for our next big web project.But we are not sure which flavour to use: Java or Python. Could you please, advise on cons and pros of each approach? Which is the best way in order to build more scalable and ...
[ "I gave the accepted answer to the question a comment claims is \"very similar\" -- but that was nearly a year ago. I'm still biased the same way (still expert on Python, rusty in Java), but in the intervening year I would say the Java runtime has just about caught up to the Python one -- or, if not quite that yet...
[ 11, 5 ]
[]
[]
[ "google_app_engine", "java", "python" ]
stackoverflow_0002799811_google_app_engine_java_python.txt
Q: Putting a thread to sleep until event X occurs I'm writing to many files in a threaded app and I'm creating one handler per file. I have HandlerFactory class that manages the distribution of these handlers. What I'd like to do is that thread A requests and gets foo.txt's file handle from the HandlerFactory class t...
Putting a thread to sleep until event X occurs
I'm writing to many files in a threaded app and I'm creating one handler per file. I have HandlerFactory class that manages the distribution of these handlers. What I'd like to do is that thread A requests and gets foo.txt's file handle from the HandlerFactory class thread B requests foo.txt's file handler handler clas...
[ "What you're looking for is known as a condition variable.\nCondition Variables\nHere is the Python 2 library reference.\nFor Python 3 it can be found here\n", "Looks like you want a threading.Semaphore associated with each handler (other synchronization objects like Events and Conditions are also possible, but ...
[ 6, 2, 0 ]
[]
[]
[ "concurrency", "locking", "multithreading", "python" ]
stackoverflow_0002800069_concurrency_locking_multithreading_python.txt
Q: In python, changing MySQL query based on function variables I'd like to be able to add a restriction to the query if user_id != None ... for example: "AND user_id = 5" but I am not sure how to add this into the below function? Thank you. def get(id, user_id=None): query = """SELECT * FROM USE...
In python, changing MySQL query based on function variables
I'd like to be able to add a restriction to the query if user_id != None ... for example: "AND user_id = 5" but I am not sure how to add this into the below function? Thank you. def get(id, user_id=None): query = """SELECT * FROM USERS WHERE text LIKE %s AND id ...
[ "def get(id, user_id=None):\n\n query = \"\"\"SELECT *\n FROM USERS\n WHERE text LIKE %s AND\n id = %s\n \"\"\"\n values = [search_text, id]\n\n if user_id is not None:\n query += ' AND user_id = %s'\n values.append(user_id)\n\n re...
[ 4, 2, 1 ]
[]
[]
[ "function", "mysql", "python" ]
stackoverflow_0002800085_function_mysql_python.txt
Q: How can I do such a typical unittest? This is a simple structure in my project: MyAPP--- note--- __init__.py views.py urls.py test.py models.py auth-- ... template--- auth--- ...
How can I do such a typical unittest?
This is a simple structure in my project: MyAPP--- note--- __init__.py views.py urls.py test.py models.py auth-- ... template--- auth--- login.html ...
[ "Just login a user for each test. The best way to do this is to use a setUp() method that creates a client, creates a user, and then logs user in. Also use a tearDown() method that does the reverse (logs out user and deletes user).\nThe methods setUp() and tearDown() are run automatically for each test in the set o...
[ 6 ]
[]
[]
[ "django", "python", "testcase" ]
stackoverflow_0002800179_django_python_testcase.txt
Q: use/run python's 2to3 as or like a unittest I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(functions, methods...) as would be normal for a unittest. It does not need to be a unittest and I do...
use/run python's 2to3 as or like a unittest
I have used the 2to3 utility to convert code from the command line. What I would like to do is run it basically as a unittest. Even if it tests the file rather than parts(functions, methods...) as would be normal for a unittest. It does not need to be a unittest and I don't what to automatically convert the files I jus...
[ "Simply use the -3 option with python2.6+ to be informed of Python3 compliance.\n", "If you are trying to verify the code will work in Python 3.x, I would suggest a script that copies the source files to a new directory, runs 2to3 on them, then copies the unit tests to the directory and runs them.\nThis may seem ...
[ 2, 1 ]
[]
[]
[ "python", "python_2to3", "unit_testing" ]
stackoverflow_0002800231_python_python_2to3_unit_testing.txt
Q: UnicodeEncodeError while writing data to an xml file My aim is to write an XML file with few tags whose values are in the regional language. I'm using Python to do this and using IDLE (Pythong GUI) for programming. While I try to write the words in an xmls file it gives the following error: UnicodeEncodeError: 'a...
UnicodeEncodeError while writing data to an xml file
My aim is to write an XML file with few tags whose values are in the regional language. I'm using Python to do this and using IDLE (Pythong GUI) for programming. While I try to write the words in an xmls file it gives the following error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: o...
[ "You should .decode your incoming cp1252 to get Unicode strings, and .encode them in utf-8 (by far the preferred encoding for XML) at the time you write, i.e.\nf.write(unicodedata.encode('utf-8'))\n\nwhere unicodedata is obtained by .decode('cp1252') on the incoming bytestrings.\nIt's possible to put lipstick on it...
[ 6 ]
[]
[]
[ "encoding", "python", "xml" ]
stackoverflow_0002800383_encoding_python_xml.txt
Q: Multi-variate regression using NumPy in Python? Is it possible to perform multi-variate regression in Python using NumPy? The documentation here suggests that it is, but I cannot find any more details on the topic. A: Yes, download this ( http://www.scipy.org/Cookbook/OLS?action=AttachFile&do=get&target=ols.0.2....
Multi-variate regression using NumPy in Python?
Is it possible to perform multi-variate regression in Python using NumPy? The documentation here suggests that it is, but I cannot find any more details on the topic.
[ "Yes, download this ( http://www.scipy.org/Cookbook/OLS?action=AttachFile&do=get&target=ols.0.2.py ) from http://www.scipy.org/Cookbook/OLS\nOr you can install R and a python-R link. R can do anything.\n", "The webpage that you linked to mentions numpy.linalg.lstsq to find the vector x\nwhich minimizes |b - Ax|. ...
[ 3, 2, 1 ]
[]
[]
[ "python", "regression" ]
stackoverflow_0002799491_python_regression.txt
Q: It's possible make an OCR in Python to check words in opened applications? I want to automate firefox in some web page and I don't have a way to "know" if the page already load completely or if it still loading... I was thinking about making an OCR to check the status bar... it's difficult ? For example, when the...
It's possible make an OCR in Python to check words
in opened applications? I want to automate firefox in some web page and I don't have a way to "know" if the page already load completely or if it still loading... I was thinking about making an OCR to check the status bar... it's difficult ? For example, when the word DONE appears at the status bar, the program contin...
[ "OCR is a terrible, terrible choice for something like this. Use OCR when you are encountering images with unknown text. If you are trying to automate Firefox, there's a billion better ways of doing so. Check out something like AutoIt or any one of a hundred automation tools for Windows. Or write a custom Firefox e...
[ 4, 1 ]
[]
[]
[ "firefox", "ocr", "python", "windows" ]
stackoverflow_0002800119_firefox_ocr_python_windows.txt
Q: video player with qt phonon (using python) I am working on Windows xp and am trying to get a simple video player running. I am trying to use Phonon::VideoPlayer module for this. I am connecting the signal as connect(self.player,SIGNAL("finished()"),self.player.deleteLater) and then , when the Play button is pre...
video player with qt phonon (using python)
I am working on Windows xp and am trying to get a simple video player running. I am trying to use Phonon::VideoPlayer module for this. I am connecting the signal as connect(self.player,SIGNAL("finished()"),self.player.deleteLater) and then , when the Play button is pressed, it makes the following call: self.player.p...
[ "Try writing\nself.player.play(Phonon.MediaSource(\"C:\\\\vid.mp4\"))\n\nto escape the \\\n", "Phonon::MediaSource mediaSource= Phonon::MediaSource(\"C:\\\\vid.mp4\");\n\nTry creating media sources like this and also other Phonon objects..\n" ]
[ 0, 0 ]
[]
[]
[ "c++", "phonon", "pyqt", "python", "qt" ]
stackoverflow_0002454560_c++_phonon_pyqt_python_qt.txt
Q: PyQt: Get the position of QGraphicsWidgets in a QGraphicsGridLayout I have a fairly simple PyQt application in which I'm placing instances of a QGraphicsWidget in a QGraphicsGridLayout and want to connect the widgets with lines drawn with a QGraphicsPath. Unfortunately, no matter what I try, I always get (0, 0) ba...
PyQt: Get the position of QGraphicsWidgets in a QGraphicsGridLayout
I have a fairly simple PyQt application in which I'm placing instances of a QGraphicsWidget in a QGraphicsGridLayout and want to connect the widgets with lines drawn with a QGraphicsPath. Unfortunately, no matter what I try, I always get (0, 0) back as the position for both the start and end widgets. I'm constructing t...
[ "If you use the QGraphicsItem::pos(), it gives you the position of the item in the parent coordinates. When using QGraphicsLayout, the parent is probably the cell containing the object thus the coordinate is equal to zero.\nSince you want to connect widgets with path, you will need scene coordinate to define the co...
[ 1 ]
[]
[]
[ "pyqt", "python", "qt" ]
stackoverflow_0002799776_pyqt_python_qt.txt
Q: testing existing attribute of a @classmethod function, yields AttributeError i have a function which is a class method, and i want to test a attribute of the class which may or may not be None, but will exist always. class classA(): def __init__(self, var1, var2 = None): self.attribute1 = var1 self.attribute2...
testing existing attribute of a @classmethod function, yields AttributeError
i have a function which is a class method, and i want to test a attribute of the class which may or may not be None, but will exist always. class classA(): def __init__(self, var1, var2 = None): self.attribute1 = var1 self.attribute2 = var2 @classmethod def func(self,x): if self.attribute2 is None: do some...
[ "There is a difference between class attributes and instance attributes. A quick demonstration would be this:\n>>> class A(object):\n... x=4\n... def __init__(self):\n... self.y=2\n>>> a=A() #a is now an instance of A\n>>> A.x #Works as x is an attribute of the class\n2: 4\n>>> a.x #Works as instanc...
[ 7, 2, 2, 0 ]
[]
[]
[ "class", "python", "variables" ]
stackoverflow_0002791759_class_python_variables.txt
Q: How to find the file system type in python I'm looking for a way in python to find out which type of file system is being used for a given path. I'm wanting to do this in a cross platform way. On linux I could just grab the output of df -T but that won't work on OSX or windows. A: Take the hint -- different pla...
How to find the file system type in python
I'm looking for a way in python to find out which type of file system is being used for a given path. I'm wanting to do this in a cross platform way. On linux I could just grab the output of df -T but that won't work on OSX or windows.
[ "Take the hint -- different platforms are actually different. \nUse lsvfs on Mac OS X and those Linux that support it.\nUse this on Windows.\nUse an if-statement to decide.\n", "This is the Windows API you might want to call. This should be a good start for the OS X api you are looking for, instead.\n" ]
[ 2, 0 ]
[ "os.popen('/sbin/fdisk -l /dev/sda') on Linux\n" ]
[ -1 ]
[ "filesystems", "macos", "python", "windows" ]
stackoverflow_0002800798_filesystems_macos_python_windows.txt
Q: MySQL LOAD DATA LOCAL INFILE example in python? I am looking for a syntax definition, example, sample code, wiki, etc. for executing a LOAD DATA LOCAL INFILE command from python. I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welco...
MySQL LOAD DATA LOCAL INFILE example in python?
I am looking for a syntax definition, example, sample code, wiki, etc. for executing a LOAD DATA LOCAL INFILE command from python. I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welcome. A Google search is not turning up much in the wa...
[ "Well, using python's MySQLdb, I use this:\nconnection = MySQLdb.Connect(host='**', user='**', passwd='**', db='**')\ncursor = connection.cursor()\nquery = \"LOAD DATA INFILE '/path/to/my/file' INTO TABLE sometable FIELDS TERMINATED BY ';' ENCLOSED BY '\\\"' ESCAPED BY '\\\\\\\\'\"\ncursor.execute( query )\nconnect...
[ 30 ]
[ "You can also get the results for the import by adding the following lines after your query:\nresults = connection.info()\n\n" ]
[ -1 ]
[ "load_data_infile", "mysql", "python" ]
stackoverflow_0001231900_load_data_infile_mysql_python.txt
Q: Boost.Python wrapping hierarchies avoiding diamond inheritance I'm having some trouble seeing what the best way to wrap a series of classes with Boost.Python while avoiding messy inheritance problems. Say I have the classes A, B, and C with the following structure: struct A { virtual void foo(); virtual vo...
Boost.Python wrapping hierarchies avoiding diamond inheritance
I'm having some trouble seeing what the best way to wrap a series of classes with Boost.Python while avoiding messy inheritance problems. Say I have the classes A, B, and C with the following structure: struct A { virtual void foo(); virtual void bar(); virtual void baz(); }; struct B : public A { virt...
[ "One approach is to derive virtually:\nstruct B : virtual public A, ... { };\nstruct C : virtual public A, ... { };\nstruct A_Wrapper : virtual public A, ... { };\n\nSee the relevant C++ FAQ Lite items for notes and what this implies.\n", "I had exactly the same problem, and I simply didn't inherited B_Wrapper fr...
[ 1, 1 ]
[]
[]
[ "boost", "boost_python", "c++", "python" ]
stackoverflow_0002792117_boost_boost_python_c++_python.txt
Q: is this a correct way to generate rsa keys? is this code going to give me correct values for RSA keys (assuming that the other functions are correct)? im having trouble getting my program to decrypt properly, as in certain blocks are not decrypting properly this is in python: import random def keygen(bits): p ...
is this a correct way to generate rsa keys?
is this code going to give me correct values for RSA keys (assuming that the other functions are correct)? im having trouble getting my program to decrypt properly, as in certain blocks are not decrypting properly this is in python: import random def keygen(bits): p = q = 3 while p == q: p = random.rand...
[ "Mathematically, your n, e and d appear to respect the RSA rules (i.e. for every prime r which divides n, r2 does not divide n, and d is an inverse of e modulo r-1). However, RSA is a bit more than that; it also mandates some padding rules, which govern how a message (a sequence of bytes) is to be transformed into ...
[ 16, 5 ]
[]
[]
[ "cryptography", "public_key", "python", "rsa" ]
stackoverflow_0002799503_cryptography_public_key_python_rsa.txt
Q: Overwrite method at runtime in python I have method that run many times. I dont want to nest ifs inside but rather want to overwrite method and then run it. I know that i can overwrite class method by simple assigment, but overwriten method doesn't see private members: class X: def __init__(self, a): s...
Overwrite method at runtime in python
I have method that run many times. I dont want to nest ifs inside but rather want to overwrite method and then run it. I know that i can overwrite class method by simple assigment, but overwriten method doesn't see private members: class X: def __init__(self, a): self.a = a self.__b = a def m(s...
[ "Attributes within classes that start with double underscores are name-mangled. Never use them unless you're certain you need them. There's nothing private about them, so you should use a single underscore instead.\nThe reason you're having this problem is because the attribute access in a2() is not name-mangled.\n...
[ 4 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0002802896_oop_python.txt
Q: How to make if-elif-else statement in python more space-saving? I have a lot of if-elif-else statements in my code if message == '0' or message == '3' or message == '5' or message == '7': ... elif message == '1' or message == '2' or message == '4' or message == '6' or message == '8': ... else: ... Is it...
How to make if-elif-else statement in python more space-saving?
I have a lot of if-elif-else statements in my code if message == '0' or message == '3' or message == '5' or message == '7': ... elif message == '1' or message == '2' or message == '4' or message == '6' or message == '8': ... else: ... Is it possible to format this in a more space-saving way? I tried it this ...
[ "if message in (\"0\", \"3\", \"5\", \"7\"):\n ...\nelif message in ...\n\nwould be one way. \nIf message is always one character long, you could also use\nif message in \"0357\":\n ....\n\nBut this would also be true if message == \"35\", therefore the warning.\n\n(EDIT)\nA short explanation why your approac...
[ 6, 1 ]
[]
[]
[ "optimization", "python" ]
stackoverflow_0002803133_optimization_python.txt
Q: How to get these values with BeautifulSoup? I have this html table: <table> <tr> <td class="datax">a</td> <td class="datax">b</td> <td class="datax">c</td> <td class="datax">d</td> </tr> <tr> <td class="datax">e</td> <td class="datax">f</td> <td c...
How to get these values with BeautifulSoup?
I have this html table: <table> <tr> <td class="datax">a</td> <td class="datax">b</td> <td class="datax">c</td> <td class="datax">d</td> </tr> <tr> <td class="datax">e</td> <td class="datax">f</td> <td class="datax">g</td> <td class="datax">h</...
[ "This should do it~\nfinal_values=[td.string for td in bs.findAll('td', {'class':'datax'})[1::2]]\n\n(after comment clarification) for your specific case it would be:\nfinal_values=[td.b.a.string for td in bs.findAll('td', {'class':'datax'})[1::2]]\n\n" ]
[ 5 ]
[ "I know using HTQL, it is simple: \n<tr>.<td>2,4\n--\nHTQL only has COM support thought. Here is a complete example in javascript: \n<html> \n<body> \n<script language=JavaScript> \n     var a= new ActiveXObject(\"HtqlCom.HtqlControl\"); \n     a.setUrl(\"C:\\\\test_table.html\"); \n     a.setQuery(\"<tr>...
[ -2 ]
[ "beautifulsoup", "python" ]
stackoverflow_0002803140_beautifulsoup_python.txt
Q: GUI Builder for Python I looking for a GUI Builder for python i know it exist, can see it in this image background A: It is Glade 3, a GUI Designer for GTK+. It generates an XML file representing your GUI. You can load this GUI later using PyGTK. Specifically, the screenshot is running a Mac OS X port of Glade...
GUI Builder for Python
I looking for a GUI Builder for python i know it exist, can see it in this image background
[ "It is Glade 3, a GUI Designer for GTK+. It generates an XML file representing your GUI. You can load this GUI later using PyGTK. \nSpecifically, the screenshot is running a Mac OS X port of Glade 3\n", "That's glade, it actually produces XML, which can be used with the PyGTK library in python\n", "The GUI desi...
[ 8, 5, 4, 2, 2, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0000529498_python.txt
Q: Chart for deciphering terms in different programming languages This has been bugging me every since I started to use Python - in PHP you have this ability to use a string as a key in an array. PHP calls these associative arrays. Python calls these dictionaries. Does anyone know of a premade chart that will let me ...
Chart for deciphering terms in different programming languages
This has been bugging me every since I started to use Python - in PHP you have this ability to use a string as a key in an array. PHP calls these associative arrays. Python calls these dictionaries. Does anyone know of a premade chart that will let me see what the different terminology is in different languages. For ex...
[ "I don't know where to find a chart, but Wikipedia has a detailed article about associative arrays in various languages\n", "I hope the below URL will solve your issue...this is ant a chat but see this blog, which express the performance management.\nhttp://www.insideria.com/2008/04/dictionaries-and-associative-a...
[ 1, 0, 0 ]
[]
[]
[ "php", "programming_languages", "python" ]
stackoverflow_0002803707_php_programming_languages_python.txt
Q: Why does not the Python MSI installers come with Tcl/Tk header files? The MSI installers downloadable from python.org does not include Tcl/Tk header (not source) files (that are required to compile some packages like matplotlib). Does anyone know of the rationale behind not including them? A: The windows install...
Why does not the Python MSI installers come with Tcl/Tk header files?
The MSI installers downloadable from python.org does not include Tcl/Tk header (not source) files (that are required to compile some packages like matplotlib). Does anyone know of the rationale behind not including them?
[ "The windows installers don't include ANY source files. Simply because that's how windows apps work. It can be compiled on one computer and it will work on all. So windows versions of things like python and php come precompiled with all options enabled.\nIf you want the source files you have to download a source ta...
[ 1, 0 ]
[]
[]
[ "header_files", "python", "tcl", "tk_toolkit", "tkinter" ]
stackoverflow_0002114615_header_files_python_tcl_tk_toolkit_tkinter.txt
Q: How can I parse a C header file with Perl? I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back. For example I have some structure like const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 3...
How can I parse a C header file with Perl?
I have a header file in which there is a large struct. I need to read this structure using some program and make some operations on each member of the structure and write them back. For example I have some structure like const BYTE Some_Idx[] = { 4,7,10,15,17,19,24,29, 31,32,35,45,49,51,52,54, 55,58,60,64,65,66,67,69,...
[ "Keeping your data lying around in a header makes it trickier to get at using other programs like Perl. Another approach you might consider is to keep this data in a database or another file and regenerate your header file as-needed, maybe even as part of your build system. The reason for this is that generating C ...
[ 10, 6, 4, 3, 2, 2, 2, 0, 0 ]
[]
[]
[ "c", "header_files", "parsing", "perl", "python" ]
stackoverflow_0000994732_c_header_files_parsing_perl_python.txt
Q: twisted reactor stops too early I'm doing a batch script to connect to a tcp server and then exiting. My problem is that I can't stop the reactor, for example: cmd = raw_input("Command: ") # custom factory, the protocol just send a line reactor.connectTCP(HOST,PORT, CommandClientFactory(cmd) d = defer.Deferred()...
twisted reactor stops too early
I'm doing a batch script to connect to a tcp server and then exiting. My problem is that I can't stop the reactor, for example: cmd = raw_input("Command: ") # custom factory, the protocol just send a line reactor.connectTCP(HOST,PORT, CommandClientFactory(cmd) d = defer.Deferred() d.addCallback(lambda x: reactor.sto...
[ "The simple solution is to call reactor.stop() at the point in your code when you detect your exit condition. Specifically, it would look like you'd want to call it somewhere within CommandClient after, I'm assuming, it sends your command to the remote machine and receives back the command's exit code. \nAs written...
[ 5 ]
[]
[]
[ "networking", "python", "twisted" ]
stackoverflow_0002804381_networking_python_twisted.txt
Q: Is possible to auto-import a module from a different subfolder in other subfolder? I have a kind of plugin system, with this layout: Python SDK Plugins Plugin1 Plugin2 All 3 have a __init__.py file. I wonder if is possible to be able to do import SDK from any plugin (as if SDK was in the site-packages folder)...
Is possible to auto-import a module from a different subfolder in other subfolder?
I have a kind of plugin system, with this layout: Python SDK Plugins Plugin1 Plugin2 All 3 have a __init__.py file. I wonder if is possible to be able to do import SDK from any plugin (as if SDK was in the site-packages folder). I'm in a situation where need to deploy, update, delete, add or change SDK files...
[ "\nPython\n\nstart.py \nfrom SDK.Plugins import Plugin1\nprint Plugin1.test()\n\nSDK\n\n__init__.py\nPlugins\n\n__init__.py\nPlugin1.py\nfrom SDK.Plugins import Plugin2\ndef test():\n return Plugin2.test2()\n\nPlugin2.py\ndef test2():\n return \"This worked!\"\n\n\n\n\n\n\n# python start.py\nThis worked!\n\nT...
[ 2 ]
[]
[]
[ "path", "plugins", "python" ]
stackoverflow_0002804625_path_plugins_python.txt
Q: How to "signal" interested child processes (without signals)? I'm trying to find a good and simple method to signal child processes (created through SocketServer with ForkingMixIn) from the parent process. While Unix signals could be used, I want to avoid them since only children who are interested should receive ...
How to "signal" interested child processes (without signals)?
I'm trying to find a good and simple method to signal child processes (created through SocketServer with ForkingMixIn) from the parent process. While Unix signals could be used, I want to avoid them since only children who are interested should receive the signal, and it would be overkill and complicated to require som...
[ "Since you are on a unix system, semaphores should be the easy answer.\nUnfortunately, python does not seem to offer a way to call the semop system call.\nIf you are using python 2.6 , you may be able to use the\nmultiprocessing module Condition class.\n", "I have come up with the idea of using a pipe file descri...
[ 3, 2 ]
[]
[]
[ "fork", "python", "signals", "subprocess", "unix" ]
stackoverflow_0002804964_fork_python_signals_subprocess_unix.txt
Q: How to build sqlite for Python 2.4? I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message: error: command 'gcc' failed with exit status...
How to build sqlite for Python 2.4?
I would like to use pysqlite interface between Python and sdlite database. I have already Python and SQLite on my computer. But I have troubles with installation of pysqlite. During the installation I get the following error message: error: command 'gcc' failed with exit status 1 As far as I understood the problems a...
[ "You can download and install Python to your home directory. \n$ cd\n$ mkdir opt\n$ mkdir downloads\n$ cd downloads\n$ wget http://www.python.org/ftp/python/2.6.2/Python-2.6.2.tgz\n$ tar xvzf Python-2.6.2.tgz\n$ cd Python-2.6.2\n$ ./configure --prefix=$HOME/opt/ --enable-unicode=ucs4\n$ make\n$ make install\n\nThe...
[ 1, 1, 0, 0 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0001455642_pysqlite_python_sqlite.txt
Q: How to compile Python scripts for use in FORTRAN? Although I found many answers and discussions about this question, I am unable to find a solution particular to my situation. Here it is: I have a main program written in FORTRAN. I have been given a set of python scripts that are very useful. My goal is to access ...
How to compile Python scripts for use in FORTRAN?
Although I found many answers and discussions about this question, I am unable to find a solution particular to my situation. Here it is: I have a main program written in FORTRAN. I have been given a set of python scripts that are very useful. My goal is to access these python scripts from my main FORTRAN program. Curr...
[ "One way or another, you'll need to get the Python runtime on your server, otherwise it won't be possible to execute Python bytecode. Ignacio is on the right track with suggesting invoking libpython directly, but due to Fortran's parameter-passing conventions, it will be a lot easier for you to write a C wrapper t...
[ 3, 2 ]
[]
[]
[ "compilation", "fortran", "python" ]
stackoverflow_0002805244_compilation_fortran_python.txt
Q: regular expression search in python I am trying to parse some data and just started reading up on regular Expressions so I am pretty new to it. This is the code I have so far String = "MEASUREMENT 3835 303 Oxygen: 235.78 Saturation: 90.51 Temperature: 24.41 DPhase: 33.07 BPhase: 29.56 ...
regular expression search in python
I am trying to parse some data and just started reading up on regular Expressions so I am pretty new to it. This is the code I have so far String = "MEASUREMENT 3835 303 Oxygen: 235.78 Saturation: 90.51 Temperature: 24.41 DPhase: 33.07 BPhase: 29.56 RPhase: 0.00 BAmp: 368.57 BPot:...
[ "re.search( r\"Oxygen: *([\\d.]+)\", String ).group( 1 )\n\n", "import re\nstring = \"blabla Oxygen: 10.10 blabla\"\nregex_oxygen = re.compile('''Oxygen:\\W+([0-9.]*)''')\nresult = re.findall(regex_oxygen,string)\nprint result\n\n", "What for?\nprint String.split()[4]\n\n", "For general parsing of lists ...
[ 2, 1, 0, 0, 0 ]
[ "I would like to share my ?is this an email? regex expresion, just to inspire you. :)\n 9 emailregex = \"^[a-zA-Z.a-zA-Z]+@mycompany.org$\"\n 10\n 11 def validateEmail(email):\n 12 \"\"\"returns 1 if is an email, 0 if not \"\"\"\n 13 # len(x.y@mycompany.org) = 17\n 14 if len(email)>=17:\n 1...
[ -1 ]
[ "python", "regex", "string" ]
stackoverflow_0002803923_python_regex_string.txt
Q: Django: Applying Calculations To A Query Set I have a QuerySet that I wish to pass to a generic view for pagination: links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300] This is my "hot" page which lists my 300 latest submissions (10 pages of 30 links each). I want to now sort this Query...
Django: Applying Calculations To A Query Set
I have a QuerySet that I wish to pass to a generic view for pagination: links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300] This is my "hot" page which lists my 300 latest submissions (10 pages of 30 links each). I want to now sort this QuerySet by an algorithm that HackerNews uses: (p - 1) ...
[ "You can make a values dict or values list from your QuerySet if it's possible and apply your sorting algorithm to the dict(list) obtained.\nSee\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields\nhttp://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list-fields\nExample\n# select...
[ 2, 1, 0 ]
[]
[]
[ "algorithm", "django", "python", "sorting" ]
stackoverflow_0002799198_algorithm_django_python_sorting.txt
Q: Regular expression works normally, but fails when placed in an XML schema I have a simple doc.xml file which contains a single root element with a Timestamp attribute: <?xml version="1.0" encoding="utf-8"?> <root Timestamp="04-21-2010 16:00:19.000" /> I'd like to validate this document against a my simple schema....
Regular expression works normally, but fails when placed in an XML schema
I have a simple doc.xml file which contains a single root element with a Timestamp attribute: <?xml version="1.0" encoding="utf-8"?> <root Timestamp="04-21-2010 16:00:19.000" /> I'd like to validate this document against a my simple schema.xsd to make sure that the Timestamp is in the correct format: <?xml version="1....
[ "Your |s match wider than you think.\n(0[0-9]{1})|(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3}\n\nis parsed as:\n(0[0-9]{1})\n -or-\n(1[0-2]{1})-(3[0-1]{1}|[0-2]{1}[0-9]{1})-[2-9]{1}[0-9]{3}\n\nYou need to use more groupings if you want to avoid it; e.g.\n((0[0-9]{1})|(1[0-2]{1}))-((3[0-1]{1}|[0-2]{...
[ 3, 3 ]
[]
[]
[ "lxml", "python", "regex", "schema", "validation" ]
stackoverflow_0002806399_lxml_python_regex_schema_validation.txt
Q: What's the best way to aggregate the boolean values of a Python dictionary? For the following Python dictionary: dict = { 'stackoverflow': True, 'superuser': False, 'serverfault': False, 'meta': True, } I want to aggregate the boolean values above into the following boolean expression: dict['stack...
What's the best way to aggregate the boolean values of a Python dictionary?
For the following Python dictionary: dict = { 'stackoverflow': True, 'superuser': False, 'serverfault': False, 'meta': True, } I want to aggregate the boolean values above into the following boolean expression: dict['stackoverflow'] and dict['superuser'] and dict['serverfault'] and dict['meta'] The ab...
[ "in python 2.5+:\nall(dict.itervalues())\n\nin python 3+\nall(dict.values())\n\ndict is a bad variable name, though, because it is the name of a builtin type\nEdit: add syntax for python 3 version. values() constructs a view in python 3, unlike 2.x where it builds the list in memory.\n" ]
[ 23 ]
[]
[]
[ "python" ]
stackoverflow_0002806611_python.txt
Q: How to bind a double precision using psycopg2 I'm trying to bind a float to a postgresql double precision using psycopg2. ele = 1.0/3.0 dic = {'name': 'test', 'ele': ele} sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)''' cur = db.cursor() cur.execute(sql, dic) db.commit() sql = """se...
How to bind a double precision using psycopg2
I'm trying to bind a float to a postgresql double precision using psycopg2. ele = 1.0/3.0 dic = {'name': 'test', 'ele': ele} sql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)''' cur = db.cursor() cur.execute(sql, dic) db.commit() sql = """select elevation from waypoints where name = 'test'""...
[ "The reason you're getting this problem is the following line of code:\nsql = '''insert into waypoints (name, elevation) values (%(name)s, %(ele)s)'''\n\nbecause when the float is converted into a string here, you don't get all of the digits that you're expecting. For instance, \nstr(ele)\n\nproduces\n'0.3333333333...
[ 0 ]
[]
[]
[ "psycopg2", "python" ]
stackoverflow_0002806517_psycopg2_python.txt
Q: On a Mac w/ Python2.6 and trying to install psycopg2 I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here: http://py-psycopg.darwinports.com/ I get something like... sudo port install py-psycopg ... bunch of erro...
On a Mac w/ Python2.6 and trying to install psycopg2
I am new to Python. I have Python2.6 running now. I am following the Tutorial on the Python site. My question is when I try to follow the instructions here: http://py-psycopg.darwinports.com/ I get something like... sudo port install py-psycopg ... bunch of errors here... Error: The following dependencies failed to bui...
[ "If you're using Python 2.6, you actually want to build py26-psycopg2:\n$ sudo port install py26-psycopg2\n\nIn MacPorts, py-* packages build using Python 2.4, py25-* using Python 2.5, and py26-* use Python 2.6.\n", "Maybe you need to look at the version for Python 2.6? \n", "I had problems installing psycopg2 ...
[ 10, 3, 1, 0, 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0001374187_macos_python.txt
Q: How do I require that an element has either one set of attributes or another in an XSD schema? I'm working with an XML document where a tag must either have one set of attributes or another. For example, it needs to either look like <tag foo="hello" bar="kitty" /> or <tag spam="goodbye" eggs="world" /> e.g. <root...
How do I require that an element has either one set of attributes or another in an XSD schema?
I'm working with an XML document where a tag must either have one set of attributes or another. For example, it needs to either look like <tag foo="hello" bar="kitty" /> or <tag spam="goodbye" eggs="world" /> e.g. <root> <tag foo="hello" bar="kitty" /> <tag spam="goodbye" eggs="world" /> </root> So I have an ...
[ "It is unfortunately not possible to use choice with attributes in XML schema. You will need to implement this validation at a higher level.\n" ]
[ 5 ]
[]
[]
[ "lxml", "python", "schema", "validation", "xml" ]
stackoverflow_0002806880_lxml_python_schema_validation_xml.txt
Q: Loading datasets from datastore and merge into single dictionary. Resource problem I have a productdatabase that contains products, parts and labels for each part based on langcodes. The problem I'm having and haven't got around is a huge amount of resource used to get the different datasets and merging them into ...
Loading datasets from datastore and merge into single dictionary. Resource problem
I have a productdatabase that contains products, parts and labels for each part based on langcodes. The problem I'm having and haven't got around is a huge amount of resource used to get the different datasets and merging them into a dict to suit my needs. The products in the database are based on a number of parts tha...
[ "A few simple ideas:\n1) Since you need all the results, instead of doing a for loop like you have, call fetch() explicitly to just go ahead and get all the results at once. Otherwise, the for loop may result in multiple queries to the datastore as it only gets so many items at once. For example, perhaps you coul...
[ 2, 1, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002806760_google_app_engine_python.txt
Q: Django ValueError at /admin/ I am running Django with mod_python on a Red Hat Linux box in production. A little while ago, for a reason unknown to me, the admin stopped working, throwing a 500 error. The error is as follows: ValueError at /admin/ Empty module name Request Method: GET Exception Type: ValueError Exc...
Django ValueError at /admin/
I am running Django with mod_python on a Red Hat Linux box in production. A little while ago, for a reason unknown to me, the admin stopped working, throwing a 500 error. The error is as follows: ValueError at /admin/ Empty module name Request Method: GET Exception Type: ValueError Exception Value: Empty module name E...
[ "I was just debugging this problem. The error arises when Django is attempting to set up the template context processors, and the root cause was a definition which should have been a tuple but was actually a string.\nThis is what I had in my config file:\nTEMPLATE_CONTEXT_PROCESSORS = (\n'django.core.context_proce...
[ 5 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0001760797_django_django_admin_python.txt
Q: How do I delete in Django? (mysql transactions) If you are familiar with Django, you know that they have a Authentication system with User model. Of course, I have many other tables that have a Foreign Key to this User model. If I want to delete this user, how do I architect a script (or through mysql itself) to ...
How do I delete in Django? (mysql transactions)
If you are familiar with Django, you know that they have a Authentication system with User model. Of course, I have many other tables that have a Foreign Key to this User model. If I want to delete this user, how do I architect a script (or through mysql itself) to delete every table that is related to this user? My o...
[ "As far as I understand it, django does an \"on delete cascade\" by default:\nhttp://docs.djangoproject.com/en/dev/topics/db/queries/#deleting-objects\n", "You don't need a script for this. When you delete a record, Django will automatically delete all dependent records (thus taking care of its own database integ...
[ 2, 0 ]
[]
[]
[ "database", "django", "mysql", "python", "transactions" ]
stackoverflow_0002795793_database_django_mysql_python_transactions.txt
Q: Implementing a popularity algorithm in Django I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algo...
Implementing a popularity algorithm in Django
I am creating a site similar to reddit and hacker news that has a database of links and votes. I am implementing hacker news' popularity algorithm and things are going pretty swimmingly until it comes to actually gathering up these links and displaying them. The algorithm is simple: Y Combinator's Hacker News: Popul...
[ "On Hacker News, only the 210 newest stories and 210 most popular stories are paginated (7 pages worth * 30 stories each). My guess is that the reason for the limit (at least in part) is this problem.\nWhy not drop all the fancy SQL for the most popular stories and just keep a running list instead? Once you've esta...
[ 10, 4, 4, 1 ]
[]
[]
[ "algorithm", "django", "postgresql", "python" ]
stackoverflow_0001965341_algorithm_django_postgresql_python.txt
Q: How to get a html elements with python lxml I have this html code: <table> <tr> <td class="test"><b><a href="">aaa</a></b></td> <td class="test">bbb</td> <td class="test">ccc</td> <td class="test"><small>ddd</small></td> </tr> <tr> <td class="test"><b><a href="">eee</a></b></td> <td class="test">fff...
How to get a html elements with python lxml
I have this html code: <table> <tr> <td class="test"><b><a href="">aaa</a></b></td> <td class="test">bbb</td> <td class="test">ccc</td> <td class="test"><small>ddd</small></td> </tr> <tr> <td class="test"><b><a href="">eee</a></b></td> <td class="test">fff</td> <td class="test">ggg</td> <td class="te...
[ "If you do el.text_content() you'll strip all the tag stuff from each element, i.e.:\nresult = [el.text_content() for el in result]\n\n", "Why dont you just fetch what you want in each step?\nlinks = [el.text for el in html.xpath('//td[@class=\"test\"][position() = 1]/b/a')]\nsmalls = [el.text for el in html.xpat...
[ 8, 4 ]
[]
[]
[ "lxml", "python", "xml" ]
stackoverflow_0002807209_lxml_python_xml.txt
Q: How can I specify a relative path in a Python logging config file? I've the following file to config logging: [loggers] keys=root [handlers] keys = root [formatters] keys = generic # Loggers [logger_root] level = DEBUG handlers = root # Handlers [handler_root] class = handlers.RotatingFileHandler args = ("test...
How can I specify a relative path in a Python logging config file?
I've the following file to config logging: [loggers] keys=root [handlers] keys = root [formatters] keys = generic # Loggers [logger_root] level = DEBUG handlers = root # Handlers [handler_root] class = handlers.RotatingFileHandler args = ("test.log", "maxBytes=1*1024*1024", "backupCount=10") level = NOTSET formatte...
[ "Mark is right, your path in the config file is relative to whatever directory is current when the logging.config.fileConfig call is made. This depends on the details of your deployment method.\nYou may need to specify an absolute path to your file, by prefixing 'test.log' with a directory you know to be writable b...
[ 7 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0002806376_django_logging_python.txt
Q: GIS: When and why to use ArcObjects over GDAL programming to work with ArcGIS rasters and vectors? Im just starting off with GDAL + python to support operations that cannot be done with ArcGIS python geoprocessing scripting. Mainly I am doing spatial modeling/analysis/editing of raster and vector data. I am a bit ...
GIS: When and why to use ArcObjects over GDAL programming to work with ArcGIS rasters and vectors?
Im just starting off with GDAL + python to support operations that cannot be done with ArcGIS python geoprocessing scripting. Mainly I am doing spatial modeling/analysis/editing of raster and vector data. I am a bit confused when ArcObject development is required versus when GDAL can be used? Is there functionality of ...
[ "GDAL is included in ArcGIS to work with some raster data formats. They do not use the GDAL utilities to do any geoprocessing. I would imagine ESRI have implemented most, if not all, of the functionality in GDAL with their own geoprocessing functions. In summary there is a big overlap in functionality between the t...
[ 5, 4, 2 ]
[]
[]
[ "arcgis", "gdal", "gis", "python" ]
stackoverflow_0002276235_arcgis_gdal_gis_python.txt
Q: Asynchronous daemon processing / ORM interaction with Django I'm looking for a way to do asynchronous data processing with a daemon that uses Django ORM. However, the ORM isn't thread-safe; it's not thread-safe to try to retrieve / modify django objects from within threads. So I'm wondering what the correct way to...
Asynchronous daemon processing / ORM interaction with Django
I'm looking for a way to do asynchronous data processing with a daemon that uses Django ORM. However, the ORM isn't thread-safe; it's not thread-safe to try to retrieve / modify django objects from within threads. So I'm wondering what the correct way to achieve asynchrony is? Basically what I need to accomplish is ta...
[ "Have a look at celery . I guess that would solve your problem. It uses multiprocessing module. It needs a (very) little setup, however helps a lot in scaling.\n", "If your asynchronous processing is being done in its own process, then thread safety is not an issue because your threads are not sharing an address ...
[ 3, 2 ]
[]
[]
[ "django", "django_models", "django_orm", "python" ]
stackoverflow_0002805914_django_django_models_django_orm_python.txt
Q: more efficient way to pickle a string The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) The lengths are 1133 characters and 4249 characters res...
more efficient way to pickle a string
The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following z = numpy.zeros(1000, numpy.uint8) len(z.dumps()) len(cPickle.dumps(z.dumps())) The lengths are 1133 characters and 4249 characters respectively. z.dumps() reveals something like...
[ "Try using a later version of the pickle protocol with the protocol parameter to pickle.dumps(). The default is 0 and is an ASCII text format. Ones greater than 1 (I suggest you use pickle.HIGHEST_PROTOCOL). Protocol formats 1 and 2 (and 3 but that's for py3k) are binary and should be more space conservative.\n", ...
[ 24, 9, 3, 1 ]
[]
[]
[ "numpy", "pickle", "python", "space_efficiency" ]
stackoverflow_0000695794_numpy_pickle_python_space_efficiency.txt
Q: how do I obtain all the elements of a generator expression I wrote? I am using google-app-engine webapp, part of the code is : class Post(db.Model): title = db.StringProperty(required=True) def categories(self): return (x.category for x in self.postcategory_set) class Category(db.Model): name...
how do I obtain all the elements of a generator expression I wrote?
I am using google-app-engine webapp, part of the code is : class Post(db.Model): title = db.StringProperty(required=True) def categories(self): return (x.category for x in self.postcategory_set) class Category(db.Model): name = db.StringProperty() class PostCategory(db.Model): post = db.Refer...
[ "It is categories().next() that you need. Generators have no get. \n", "If you wanted an all method you should return a list comprehension instead of a generator: \nreturn [x.category for x in self.postcategory_set]\n\nbut since postcategory_set is already an iterable (because you iterated it) \nreturn self.postc...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "python", "referenceproperty" ]
stackoverflow_0002807841_google_app_engine_python_referenceproperty.txt
Q: Scipy-Cluster installation for python 2.6 Has anyone used scipy-cluster for python? I am trying to compile its source code with python 2.6 but I get some irrelevant errors. has someone had the same problem? A: apt-get install python-hcluster worked for me on Ubuntu 10.04.
Scipy-Cluster installation for python 2.6
Has anyone used scipy-cluster for python? I am trying to compile its source code with python 2.6 but I get some irrelevant errors. has someone had the same problem?
[ "apt-get install python-hcluster worked for me on Ubuntu 10.04.\n" ]
[ 0 ]
[]
[]
[ "python", "scipy" ]
stackoverflow_0002805772_python_scipy.txt
Q: How do I retrieve program output in Python? I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to: $version = `java -version`; How would I go about getting the same end result in Python...
How do I retrieve program output in Python?
I'm not a Perl user, but from this question deduced that it's exceedingly easy to retrieve the standard output of a program executed through a Perl script using something akin to: $version = `java -version`; How would I go about getting the same end result in Python? Does the above line retrieve standard error (eq...
[ "For python 2.5: sadly, no. You need to use subprocess:\nimport subprocess\nproc = subprocess.Popen(['java', '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nout, err = proc.communicate()\n\nDocs are at http://docs.python.org/library/subprocess.html\n", "In Python 2.7+\nfrom subprocess import check_o...
[ 7, 6, 4 ]
[]
[]
[ "c++", "perl", "python" ]
stackoverflow_0002804194_c++_perl_python.txt
Q: Google App Engine: 403 and 404 error How do I implement using python if I want to manage the 403 and 404 error, for example, to know which URL is most the 403 or 404 error? A: There is no need to do this manually on App Engine. Just take a look at the "Errors" section in the dashboard for your app. For more info...
Google App Engine: 403 and 404 error
How do I implement using python if I want to manage the 403 and 404 error, for example, to know which URL is most the 403 or 404 error?
[ "There is no need to do this manually on App Engine. Just take a look at the \"Errors\" section in the dashboard for your app.\nFor more information on this, see http://code.google.com/intl/de-DE/appengine/kb/general.html#erroruris\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0002808416_google_app_engine_python.txt
Q: Are there any Bayeux clients in Python? I need to connect to a Bayeux server form a wxPython APP. I would appreciate any hint about that. A: Ok I've found an example client here: http://svn.cometd.com/trunk/cometd-twisted/
Are there any Bayeux clients in Python?
I need to connect to a Bayeux server form a wxPython APP. I would appreciate any hint about that.
[ "Ok I've found an example client here:\nhttp://svn.cometd.com/trunk/cometd-twisted/\n" ]
[ 6 ]
[]
[]
[ "bayeux", "cometd", "python" ]
stackoverflow_0002809202_bayeux_cometd_python.txt
Q: Installing Python egg dependencies without apt-get I've got a Python module which is distributed on PyPI, and therefore installable using easy_install. It depends on lxml, which in turn depends on libxslt1-dev. I'm unable to install libxslt1-dev with easy_install, so it doesn't work to put it in install_requires. ...
Installing Python egg dependencies without apt-get
I've got a Python module which is distributed on PyPI, and therefore installable using easy_install. It depends on lxml, which in turn depends on libxslt1-dev. I'm unable to install libxslt1-dev with easy_install, so it doesn't work to put it in install_requires. Is there any way I can get setuptools to install it inst...
[ "It's better use apt-get to install lxml (or the python packages that has c extensions) and then pull pure python package from pypi. Also I generally try to avoid using easy_install for top level install, I rather create a virtual env using virtualenv and then use easy_install created by virtualenv to keep my setup...
[ 1, 1 ]
[]
[]
[ "installation", "packaging", "python", "setuptools" ]
stackoverflow_0002808956_installation_packaging_python_setuptools.txt
Q: sort a list of percentages I have the following list: l = ['50%','12.5%','6.25%','25%'] Which I would like to sort in the following order: ['6.25%','12.5%','25%','50%'] Using l.sort() yields: ['12.5%','25%','50%','6.25%'] Any cool tricks to sort these lists easily in Python? A: You can sort with a custom key ...
sort a list of percentages
I have the following list: l = ['50%','12.5%','6.25%','25%'] Which I would like to sort in the following order: ['6.25%','12.5%','25%','50%'] Using l.sort() yields: ['12.5%','25%','50%','6.25%'] Any cool tricks to sort these lists easily in Python?
[ "You can sort with a custom key\nb =['52.5%', '62.4%', '91.8%', '21.5%']\nb.sort(key = lambda a: float(a[:-1]))\n\nThis resorts the set, but uses the numerical value as the key (i.e. chops of the '%' in the string and converts to float.\n" ]
[ 17 ]
[]
[]
[ "list", "python", "sorting" ]
stackoverflow_0002809415_list_python_sorting.txt
Q: Can I just broadcast a specific message in my own network in python? I just want to broadcast a udp message on a specific port on my network. How can I accomplish this in python? A: This will only work with IPv4 networks: BC_PORT = 12345 import sys, time from socket import * s = socket(AF_INET, SOCK_DGRAM) s.bi...
Can I just broadcast a specific message in my own network in python?
I just want to broadcast a udp message on a specific port on my network. How can I accomplish this in python?
[ "This will only work with IPv4 networks:\nBC_PORT = 12345\nimport sys, time\nfrom socket import *\ns = socket(AF_INET, SOCK_DGRAM)\ns.bind(('', 0))\ns.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)\ns.sendto(\"hello world\", ('<broadcast>', BC_PORT))\n\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0002809392_python.txt
Q: Writing csv header removes data from numpy array written below I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line f...
Writing csv header removes data from numpy array written below
I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line from datastack. Any ideas why that could be? s = ','.join(itertools....
[ "You a file with the filename 'export.csv' twice, once when you call open() and once when you call numpy.savetxt(). Thus, there are two open file handles competing for the same filename. If you pass the file handle rather than the file name to numpy.savetxt() you avoid this race condition:\ns = ','.join(itertools...
[ 6 ]
[]
[]
[ "csv", "numpy", "python" ]
stackoverflow_0002809478_csv_numpy_python.txt
Q: Python byte per byte XOR decryption I have an XOR encypted file by a VB.net program using this function to scramble: Public Class Crypter ... 'This Will convert String to bytes, then call the other function. Public Function Crypt(ByVal Data As String) As String Return Encoding.Default.GetString...
Python byte per byte XOR decryption
I have an XOR encypted file by a VB.net program using this function to scramble: Public Class Crypter ... 'This Will convert String to bytes, then call the other function. Public Function Crypt(ByVal Data As String) As String Return Encoding.Default.GetString(Crypt(Encoding.Default.GetBytes(Data))) ...
[ "Your decoded data appears to contain unicode characters with values above 256. In Python 2.x chr can only handle values below 256. Use unichr instead of chr and it should work:\nreturn ''.join(unichr((ord(x) ^ ord(y))) \\\n for (x, y) in izip(data.decode('utf-8'), cycle(self.key))\n\n", "is it correct to save...
[ 3, 2, 1, 1 ]
[]
[]
[ "encryption", "python", "xor" ]
stackoverflow_0002806423_encryption_python_xor.txt
Q: Efficient way to combine results of two database queries I have two tables on different servers, and I'd like some help finding an efficient way to combine and match the datasets. Here's an example: From server 1, which holds our stories, I perform a query like: query = """SELECT author_id, title, text ...
Efficient way to combine results of two database queries
I have two tables on different servers, and I'd like some help finding an efficient way to combine and match the datasets. Here's an example: From server 1, which holds our stories, I perform a query like: query = """SELECT author_id, title, text FROM stories ORDER BY timestamp_created DESC ...
[ "If memory isn't a problem, you could use a dictionary.\nresults1_dict = dict((row[0], list(row[1:])) for row in results1)\nresults2_dict = dict((row[0], list(row[1:])) for row in results2)\n\nfor key, value in results2_dict:\n if key in results1_dict:\n results1_dict[key].extend(value)\n else:\n ...
[ 2, 0, 0, 0 ]
[]
[]
[ "database", "mysql", "pylons", "python", "sharding" ]
stackoverflow_0002808142_database_mysql_pylons_python_sharding.txt
Q: Sleeping a thread is blocking stdin I'm running a function which evaluates commands passed in using stdin and another function which runs a bunch of jobs. I need to make the latter function sleep at regular intervals but that seems to be blocking the stdin. Any advice on how to resolve this would be appreciated. T...
Sleeping a thread is blocking stdin
I'm running a function which evaluates commands passed in using stdin and another function which runs a bunch of jobs. I need to make the latter function sleep at regular intervals but that seems to be blocking the stdin. Any advice on how to resolve this would be appreciated. The source code for the functions is def r...
[ "Use a single thread:\nimport time\nimport select\nimport logging\nimport sys\n\ndef stdinWait(interval):\n start = time.time()\n while True:\n time_left = interval - (time.time() - start)\n if time_left <= 0:\n break\n r, w, x = select.select([sys.stdin], [], [], time_left)\n ...
[ 1 ]
[]
[]
[ "multithreading", "python", "sleep", "time" ]
stackoverflow_0002809282_multithreading_python_sleep_time.txt
Q: Routing Skype call to another Voip company As my project to do over this summer I would like to create a program that answers a Skype call using the Skype API and allows a user to connect to another VOIP provider (through SIP) and make calls by dialling through the client callers Skype application. I understand th...
Routing Skype call to another Voip company
As my project to do over this summer I would like to create a program that answers a Skype call using the Skype API and allows a user to connect to another VOIP provider (through SIP) and make calls by dialling through the client callers Skype application. I understand that the Skype API allows me to answer and receive...
[ "I think you'll have to hook into your OS' sound processing.\nOn Windows, you could install Virtual Audio Cable and configure Skype to use those virtual devices. Since nothing else will use them you can just capture and send sound from/to them to \"talk\" with Skype.\n" ]
[ 1 ]
[]
[]
[ "api", "python", "skype", "voip" ]
stackoverflow_0002805595_api_python_skype_voip.txt
Q: Can I get the raw SQL generated by a prepared statement in Python’s sqlite3 module? If so, how can I do this? A: When executing a prepared statement, no new SQL is generated. The idea of prepared statements is that the SQL query and its data are transmitted separately (that's why you don't have to escape any arg...
Can I get the raw SQL generated by a prepared statement in Python’s sqlite3 module?
If so, how can I do this?
[ "When executing a prepared statement, no new SQL is generated.\nThe idea of prepared statements is that the SQL query and its data are transmitted separately (that's why you don't have to escape any arguments) - the query is most likely only stored in an optimized form after preparing it.\n", "when you create a p...
[ 2, 1 ]
[]
[]
[ "pysqlite", "python", "sqlite" ]
stackoverflow_0002810235_pysqlite_python_sqlite.txt
Q: python socket problem I write this python code: import socks import socket socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "64.83.219.7", 58279) socket.socket = socks.socksocket socket.setdefaulttimeout(19) import urllib2 print urllib2.urlopen('http://www.google.com').read() but when I execute it, I get this error...
python socket problem
I write this python code: import socks import socket socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "64.83.219.7", 58279) socket.socket = socks.socksocket socket.setdefaulttimeout(19) import urllib2 print urllib2.urlopen('http://www.google.com').read() but when I execute it, I get this error: urllib2.URLError: <urlope...
[ "Something timed out in your script. I guess the connection to google because of wrong proxy setup. I think your goal is to fetch the contents of http://www.google.com through a proxy?\nI don't know about this method to set it using socket/socks module. Maybe you want to take a look at the following chapters in the...
[ 2 ]
[]
[]
[ "python", "sockets", "socks" ]
stackoverflow_0002810256_python_sockets_socks.txt
Q: GTK Progressbar pulsing python How can I get a Progressbar to "pulse" while another function is run? A: Push that another function into a separate thread. As long as your main thread runs any code, GUI is frozen. This is not a problem for short code pieces, but obviously a problem in your case. Also read what...
GTK Progressbar pulsing python
How can I get a Progressbar to "pulse" while another function is run?
[ "Push that another function into a separate thread. As long as your main thread runs any code, GUI is frozen. This is not a problem for short code pieces, but obviously a problem in your case.\nAlso read what PyGTK FAQ has to say about using threads in PyGTK program.\n", "There is an example of how to do this h...
[ 1, 1, 0 ]
[]
[]
[ "gtk", "python" ]
stackoverflow_0002805455_gtk_python.txt
Q: Making a CharField use a PasswordInput in the admin I have a Django site in which the site admin inputs their Twitter Username/Password in order to use the Twitter API. The Model is set up like this: class TwitterUser(models.Model): screen_name = models.CharField(max_length=100) password = models.CharField(max_le...
Making a CharField use a PasswordInput in the admin
I have a Django site in which the site admin inputs their Twitter Username/Password in order to use the Twitter API. The Model is set up like this: class TwitterUser(models.Model): screen_name = models.CharField(max_length=100) password = models.CharField(max_length=255) def __unicode__(self): return self.screen_n...
[ "From the docs, you can build your own form, something like this:\nfrom django.forms import ModelForm, PasswordInput\n\nclass TwitterUserForm(ModelForm):\n class Meta:\n model = TwitterUser\n widgets = {\n 'password': PasswordInput(),\n }\n\nOr you can do it like this:\nfrom djang...
[ 34 ]
[]
[]
[ "django", "django_admin", "python" ]
stackoverflow_0002810996_django_django_admin_python.txt
Q: Python file input string: how to handle escaped unicode characters? In a text file (test.txt), my string looks like this: Gro\u00DFbritannien Reading it, python escapes the backslash: >>> file = open('test.txt', 'r') >>> input = file.readline() >>> input 'Gro\\u00DFbritannien' How can I have this interpreted as ...
Python file input string: how to handle escaped unicode characters?
In a text file (test.txt), my string looks like this: Gro\u00DFbritannien Reading it, python escapes the backslash: >>> file = open('test.txt', 'r') >>> input = file.readline() >>> input 'Gro\\u00DFbritannien' How can I have this interpreted as unicode? decode() and unicode() won't do the job. The following code writ...
[ "You want to use the unicode_escape codec:\n>>> x = 'Gro\\\\u00DFbritannien'\n>>> y = unicode(x, 'unicode_escape')\n>>> print y\nGroßbritannien\n\nSee the docs for the vast number of standard encodings that come as part of the Python standard library.\n", "Use the built-in 'unicode_escape' codec:\n>>> file = open...
[ 9, 4 ]
[]
[]
[ "decode", "python", "unicode", "utf_8" ]
stackoverflow_0002811174_decode_python_unicode_utf_8.txt
Q: trouble setting up GtkTreeViews in PyGtk I've got some code in a class that extends gtk.TreeView, and this is the init method. I want to create a tree view that has 3 columns. A toggle button, a label, and a drop down box that the user can type stuff into. The code below works, except that the toggle button doesn'...
trouble setting up GtkTreeViews in PyGtk
I've got some code in a class that extends gtk.TreeView, and this is the init method. I want to create a tree view that has 3 columns. A toggle button, a label, and a drop down box that the user can type stuff into. The code below works, except that the toggle button doesn't react to mouse clicks and the label and the ...
[ "First of all, you need to create a model with bool, str and str columns, not the way you are doing now. Second, you need to bind properties of renderers from appropriate model columns, e.g. as in\nself.columnButton = \\\n gtk.TreeViewColumn ('Enabled', self.buttonRenderer, \n active = 0)...
[ 2, 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0002794296_gtk_gtktreeview_pygtk_python.txt
Q: Embedding Python and adding C functions to the interpreter I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my progr...
Embedding Python and adding C functions to the interpreter
I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my program. Here's my code so far: #include "python.h" static PyObject...
[ "You need to bind that function to some module, see http://docs.python.org/extending/embedding.html#extending-embedded-python\nEdit:\nBasicly your code should work. Whats not working?\n" ]
[ 2 ]
[]
[]
[ "c", "c++", "embedding", "function_pointers", "python" ]
stackoverflow_0002811596_c_c++_embedding_function_pointers_python.txt
Q: Django-registration and ReCaptcha integration - how to pass the user's IP New to django and trying to setup django-registration 0.8 with recaptcha-client. I followed the advice posted in the answer to this question. I used the custom form and custom backend from that post and the widget and field from this tutoria...
Django-registration and ReCaptcha integration - how to pass the user's IP
New to django and trying to setup django-registration 0.8 with recaptcha-client. I followed the advice posted in the answer to this question. I used the custom form and custom backend from that post and the widget and field from this tutorial. My form is displaying properly with the recaptcha widget but when I submit i...
[ "I also used the code from the tutorial you linked, in my case to add reCaptcha to the django comments app.\nYou need something like initial={'captcha': request.META['REMOTE_ADDR']} at the point where your RecaptchaRegistrationForm gets instantiated.\nUnfortunately this is buried in the registration/views.py regist...
[ 2 ]
[]
[]
[ "django", "python", "recaptcha", "registration" ]
stackoverflow_0002711680_django_python_recaptcha_registration.txt
Q: PyImport_ImportModule("PyQt4.QtGui") fails I've got a C++ windows app that is trying to load a PyQt4 object, similar to the way PyQt4 does it for providing python widgets in the QtDesigner. The app loads other Python modules just fine, but fails to load PyQt4.QtGui. Also, with straight Python, I can load PyQt4.QtG...
PyImport_ImportModule("PyQt4.QtGui") fails
I've got a C++ windows app that is trying to load a PyQt4 object, similar to the way PyQt4 does it for providing python widgets in the QtDesigner. The app loads other Python modules just fine, but fails to load PyQt4.QtGui. Also, with straight Python, I can load PyQt4.QtGui just fine. The debug output when it attempts ...
[ "After some investigation, it appears that my C++ app is using Qt dlls from one install of Qt, and Python is trying to load different Qt dlls - the ones installed with PyQt. I suspect that the failure is happening because the same process is trying to two dlls that are mostly the same. \n" ]
[ 0 ]
[]
[]
[ "pyqt4", "python" ]
stackoverflow_0002811982_pyqt4_python.txt
Q: Sqlalchemy+elixir: How query with a ManyToMany relationship? I'm using sqlalchemy with Elixir and have some troubles trying to make a query.. I have 2 entities, Customer and CustomerList, with a many to many relationship. customer_lists_customers_table = Table('customer_lists_customers', met...
Sqlalchemy+elixir: How query with a ManyToMany relationship?
I'm using sqlalchemy with Elixir and have some troubles trying to make a query.. I have 2 entities, Customer and CustomerList, with a many to many relationship. customer_lists_customers_table = Table('customer_lists_customers', metadata, Column('id', Integer, primary_key=Tru...
[ "Read the error message with attention, it points to the source of problem. Did you mean\nCustomerList.query.filter_by(CustomerList.customers.contains(customer)).all()?\nUpdate: When using declarative definition you can use just defined relation in class scope, but these properties are not visible outside class:\nc...
[ 1, 1, 0 ]
[]
[]
[ "python", "python_elixir", "sqlalchemy" ]
stackoverflow_0002810534_python_python_elixir_sqlalchemy.txt
Q: How To Create Per-Request Singleton in Pylons? In our Pylons based web-app, we're creating a class that essentially provides some logging functionality. We need a new instance of this class for each http request that comes in, but only one per request. What is the proper way to go about this? Should we just create...
How To Create Per-Request Singleton in Pylons?
In our Pylons based web-app, we're creating a class that essentially provides some logging functionality. We need a new instance of this class for each http request that comes in, but only one per request. What is the proper way to go about this? Should we just create the object in middleware and store in in request.en...
[ "There's a good implementation of request local variables in Paste: paste.registry Pylons uses this for its own request-local global variables.\nJust create the object in \"middleware\" like documented and import the global variable to the modules where you need it. (middleware in scarequotes because it's not stric...
[ 1, 0 ]
[]
[]
[ "pylons", "python", "singleton" ]
stackoverflow_0002812011_pylons_python_singleton.txt
Q: Generic function that accept a table and column name and returns all the primary key values that matches a filter value given i have functions that look like this that is littered through out the code def get_M_status(S): M_id = marital.select(marital.c.marital_status_description == S).execute().fetchone() ...
Generic function that accept a table and column name and returns all the primary key values that matches a filter value given
i have functions that look like this that is littered through out the code def get_M_status(S): M_id = marital.select(marital.c.marital_status_description == S).execute().fetchone() if M_id == None: print "Warning: No Marital id found for %s Marital status to Single" % S M_id = marital.select(...
[ "If the primary key is only one column, you can do something like:\ngetattr(table.c, pkey_col_name) == S\n\nas the 'generic' version of marital.c.marital_status_description == S.\nSo, something like (please note: this is untested):\ndef get_row(table, col_name, val, default=None):\n col = getattr(table.c, col_na...
[ 1, 1 ]
[]
[]
[ "python", "sqlalchemy" ]
stackoverflow_0002801164_python_sqlalchemy.txt
Q: Python proper use of __str__ and __repr__ My current project requires extensive use of bit fields. I found a simple, functional recipe for bit a field class but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing __str__ and __repr__ and I want to make sure I'm followi...
Python proper use of __str__ and __repr__
My current project requires extensive use of bit fields. I found a simple, functional recipe for bit a field class but it was lacking a few features I needed, so I decided to extend it. I've just got to implementing __str__ and __repr__ and I want to make sure I'm following convention. __str__ is supposed to be inform...
[ "The __repr__ should preferably be a string that could be used to recreate the object, for example if you use eval on it - see the docs here. This isn't an exact science, as it can depend on how the user of your module imported it, for example.\nI would have the __str__ return the binary string, and the __repr__ re...
[ 12, 1, 0 ]
[]
[]
[ "bit_manipulation", "conventions", "python", "representation" ]
stackoverflow_0002812809_bit_manipulation_conventions_python_representation.txt
Q: Which button was clicked? How can I detect which mouse button was clicked (right or left) in the slot for QtCore.SIGNAL('cellClicked(int,int)')? A: You would probably pass the event to your cellClicked function. I'm assuming you emit your signal from a place that has access to a QMouseEvent. Check out this thre...
Which button was clicked?
How can I detect which mouse button was clicked (right or left) in the slot for QtCore.SIGNAL('cellClicked(int,int)')?
[ "You would probably pass the event to your cellClicked function. I'm assuming you emit your signal from a place that has access to a QMouseEvent.\nCheck out this thread.\nExcerpt:\ndef mousePressEvent(self, event):\n if event.button() == QtCore.Qt.RightButton:\n event.accept()\n self.rightClickMen...
[ 0 ]
[]
[]
[ "pyqt4", "python", "qtablewidget" ]
stackoverflow_0002810074_pyqt4_python_qtablewidget.txt
Q: using an alternative string quotation syntax in python Just wondering... I find using escape characters too distracting. I'd rather do something like this (console code): >>> print ^'Let's begin and end with sets of unlikely 2 chars and bingo!'^ Let's begin and end with sets of unlikely 2 chars and bingo! Note t...
using an alternative string quotation syntax in python
Just wondering... I find using escape characters too distracting. I'd rather do something like this (console code): >>> print ^'Let's begin and end with sets of unlikely 2 chars and bingo!'^ Let's begin and end with sets of unlikely 2 chars and bingo! Note the ' inside the string, and how this syntax would have no is...
[ "Python has this use \"\"\" or ''' as the delimiters\nprint '''Let's begin and end with sets of unlikely 2 chars and bingo'''\n\nHow often do you have both of 3' and 3\" in a string\n" ]
[ 13 ]
[]
[]
[ "python", "quotations", "string", "syntax" ]
stackoverflow_0002813638_python_quotations_string_syntax.txt
Q: python : in which timezone is it a specific time right now? i have users from all timezones, and i want to send out alerts at around 8AM in each users respective timezone. i need a python script that runs every hour [in a cron job] and i need to find out at which timezone it is 8AM right now, and i can use that i...
python : in which timezone is it a specific time right now?
i have users from all timezones, and i want to send out alerts at around 8AM in each users respective timezone. i need a python script that runs every hour [in a cron job] and i need to find out at which timezone it is 8AM right now, and i can use that info to select the users that have to receive the alerts. how do i...
[ "Python defines a tzinfo class that gives you the offset of a time zone, but it doesn't provide any concrete implementation of the class. There are a few implementations available, I've used python-dateutil successfully. Obviously you'll need a time zone for each user; at the hourly (or half-hourly) run, take the c...
[ 1, 0 ]
[]
[]
[ "python", "timezone" ]
stackoverflow_0002813745_python_timezone.txt
Q: How do you check the presence of many keys in a Python dictionary? I have the following dictionary: sites = { 'stackoverflow': 1, 'superuser': 2, 'meta': 3, 'serverfault': 4, 'mathoverflow': 5 } To check if there are more than one key available in the above dictionary, I will do something like...
How do you check the presence of many keys in a Python dictionary?
I have the following dictionary: sites = { 'stackoverflow': 1, 'superuser': 2, 'meta': 3, 'serverfault': 4, 'mathoverflow': 5 } To check if there are more than one key available in the above dictionary, I will do something like: 'stackoverflow' in sites and 'serverfault' in sites The above is main...
[ "You can pretend the keys of the dict are a set, and then use set.issubset:\nset(['stackoverflow', 'serverfault']).issubset(sites) # ==> True\n\nset(['stackoverflow', 'google']).issubset(sites) # ==> False\n\n", "You could use all:\nprint( all(site in sites for site in ('stackoverflow','meta')) )\n# True\nprint( ...
[ 12, 9, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0002813806_python.txt
Q: Python MD5 Hash Faster Calculation I will try my best to explain my problem and my line of thought on how I think I can solve it. I use this code for root, dirs, files in os.walk(downloaddir): for infile in files: f = open(os.path.join(root,infile),'rb') filehash = hashlib.md5() while True: ...
Python MD5 Hash Faster Calculation
I will try my best to explain my problem and my line of thought on how I think I can solve it. I use this code for root, dirs, files in os.walk(downloaddir): for infile in files: f = open(os.path.join(root,infile),'rb') filehash = hashlib.md5() while True: data = f.read(10240) if len(dat...
[ "Hash calculation in your case will almost certanly be I/O bound (unless you'll be running it on a machine with a really slow processor), so multithreading or processing of multiple files at once probably won't yield you expected results.\nArraging files over multiple drives or on a faster (SSD) drive would probabl...
[ 4, 2, 2, 2 ]
[]
[]
[ "md5", "multicore", "multithreading", "python" ]
stackoverflow_0002813635_md5_multicore_multithreading_python.txt
Q: How can I implement "real time" messaging on Google AppEngine? I'm creating a web application on Google AppEngine where I want the user to be notified a quickly as possible after certain events occour. The problem is similar to say a chat server in that I need something happening on one connection (someone is writ...
How can I implement "real time" messaging on Google AppEngine?
I'm creating a web application on Google AppEngine where I want the user to be notified a quickly as possible after certain events occour. The problem is similar to say a chat server in that I need something happening on one connection (someone is writing a message in a chat room) to propagate to a number of other conn...
[ "Requests on App Engine are limited to 30 seconds execution time, which makes long polling difficult. Further, you need to keep your average execution time low, or you will very quickly run out of instances to execute your queries - App Engine will only provision new instances if your app is reasonably fast. For th...
[ 4, 1, 1 ]
[]
[]
[ "comet", "google_app_engine", "javascript", "python" ]
stackoverflow_0002660316_comet_google_app_engine_javascript_python.txt
Q: How to pack python files and its dependencies in a single executable file? I've got a piece of software which consists of several python sources and a couple of c++ libraries. I'd like to pack them in a executable single file, just like java does with .jar files. Is there a way to do that? A: You may want to hav...
How to pack python files and its dependencies in a single executable file?
I've got a piece of software which consists of several python sources and a couple of c++ libraries. I'd like to pack them in a executable single file, just like java does with .jar files. Is there a way to do that?
[ "You may want to have a look at py2exe, pyInstaller or others.\n", "Sure is.\n", "You can use python egg files, they are very similar to java jar files.\nhttp://mrtopf.de/blog/python_zope/a-small-introduction-to-python-eggs/\n" ]
[ 10, 3, 0 ]
[]
[]
[ "archive", "executable", "libraries", "python" ]
stackoverflow_0002813229_archive_executable_libraries_python.txt
Q: parsing a string of ascii text into separate variables I have a piece of text that gets handed to me like: here is line one\n\nhere is line two\n\nhere is line three What I would like to do is break this string up into three separate variables. I'm not quite sure how one would go about accomplishing this in pyth...
parsing a string of ascii text into separate variables
I have a piece of text that gets handed to me like: here is line one\n\nhere is line two\n\nhere is line three What I would like to do is break this string up into three separate variables. I'm not quite sure how one would go about accomplishing this in python. Thanks for any help, jml
[ "a, b, c = s.split('\\n\\n')\n\n", "s1, s2, s3 = that_string_variable.split('\\n\\n')\n\nBasically, whatever variable you've got that string in, you then .split() on the token you want to use as the separator (in this case, '\\n\\n'), and that will return a list of strings. You can assign using \"unpacking\" whe...
[ 4, 1, 1, 0 ]
[]
[]
[ "parsing", "python", "string", "tokenize" ]
stackoverflow_0002814738_parsing_python_string_tokenize.txt
Q: writing pexpect like program in c++ on Linux Is there any way of writing pexpect like small program which can launch a process and pass the password to that process? I don't want to install and use pexpect python library but want to know the logic behind it so that using linux system apis I can build something sim...
writing pexpect like program in c++ on Linux
Is there any way of writing pexpect like small program which can launch a process and pass the password to that process? I don't want to install and use pexpect python library but want to know the logic behind it so that using linux system apis I can build something similar.
[ "You could just use \"expect\". It is very light weight and is made to do what youre describing.\n", "For very simple cases, empty is one option. It's a lightweight C program, and it can be used straight from a shell script and doesn't require Tcl.\nFor Debian/Ubuntu, the package is empty-expect.\n" ]
[ 2, 0 ]
[]
[]
[ "c++", "linux", "pexpect", "python" ]
stackoverflow_0001982788_c++_linux_pexpect_python.txt
Q: How can I make the PyDev editor selectively ignore errors? I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ISubInterface The problem is that PyDev will always flag this...
How can I make the PyDev editor selectively ignore errors?
I'm using PyDev under Eclipse to write some Jython code. I've got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ISubInterface The problem is that PyDev will always flag this as an error and say "Unresolved import: ISubInterface". The co...
[ "You can add a comment\n#@UnresolvedImport\n#@UnusedVariable\n\nSo your import becomes:\nimport com.work.project.component.client.Interface.ISubInterface as ISubInterface #@UnresolvedImport\n\nThat should remove the error/warning. There are other comments you can add as well.\n", "Add the hash character # at the ...
[ 57, 30, 6 ]
[ "It is not a PYTHONPATH issue. It is related to importing/using static class-internal members of a Java class. I am getting the same sort of thing all over the place e.g. when trying to use constants in java.awt.Color:\nimport java.awt.Color as Color\nborderColor = Color.BLACK # get \"Undefined variable from impo...
[ -1 ]
[ "jython", "pydev", "python", "python_import" ]
stackoverflow_0001702043_jython_pydev_python_python_import.txt
Q: parsing a string based on specified identifiers Let's say that I have the following text: input = "one aaa and bbb two bbbb er ... // three cccc" I would like to parse this into a group of variables that contain criteria = ["one", "two", "three"] v1,v2,v3 = input.split(criteria) I know that the example above wo...
parsing a string based on specified identifiers
Let's say that I have the following text: input = "one aaa and bbb two bbbb er ... // three cccc" I would like to parse this into a group of variables that contain criteria = ["one", "two", "three"] v1,v2,v3 = input.split(criteria) I know that the example above won't work, but is there some utility in python that wo...
[ "Not terribly elegant but it works:\n>>> s\n'one aaa two bbbb three cccc'\n>>> re.split(r\"\\s*(?:one|two|three)\\s*\", s)\n['', 'aaa', 'bbbb', 'cccc']\n\nThe ?: keeps it from returning the delimiting identifiers in the results.\n", "So, so ugly, but it should do what you need:\ni1 = iter(input.split())\ni2 = ite...
[ 1, 1 ]
[]
[]
[ "parsing", "python", "string" ]
stackoverflow_0002814948_parsing_python_string.txt
Q: Django site on Nginx+FastCGI goes (504 gateway timeout) Sometimes my whole Django based site goes into 504 gateway timeout errors so none page can be displayed. Is it possible to write a shell program and cronjob it run every 5 minutes to detect such errors and restart FastCGI process if needed? I'm currently usin...
Django site on Nginx+FastCGI goes (504 gateway timeout)
Sometimes my whole Django based site goes into 504 gateway timeout errors so none page can be displayed. Is it possible to write a shell program and cronjob it run every 5 minutes to detect such errors and restart FastCGI process if needed? I'm currently using command below to restart FastCGI in case it's crashed but i...
[ "Perhaps you should find out why the site starts serving 504 errors first - check the logs (or add logging if you don't have enough information), and fix whatever the problem is. Alternatively, you may find nginx + apache + mod_wsgi a more stable approach - nginx is a fantastic front-end webserver for serving stati...
[ 3, 0 ]
[]
[]
[ "django", "fastcgi", "python", "restart", "timeout" ]
stackoverflow_0002466963_django_fastcgi_python_restart_timeout.txt
Q: Common coding style for Python? I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now. 1.- What is the most widely used column width? (the eternal question) I'm currently sticki...
Common coding style for Python?
I'm pretty new to Python, and I want to develop my first serious open source project. I want to ask what is the common coding style for python projects. I'll put also what I'm doing right now. 1.- What is the most widely used column width? (the eternal question) I'm currently sticking to 80 columns (and it's a pain!) 2...
[ "PEP 8 is pretty much \"the root\" of all common style guides.\nGoogle's Python style guide has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular four-space ones, and the CamelCase style for functions and methods instead of the camel_case style, ar...
[ 20, 2, 1 ]
[]
[]
[ "coding_style", "column_width", "indentation", "naming_conventions", "python" ]
stackoverflow_0002815272_coding_style_column_width_indentation_naming_conventions_python.txt
Q: Given a date range how to calculate the number of weekends partially or wholly within that range? Given a date range how to calculate the number of weekends partially or wholly within that range? (A few definitions as requested: take 'weekend' to mean Saturday and Sunday. The date range is inclusive i.e. the end d...
Given a date range how to calculate the number of weekends partially or wholly within that range?
Given a date range how to calculate the number of weekends partially or wholly within that range? (A few definitions as requested: take 'weekend' to mean Saturday and Sunday. The date range is inclusive i.e. the end date is part of the range 'wholly or partially' means that any part of the weekend falling within the da...
[ "General approach for this kind of thing:\nFor each day of the week, figure out how many days are required before a period starting on that day \"contains a weekend\". For instance, if \"contains a weekend\" means \"contains both the Saturday and the Sunday\", then we have the following table:\nSunday: 8\nMonday: 7...
[ 5, 2, 1, 0 ]
[]
[]
[ "date", "date_arithmetic", "python" ]
stackoverflow_0000883615_date_date_arithmetic_python.txt
Q: Having trouble with time.sleep When I run, for example: print("[",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.slee...
Having trouble with time.sleep
When I run, for example: print("[",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1) print("=",end=" ") time.sleep(1...
[ "Try flushing stdout after each print:\nimport sys\n\nprint(\"=\",end=\" \")\nsys.stdout.flush()\n\n", "Actually, a progress bar belongs to sys.stderr, which is (very conveniently and not coincidentally at all) not buffered. So I suggest you:\nprint(\"=\", end=\" \", file=sys.stderr)\n\ninstead.\nPS a synopsis of...
[ 5, 3, 0, 0 ]
[]
[]
[ "buffering", "python", "python_3.x" ]
stackoverflow_0002814933_buffering_python_python_3.x.txt
Q: converting a treebank of vertical trees to s-expressions I have a collection of parse trees, and they are in this ascii representation where indentation determines the structure (and closing brackets are implicit). I need to convert them to s-expressions so that parentheses determine the structure. It's a little b...
converting a treebank of vertical trees to s-expressions
I have a collection of parse trees, and they are in this ascii representation where indentation determines the structure (and closing brackets are implicit). I need to convert them to s-expressions so that parentheses determine the structure. It's a little bit like python's significant whitespace vs. braces. The input ...
[ "Focusing only on the example you're giving in this Q, and the Q's title about converting vertical trees to S-expressions, something like...:\nimport re\nimport sys\n\nsamp='''S\n=NP\n==(DT +def) the\n== (N +ani) man\n=VP\n==V walks'''.splitlines()\n\nrelinelev = re.compile(r'(=*)(.*)')\nreclean = re.compile(r'\\s*...
[ 1 ]
[]
[]
[ "corpus", "python" ]
stackoverflow_0002815020_corpus_python.txt
Q: Cleaning up temp folder after long-running subprocess exits I have a Python script (running inside another application) which generates a bunch of temporary images. I then use subprocess to launch an application to view these. When the image-viewing process exists, I want to remove the temporary images. I can't do...
Cleaning up temp folder after long-running subprocess exits
I have a Python script (running inside another application) which generates a bunch of temporary images. I then use subprocess to launch an application to view these. When the image-viewing process exists, I want to remove the temporary images. I can't do this from Python, as the Python process may have exited before t...
[ "If you're on any variant of Unix, you could fork your Python program, and have the parent process go on with its life while the child process daemonized, runs the viewer (doesn't matter in the least if that blocks the child process, which has no other job in life anyway;-), and cleans up after it. The original Py...
[ 1 ]
[]
[]
[ "python", "subprocess", "temporary_files" ]
stackoverflow_0002815665_python_subprocess_temporary_files.txt
Q: reloading module, need to re-compile sub modules? sorry, im sure this is asked a bunch, but i couldnt find it. in myModule.py: from myModule.subModule import myClass i am working on myClass, and want to stay in my ipython session and test it. reload(myModule) doesnt re-compile myClass. how can i do this? A: Yo...
reloading module, need to re-compile sub modules?
sorry, im sure this is asked a bunch, but i couldnt find it. in myModule.py: from myModule.subModule import myClass i am working on myClass, and want to stay in my ipython session and test it. reload(myModule) doesnt re-compile myClass. how can i do this?
[ "You need to repeat your imports after reloading the \"leafmost\" submodule. E.g., given:\n$ mkdir myModule\n$ touch myModule/__init__.py\n$ cat >myModule/subModule.py\nclass MyClass(object): kind='first'\n\nand then\n>>> from myModule.subModule import MyClass\n>>> MyClass.kind\n'first'\n\nand in another terminal\n...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0002814609_python.txt
Q: Difference between Python urllib.urlretrieve() and wget I am trying to retrieve a 500mb file using Python, and I have a script which uses urllib.urlretrieve(). There seems to some network problem between me and the download site, as this call consistently hangs and fails to complete. However, using wget to retriev...
Difference between Python urllib.urlretrieve() and wget
I am trying to retrieve a 500mb file using Python, and I have a script which uses urllib.urlretrieve(). There seems to some network problem between me and the download site, as this call consistently hangs and fails to complete. However, using wget to retrieve the file tends to work without problems. What is the differ...
[ "The answer is quite simple. Python's urllib and urllib2 are nowhere near as mature and robust as they could be. Even better than wget in my experience is cURL. I've written code that downloads gigabytes of files over HTTP with file sizes ranging from 50 KB to over 2 GB. To my knowledge, cURL is the most reliab...
[ 17, 2 ]
[]
[]
[ "download", "python", "urllib", "wget" ]
stackoverflow_0002777116_download_python_urllib_wget.txt