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: Regular Expressions to parse template tags in XML I need to parse some XML to pull out embedded template tags for further parsing. I can't seem to bend Python's regular expressions to do what I want, though. In English: when a template tag is contained anywhere in the row, remove all the XML for that specific row...
Regular Expressions to parse template tags in XML
I need to parse some XML to pull out embedded template tags for further parsing. I can't seem to bend Python's regular expressions to do what I want, though. In English: when a template tag is contained anywhere in the row, remove all the XML for that specific row and leave only the template tag in its place. I put to...
[ "Please don't use regular expressions for this problem.\nI'm serious, parsing XML with a regex is hard, and it makes your code 50x less maintainable by anyone else.\nlxml is the defacto tool that pythonistas use to parse XML... take a look at this article on Stack Overflow for sample usage. Or consider this answer...
[ 4, 3 ]
[]
[]
[ "lxml", "python", "regex", "xml" ]
stackoverflow_0005878055_lxml_python_regex_xml.txt
Q: How to configure the webserver to server a particular page as the default page? I am using Lighttpd and Django. I have configured my Lighttpd server to pass all the requests ending with ".psp" extension to Django. My startup page is a page served through Django, which is accessed as "http://192.168.1.198/home.psp"...
How to configure the webserver to server a particular page as the default page?
I am using Lighttpd and Django. I have configured my Lighttpd server to pass all the requests ending with ".psp" extension to Django. My startup page is a page served through Django, which is accessed as "http://192.168.1.198/home.psp". I want to enable the user to browse this page without writing "home.psp" explicitly...
[ "I think you're confusing concepts here between the \"old\" method of having individual files represent web pages which themselves contain code that is passed off to an interpreter before being sent in a response to how django/frameworks work.\nIf you're familiar with apache, imagine django as in part taking on the...
[ 1, 0, 0 ]
[]
[]
[ "django", "lighttpd", "python" ]
stackoverflow_0004825787_django_lighttpd_python.txt
Q: Traversing object hierarchy pickle style I'm in a need for doing some sort of processing on the objects that get pickled just before it happens. More precisely for instances of subclasses of a certain base class I would like something totally different to be pickled instead and then recreated on loading. I'm aware...
Traversing object hierarchy pickle style
I'm in a need for doing some sort of processing on the objects that get pickled just before it happens. More precisely for instances of subclasses of a certain base class I would like something totally different to be pickled instead and then recreated on loading. I'm aware of __getstate__ & __setstate__ however this i...
[ "The only additional hooks that are related are reduce() and __reduce__ex()\nhttp://docs.python.org/library/pickle.html\nWhat is the difference between __reduce__ and __reduce_ex__?\nPython: Ensuring my class gets pickled only with the latest protocol\nNot sure if they really provide what you need in particular.\n"...
[ 2 ]
[]
[]
[ "celery", "django", "pickle", "python", "serialization" ]
stackoverflow_0005878830_celery_django_pickle_python_serialization.txt
Q: Posting an Intent from Python scripts using Monkey/Monkey Runner I am trying to test my apps using python and monkey runner. I want to send an intent during start activity. I tried using extras and this doesnt help. Can some one help me with this? If possible can some one provide me a sample AndroidManifest.xml an...
Posting an Intent from Python scripts using Monkey/Monkey Runner
I am trying to test my apps using python and monkey runner. I want to send an intent during start activity. I tried using extras and this doesnt help. Can some one help me with this? If possible can some one provide me a sample AndroidManifest.xml and test.py on how to do this. Thank you all for the help blr p sh
[ "There are some bugs in monkeyrunner avoiding correct handling of extras. This question also mentions the case passing booleans, but it's not restricted to them.\nThe workaround, as monkeyrunner does not do much that invoking ADB in this cases is to use\ndevice.shell('am start -a android.intent.action.MAIN -n my.pk...
[ 0 ]
[]
[]
[ "android", "android_intent", "monkeyrunner", "python" ]
stackoverflow_0005875817_android_android_intent_monkeyrunner_python.txt
Q: how to make the width and height x2 using python Regular i have to do many work to change like this: <img src = "/" height="111" width="10" /> to <img src = "/" height="222" width="20" /> so i want to use python Regular this is my code : import re s = '<img src = "werwerwe" height="111" width="10" />' def a(x...
how to make the width and height x2 using python Regular
i have to do many work to change like this: <img src = "/" height="111" width="10" /> to <img src = "/" height="222" width="20" /> so i want to use python Regular this is my code : import re s = '<img src = "werwerwe" height="111" width="10" />' def a(x): print x.group(2) print x.group(4) ss = re.sub(r'''...
[ "Don't use regular expressions to parse HTML. Use BeautifulSoup\n>>> from BeautifulSoup import BeautifulSoup\n>>> ht = '<html><head><title>foo</title></head><body><p>whatever: <img src=\"foo/img.png\" height=\"111\" width=\"22\" /></p><ul><li><img src=\"foo/img2.png\" height=\"32\" width=\"44\" /></li></ul></body><...
[ 4, 2, 2, 1, 1, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005877717_python_regex.txt
Q: Weird: logger only uses the formatter of the first handler for exceptions I'm witnessing the logging module behaving in a funny way. Am I missing something ? I'm doing the usual thing of having two handlers: a StreamHandler for logging only INFO and higher to the console, and a FileHandler that will also handle a...
Weird: logger only uses the formatter of the first handler for exceptions
I'm witnessing the logging module behaving in a funny way. Am I missing something ? I'm doing the usual thing of having two handlers: a StreamHandler for logging only INFO and higher to the console, and a FileHandler that will also handle all the DEBUG information. It worked fine until I decided to have a different fo...
[ "This is the code I came up with. It does the job :).\nclass CachelessFormatter(logging.Formatter):\n # I came up with that after reading the answers to\n # http://stackoverflow.com/questions/5875225/\n # which pointed me to\n # http://bugs.python.org/issue6435\n # I still think Vinay Sajip ...
[ 9, 5, 1 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0005875225_logging_python.txt
Q: How do I install Python Imaging Library on Mac OS X? I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've bee...
How do I install Python Imaging Library on Mac OS X?
I'm an extremely amateur programmer; I've done some recreational algorithmics programming, but I honestly have no idea how libraries and programming languages really fit together. I'm supposed to work on a project that requires some image processing, so I've been trying to install PIL for a while, but I haven't been ab...
[ "Actually, assuming you're still using the default 2.5.x Python that comes with OS X (at least as of 10.5.6), there's a pre-built installer package for it (download the dmg for PIL).\nOtherwise, you'll need to either build it from source -- which does require the mac dev tools -- or install it with MacPorts or fink...
[ 4, 3, 0, 0 ]
[]
[]
[ "macos", "module", "python" ]
stackoverflow_0000903242_macos_module_python.txt
Q: What is the role of the Empty production for PEGs? The empty production rule nonterminal -> epsilon is useful in lex-yacc LR bottom up parser generators (e.g. PLY). In what context should one use Empty productions in PEG parsers e.g. pyparsing ? A: BNF's often use empty as an alternative, effectively making the...
What is the role of the Empty production for PEGs?
The empty production rule nonterminal -> epsilon is useful in lex-yacc LR bottom up parser generators (e.g. PLY). In what context should one use Empty productions in PEG parsers e.g. pyparsing ?
[ "BNF's often use empty as an alternative, effectively making the overall expression optional:\nleading_sign ::= + | - | empty\ninteger ::= leading_sign digit...\n\nThis is unnecessary in pyparsing, since pyparsing includes the Optional class for this:\n# no empty required\nleading_sign = Optional(oneOf(\"+ -\"))\ni...
[ 5 ]
[]
[]
[ "peg", "ply", "pyparsing", "python" ]
stackoverflow_0005879340_peg_ply_pyparsing_python.txt
Q: Will using less calls to functions increase speed of total execution? Possible Duplicate: Does creating separate functions instead of one big one slow processing time? OOP Bloop boop! Yes, OOP is great, keeps code clean and well organized. That's why I like to use it. I"m referring to to OOP very primitively spe...
Will using less calls to functions increase speed of total execution?
Possible Duplicate: Does creating separate functions instead of one big one slow processing time? OOP Bloop boop! Yes, OOP is great, keeps code clean and well organized. That's why I like to use it. I"m referring to to OOP very primitively specifically in using functions (defs). Will taking out my function calls and...
[ "Write it correctly (i.e. with concerns properly separated into distinct functions and classes), then use PyPy to make it fast.\nPyPy uses function inlining and assorted other tricks in its Just-In-Time compiler to speed up code execution without having to make it unmaintainable in the name of speed.\nNote that thi...
[ 3, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005877516_python.txt
Q: cvUpdateMotionHistory in Python/OpenCV I want to use the function cv.UpdateMotionHistory in my python/opencv application.Using the new python interface: UpdateMotionHistory(silhouette,mhi,timestamp,duration)-> None Here how to the parameter timestamp? in C, I can simply use built-in function clock(). In python, I...
cvUpdateMotionHistory in Python/OpenCV
I want to use the function cv.UpdateMotionHistory in my python/opencv application.Using the new python interface: UpdateMotionHistory(silhouette,mhi,timestamp,duration)-> None Here how to the parameter timestamp? in C, I can simply use built-in function clock(). In python, I try to use time.time(), but it fails. I try...
[ "import time\nCLOCKS_PER_SEC = 1.0\nseconds = time.clock() / CLOCKS_PER_SEC\n\n" ]
[ 2 ]
[]
[]
[ "opencv", "python" ]
stackoverflow_0005879471_opencv_python.txt
Q: Run python script without the "python" keyword How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files? Right now I have to do this: python script.py What I like to do is this: script.py A: Add a shebang: #!/usr/bin/python or #!/usr/bi...
Run python script without the "python" keyword
How can I run a python script in Terminal on Mac without using the "python" keyword, without having to edit my existing python files? Right now I have to do this: python script.py What I like to do is this: script.py
[ "Add a shebang:\n#!/usr/bin/python\n\nor\n#!/usr/bin/env python\n\nI prefer the second one, since Python can be anywhere like /usr/bin/python, /usr/local/bin/python etc. and second one ensure that you don't have to keep editing the shebang.\nAnd then you can just execute it as ./script.py if it is executable.\n", ...
[ 19, 16, 5 ]
[]
[]
[ "macos", "python", "terminal" ]
stackoverflow_0005879869_macos_python_terminal.txt
Q: Python * imports I've generally been told that the following is bad practice. from module import * The main reasoning (or so I've been told), is that you could possibly import something you didn't want, and it could shadow a similarly named function or class from another module. However, what about PyQt from PyQt...
Python * imports
I've generally been told that the following is bad practice. from module import * The main reasoning (or so I've been told), is that you could possibly import something you didn't want, and it could shadow a similarly named function or class from another module. However, what about PyQt from PyQt4.QtCore import * Eve...
[ "This can sort of turn into a religious war. It's a matter of whether you want to be explicit or whether you want to avoid being too verbose. In general, following the Zen of Python, it's better to be explicit, but sometimes people just don't find it practical to list every import from particular module.\n", "My ...
[ 9, 5, 5, 3, 3, 3, 2, 1 ]
[]
[]
[ "pyqt", "python", "python_import" ]
stackoverflow_0005877218_pyqt_python_python_import.txt
Q: Python + Twisted + sqlanydb = abort() I'm using Twisted 11 together with SQLAnywhere 12 via the official sqlanydb driver. Generally, it works fine. But occasionally the application crashes with an abort on the first query. If one query worked, all following work too. However my tests run only seldom through. That'...
Python + Twisted + sqlanydb = abort()
I'm using Twisted 11 together with SQLAnywhere 12 via the official sqlanydb driver. Generally, it works fine. But occasionally the application crashes with an abort on the first query. If one query worked, all following work too. However my tests run only seldom through. That's awful to develop with and strace doesn't ...
[ "It looks like your database library is not threadsafe. In order to make it a stable connection, do this:\nself.dbpool = ConnectionPool(..., cp_min=1, cp_max=1)\n\nThis will set the maximum concurrency to 1, and the ThreadPool will be limited to 1 thread, meaning that no queries will run simultaneously. This should...
[ 2, 1 ]
[]
[]
[ "python", "sqlanywhere", "twisted" ]
stackoverflow_0005790435_python_sqlanywhere_twisted.txt
Q: pseudo inverse of sparse matrix in python I am working with data from neuroimaging and because of the large amount of data, I would like to use sparse matrices for my code (scipy.sparse.lil_matrix or csr_matrix). In particular, I will need to compute the pseudo-inverse of my matrix to solve a least-square problem....
pseudo inverse of sparse matrix in python
I am working with data from neuroimaging and because of the large amount of data, I would like to use sparse matrices for my code (scipy.sparse.lil_matrix or csr_matrix). In particular, I will need to compute the pseudo-inverse of my matrix to solve a least-square problem. I have found the method sparse.lsqr, but it is...
[ "You could study more on the alternatives offered in scipy.sparse.linalg. \nAnyway, please note that a pseudo-inverse of a sparse matrix is most likely to be a (very) dense one, so it's not really a fruitful avenue (in general) to follow, when solving sparse linear systems.\nYou may like to describe a slight more ...
[ 9, 7 ]
[]
[]
[ "least_squares", "linear_algebra", "matrix_inverse", "python", "sparse_matrix" ]
stackoverflow_0005879986_least_squares_linear_algebra_matrix_inverse_python_sparse_matrix.txt
Q: python and mechanize - seeing the options in a select field My html form looks like this: <form name="someform"> <select name="someid"> <option value ="option1"> I'm trying to see all of the choices and be able to choose them. I can select the form like this: br.select_form("someform") I can print...
python and mechanize - seeing the options in a select field
My html form looks like this: <form name="someform"> <select name="someid"> <option value ="option1"> I'm trying to see all of the choices and be able to choose them. I can select the form like this: br.select_form("someform") I can print(br) and see the SelectControl that I want. If I do: print br["s...
[ "Using br.possible_items(\"someid\") gives you the list of options. \n", "I think what you want to do is to print br.form. This prints out ONLY the options in the form. Also, if anything in the form is a dropdown, then the options for that dropdown should also show up.\nYou could then use BeautifulSoup to parse t...
[ 3, 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0004811656_mechanize_python.txt
Q: How to start a Python script several functions in I have a Python script and I want to call it several functions down the script. Example code below: class Name(): def __init__(self): self.name = 'John' self.address = 'Place' self.age = '100' def printName(self): print sel...
How to start a Python script several functions in
I have a Python script and I want to call it several functions down the script. Example code below: class Name(): def __init__(self): self.name = 'John' self.address = 'Place' self.age = '100' def printName(self): print self.name def printAddress(self): print self....
[ "If you are asking how can you launch your python script and have it start executing at different positions then you will have to launch the script with some information on what you want it to do. The most common way to do this would be to add support for command line arguments.\nimport sys\n\nif __name__ == '__mai...
[ 3, 1, 0, 0 ]
[]
[]
[ "execute", "function", "python" ]
stackoverflow_0002855872_execute_function_python.txt
Q: SQLite Python AND statement not working I'm attempting to pull a list of rows from an SQLite database that are on a given day of the week and a certain hour of that day. When I open my sqlite browser and type the SQL: SELECT * FROM points WHERE strftime('%H', checkintime) == '12' AND strftime('%w', checkintime) ...
SQLite Python AND statement not working
I'm attempting to pull a list of rows from an SQLite database that are on a given day of the week and a certain hour of that day. When I open my sqlite browser and type the SQL: SELECT * FROM points WHERE strftime('%H', checkintime) == '12' AND strftime('%w', checkintime) == '1' It works and I receive all of the row...
[ "I reckon you have to convert your number parameters to strings, otherwise they won't get quoted as you do in your statement in sqlite. The variable substitution with ? does not quote numbers.\nYou are actually comparing strings, so you must convert the parameters to strings.\n", "The time and day values do need ...
[ 1, 1, 0, 0 ]
[]
[]
[ "database", "execute", "python", "sqlite" ]
stackoverflow_0005152172_database_execute_python_sqlite.txt
Q: Python GTK Listviews using Glade I am currently developing an application for my Linux desktop that reads data from my Garmin Forerunner sports watch, parses the not-so-well-formed XML file, and writes the data to a MySQL database table. I'm not overly experienced with Python or GTK, so the graphical stuff I hand...
Python GTK Listviews using Glade
I am currently developing an application for my Linux desktop that reads data from my Garmin Forerunner sports watch, parses the not-so-well-formed XML file, and writes the data to a MySQL database table. I'm not overly experienced with Python or GTK, so the graphical stuff I handled using the Glade GUI designer. Her...
[ "check if an example below would work for you. It loads ui from the glade file and uses sqlite database to store items.\nscript:\nimport gtk\nimport sqlite3\n\nclass ListViewTestApp:\n def __init__(self):\n builder = gtk.Builder()\n builder.add_from_file('listview_test.glade')\n builder.con...
[ 3, 0 ]
[]
[]
[ "garmin", "glade", "gtk", "pygtk", "python" ]
stackoverflow_0004925155_garmin_glade_gtk_pygtk_python.txt
Q: How do I remove html entities (and more) using lxml? I've got an html file that has some text that looks like this (after running it through lxml.html parse, lxml.html clean, and this is the result of etree.tostring(table, pretty_print=True)) <tr><td>&#13; 224&#13; 9:00 am&#13; -3:00 pm&#13; NPHC Leadership</td>&...
How do I remove html entities (and more) using lxml?
I've got an html file that has some text that looks like this (after running it through lxml.html parse, lxml.html clean, and this is the result of etree.tostring(table, pretty_print=True)) <tr><td>&#13; 224&#13; 9:00 am&#13; -3:00 pm&#13; NPHC Leadership</td>&#13; <td>&#13; <font>ALSO IN 223; WALL OPEN</font></td>&#1...
[ "Here is an example of stripping out all attributes and allowing only tags in [table, tr, td]. I've added a few Unicode entities for sake of illustration. \nDATA = '''<table border=\"1\"><tr colspan=\"4\"><td rowspan=\"2\">\\r\n224&#13;\n&#8220;hi there&#8221;\n9:00 am\\r\n-3:00 pm&#13;\nNPHC Leadership</td>\\r\n<...
[ 4, 3 ]
[]
[]
[ "html_parsing", "lxml", "python" ]
stackoverflow_0005875005_html_parsing_lxml_python.txt
Q: Browser caching with BottlePy/GAE I'm running Google Page Speed on my website which is in Python/Bottle on Google App Engine. It's saying: 'The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:' and then goes on to li...
Browser caching with BottlePy/GAE
I'm running Google Page Speed on my website which is in Python/Bottle on Google App Engine. It's saying: 'The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:' and then goes on to list most of my static files (images, css...
[ "If you have this in your code:\n@bottle.route('/static/:filename#.*#')\ndef static(filename):\n return bottle.static_file(filename, root='./static/')\n\nyou can add:\nresponse.headers['Cache-Control'] = 'public, max-age=SECONDS'\n\nin front of the return to enable caching in the browser. This also works for dyn...
[ 3 ]
[]
[]
[ "bottle", "browser_cache", "google_app_engine", "python" ]
stackoverflow_0005875171_bottle_browser_cache_google_app_engine_python.txt
Q: Twisted LoopingCall serialized when needed I am using a LoopingCall to get jobs to a worker every X seconds - but there might be times when the worker doesn't finish the previous job sooner that X seconds and then I want the LoopingCall to not get any new job. Basically I want a way to let the LoopingCall to wait ...
Twisted LoopingCall serialized when needed
I am using a LoopingCall to get jobs to a worker every X seconds - but there might be times when the worker doesn't finish the previous job sooner that X seconds and then I want the LoopingCall to not get any new job. Basically I want a way to let the LoopingCall to wait another round until it pulls the job.
[ "http://twistedmatrix.com/documents/current/api/twisted.internet.task.LoopingCall.html\nThe function your LoopingCall calls may return a deferred. Rescheduling will not occur until that deferred is fired.\nI'm having trouble understanding your post, but I think this is what you're after. Have your worker-function r...
[ 4 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0005880522_python_twisted.txt
Q: Multi tier architecture implementation on Python I need to create web application, which can be reached by user as regular web site and as XML-RPC web service. Also web site should have mobile version. I'm planning to use next technologies: Django (for web frontends (regular and mobile)). Pyramid (for web service...
Multi tier architecture implementation on Python
I need to create web application, which can be reached by user as regular web site and as XML-RPC web service. Also web site should have mobile version. I'm planning to use next technologies: Django (for web frontends (regular and mobile)). Pyramid (for web service). SQLAlchemy, Memcached (for persistence level) Late...
[ "This architecture really makes no sense. You're using Django, a full-stack web framework, for the front end, but not using it for the database. And you're using Pyramid, another full-stack web framework, for the web service side, thus ensuring that you duplicate all the business logic.\nMuch as I am an advocate of...
[ 4, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005880438_python.txt
Q: Python: List to tuple without " I am trying to use the Abaqus (a commercial FEA code) scripting interface to generate FE models, although my question is relating to Python specifically, but a bit of background on why I am trying to do this. Abaqus has a built in boolean merge operation that requires the following...
Python: List to tuple without "
I am trying to use the Abaqus (a commercial FEA code) scripting interface to generate FE models, although my question is relating to Python specifically, but a bit of background on why I am trying to do this. Abaqus has a built in boolean merge operation that requires the following syntax to be used: a.InstanceFromBoo...
[ "You're close, try:\nfor i in range(4):\n val = a.instances[\"name_\"+str(i)]\n my_list.append(val)\n\nYou can make this even shorter using a generator expression:\nmy_list = tuple(a.instances[\"name_\"+str(i)] for i in range(4))\n\n", "Those characters will be printed out simply because you're printing out...
[ 3, 1 ]
[]
[]
[ "python", "tuples" ]
stackoverflow_0005881309_python_tuples.txt
Q: delay in python I Created a quiz game on python, where basically the user answers some questions i randomly made up and after that they press enter, it will say " calculating you smartness " and will show a random number on your screen. problem is,everytime the user press enter it will say "calculating your smart...
delay in python
I Created a quiz game on python, where basically the user answers some questions i randomly made up and after that they press enter, it will say " calculating you smartness " and will show a random number on your screen. problem is,everytime the user press enter it will say "calculating your smartness" and shows the n...
[ "time module's sleep()\nAlso, you already have it imported for some reason.\n", "use time.sleep(secs), see here: http://docs.python.org/library/time.html#time.sleep\n", "You're looking for time.sleep().\n" ]
[ 2, 1, 1 ]
[]
[]
[ "delay", "python", "timer" ]
stackoverflow_0005881605_delay_python_timer.txt
Q: pyqt: connect signal dynamically with user-supplied variables? I create a dialog with a custom class: d = ModifyRect(ctrl_name, rect_name) It is shown modelessly. When it is accepted or rejected, I want to call a function on my MainWindow passing in these two variables, i.e. this slot should be called: @QtCore.py...
pyqt: connect signal dynamically with user-supplied variables?
I create a dialog with a custom class: d = ModifyRect(ctrl_name, rect_name) It is shown modelessly. When it is accepted or rejected, I want to call a function on my MainWindow passing in these two variables, i.e. this slot should be called: @QtCore.pyqtSlot("QString","QString") def modifyRectAccepted(self, ctrl_name, ...
[ "You cannot do that directly. You need to use signal mapper or intermediate slot. See this question answered a few days ago.\nOr, if you're just interested in the source of the signal, use QObject's sender() method.\nEDIT:\nTo use closures as intermediate slots you must use the New-syle signal and slot paradigm. Th...
[ 3 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qt4" ]
stackoverflow_0005876807_pyqt_pyqt4_python_qt_qt4.txt
Q: Expose _hashlib.pyd internals for EVP_MD_CTX? Anyone know how to expose python 2.x _hashlib.pyd internals using ctypes? I especially need to extract the EVP_MD_CTX struct for serialization of python HASH objects. A: Mapping C structures from header files (openssl/evp.h and _hashopenssl.c in your case) is straigh...
Expose _hashlib.pyd internals for EVP_MD_CTX?
Anyone know how to expose python 2.x _hashlib.pyd internals using ctypes? I especially need to extract the EVP_MD_CTX struct for serialization of python HASH objects.
[ "Mapping C structures from header files (openssl/evp.h and _hashopenssl.c in your case) is straightforward, but is not always portable across different versions. Here it is for my environment:\nfrom ctypes import *\n\nPyObject_HEAD = [\n ('ob_refcnt', c_size_t),\n ('ob_type', c_void_p),\n]\n\nclass EVP_MD(Str...
[ 3 ]
[]
[]
[ "ctypes", "hashlib", "python", "serialization" ]
stackoverflow_0005880456_ctypes_hashlib_python_serialization.txt
Q: PyGame Circular Collision Issues - Circle Interior I'm making a puzzle game that requires the user to 'draw' circles onto a background to get a ball to the exit. They create circles by holding their mouse button, the circle grows; when it is big enough, they let go and it is 'punched' into the physical space and b...
PyGame Circular Collision Issues - Circle Interior
I'm making a puzzle game that requires the user to 'draw' circles onto a background to get a ball to the exit. They create circles by holding their mouse button, the circle grows; when it is big enough, they let go and it is 'punched' into the physical space and balls then react to it. I have a problem, however, that w...
[ "The problem is with unintended hits rather than missed ones. What you really want to check is if all parts of the ball are covered by some circle, while the check you're doing is if any circle only partially overlaps - but an override if any circle fully covers the ball. \nI figure for any potential hit point, i.e...
[ 1, 0 ]
[]
[]
[ "collision_detection", "game_physics", "physics", "pygame", "python" ]
stackoverflow_0005879856_collision_detection_game_physics_physics_pygame_python.txt
Q: How to close a socket left open by a killed program? I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown tim...
How to close a socket left open by a killed program?
I have a Python application which opens a simple TCP socket to communicate with another Python application on a separate host. Sometimes the program will either error or I will directly kill it, and in either case the socket may be left open for some unknown time. The next time I go to run the program I get this error:...
[ "Assume your socket is named s... you need to set socket.SO_REUSEADDR on the server's socket before binding to an interface... this will allow you to immediately restart a TCP server...\ns.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ns.bind((ADDR, PORT))\n\n", "You might want to try using Twisted for y...
[ 53, 12, 5 ]
[]
[]
[ "linux", "networking", "python", "sockets", "tcp" ]
stackoverflow_0005875177_linux_networking_python_sockets_tcp.txt
Q: Python's string.strip() weird behavior I got a string looking like that: EVENTS: RAID Volume Set Information Volume Set Name : ARC-1120-VOL#00 Raid Set Name : Raid Set # 00 Volume Capacity : 1.0GB SCSI Ch/Id/Lun : 00/00/00 Raid Level : Raid5 Stripe Size : 64K Member Disks : 3 Cache Mode : ...
Python's string.strip() weird behavior
I got a string looking like that: EVENTS: RAID Volume Set Information Volume Set Name : ARC-1120-VOL#00 Raid Set Name : Raid Set # 00 Volume Capacity : 1.0GB SCSI Ch/Id/Lun : 00/00/00 Raid Level : Raid5 Stripe Size : 64K Member Disks : 3 Cache Mode : Write Back Tagged Queuing : Enabled Volume ...
[ "Because the argument of strip is the string of characters to remove and yours includes \"V\".\nWhy are you passing it that string anyways?\n", "Did you read the documentation of strip()?\nIt strips of any number of characters that you provided, so .strip(\"EVENTS: RAID\\n\") strips of every E, every V, every E, ...
[ 3, 2, 1, 1, 0 ]
[]
[]
[ "python", "string", "strip" ]
stackoverflow_0005882006_python_string_strip.txt
Q: Python: pass method as argument in function I've seen a lot of posts but none really addressing my question. With Python, I am trying to pass a method as an argument in a function which requires two arguments: # this is a method within myObject def getAccount(self): account = (self.__username, self.__password)...
Python: pass method as argument in function
I've seen a lot of posts but none really addressing my question. With Python, I am trying to pass a method as an argument in a function which requires two arguments: # this is a method within myObject def getAccount(self): account = (self.__username, self.__password) return account # this is a function from a s...
[ "You want to use python argument unpacking:\nmyData = myModule.logIn( * myObject.getAccount() )\n\nThe * before an argument to a function signals that the following tuple should be split into its constituents and passed as positional arguments to the function.\nOf course, you could do this by hand, or write a wrapp...
[ 8, 6, 4, 3 ]
[]
[]
[ "arguments", "methods", "python" ]
stackoverflow_0005881615_arguments_methods_python.txt
Q: Python web scraping involving HTML tags with attributes I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following: <html> <body> <div id="container"> <div id="contents"> <table> <tbody> <tr> <td class="author">####I ...
Python web scraping involving HTML tags with attributes
I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following: <html> <body> <div id="container"> <div id="contents"> <table> <tbody> <tr> <td class="author">####I want whatever is located here ###</td> </tr> </tbody> </table...
[ "It's not clear to me from your question why you need to worry about the div tags -- what about doing just:\nsoup = BeautifulSoup(html)\nthetd = soup.find('td', attrs={'class': 'author'})\nprint thetd.string\n\nOn the HTML you give, running this emits exactly:\n####I want whatever is located here ###\n\nwhich appea...
[ 12, 6, 5, 1 ]
[]
[]
[ "beautifulsoup", "lxml", "python", "screen_scraping" ]
stackoverflow_0001391657_beautifulsoup_lxml_python_screen_scraping.txt
Q: how to make python mechanize ignore dropdown constraints I'm trying to use python mechanize to fill data into a webpage from an excel file. b = Browser() b.open("http://something/LoginForm.aspx") b.select_form(nr=0) b["ctl00$ContentPlaceHolder1$usertext"] = "username" b["ctl00$ContentPlaceHolder1$passtext"] = "pa...
how to make python mechanize ignore dropdown constraints
I'm trying to use python mechanize to fill data into a webpage from an excel file. b = Browser() b.open("http://something/LoginForm.aspx") b.select_form(nr=0) b["ctl00$ContentPlaceHolder1$usertext"] = "username" b["ctl00$ContentPlaceHolder1$passtext"] = "password" b.submit() b.select_form(nr=0) The problem is that wh...
[ "This needs an example. In my experience with aspx pages is that it doesn't use ajax. The first control is probably submitting and causing the whole page to reload with the new values in the other dropdown. \nThere may also be VIEWSTATE variables that need to correspond with the form, which means it is probably ...
[ 0 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0005741002_mechanize_python.txt
Q: Search and replace operation I have a list which has URL values like: http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg How can I change the _s in the end to _m for all occurrences? A: Try this: str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg" str = str.replace("_s","_m") I...
Search and replace operation
I have a list which has URL values like: http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg How can I change the _s in the end to _m for all occurrences?
[ "Try this:\nstr = \"http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg\"\nstr = str.replace(\"_s\",\"_m\")\n\nIf you want to be sure that only the las part is changed and you know all are .jpg files you can use:\nstr = \"http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg\"\nstr = str.repla...
[ 7, 4 ]
[]
[]
[ "python", "replace" ]
stackoverflow_0005882221_python_replace.txt
Q: Clone and Expando class object in Python for App Engine What is a good way to clone (make a copy of) an Expando class object when using Python on Google App Engine? I came across some code on here, but unless I'm mistaken, it does not work on expando properties: Copy an entity in Google App Engine datastore in Pyt...
Clone and Expando class object in Python for App Engine
What is a good way to clone (make a copy of) an Expando class object when using Python on Google App Engine? I came across some code on here, but unless I'm mistaken, it does not work on expando properties: Copy an entity in Google App Engine datastore in Python without knowing property names at 'compile' time Thanks!
[ "Here's a revised version of Nick's function that includes dynamic properties:\ndef clone_entity(e, **extra_args):\n \"\"\"Clones an entity, adding or overriding constructor attributes.\n\n The cloned entity will have exactly the same property values as the original\n entity, except where overridden. By default ...
[ 2 ]
[]
[]
[ "expando", "google_app_engine", "python" ]
stackoverflow_0005879301_expando_google_app_engine_python.txt
Q: thread.start_new_thread vs threading.Thread.start What is the difference between thread.start_new_thread and threading.Thread.start in python? I have noticed that when start_new_thread is called, the new thread terminates as soon as the calling thread terminates. threading.Thread.start is the opposite: the callin...
thread.start_new_thread vs threading.Thread.start
What is the difference between thread.start_new_thread and threading.Thread.start in python? I have noticed that when start_new_thread is called, the new thread terminates as soon as the calling thread terminates. threading.Thread.start is the opposite: the calling thread waits for other threads to terminate.
[ "The thread module is the low-level threading API of Python. Its direct usage isn't recommended, unless you really need to. The threading module is a high-level API, built on top of thread. The Thread.start method is actually implemented using thread.start_new_thread.\nThe daemon attribute of Thread must be set bef...
[ 12, 1 ]
[]
[]
[ "multithreading", "new_operator", "python" ]
stackoverflow_0005882362_multithreading_new_operator_python.txt
Q: python create celery task job lets say i have a python programm whitch i want to run always max 10 times in parallel using celery / rabbigmq and if some of the process finish i want to know about it so i can start a new process. how can i do so? some examples would be nice A: Giving an example is difficult as me...
python create celery task job
lets say i have a python programm whitch i want to run always max 10 times in parallel using celery / rabbigmq and if some of the process finish i want to know about it so i can start a new process. how can i do so? some examples would be nice
[ "Giving an example is difficult as messaging is a bit complex, but what you can do basically is:\n\nrewrite your program to be a task or write a task that calls your program using subprocess\nconfigure celery to have 10 workers\nexecute as many tasks as you need to get your job done, Celery will add them to its que...
[ 1 ]
[]
[]
[ "celery", "parallel_processing", "python" ]
stackoverflow_0005880867_celery_parallel_processing_python.txt
Q: Default format of date I know about Django filter "date" which allows to format date in templates. I know that I can modify representation of particular field in particular model. But when I have big Django project and would like to keep format of date to show in template in consistent way - is there any possibili...
Default format of date
I know about Django filter "date" which allows to format date in templates. I know that I can modify representation of particular field in particular model. But when I have big Django project and would like to keep format of date to show in template in consistent way - is there any possibility to achieve this with sett...
[ "Make sure to check the settings that affect the representation of dates.\nEspecially DATE_FORMAT \n\nThe default formatting to use for\n displaying date fields in any part of\n the system\n\nand DATETIME_FORMAT\n\nThe default formatting to use for\n displaying datetime fields in any part\n of the system. Note ...
[ 3 ]
[]
[]
[ "django", "gettext", "python" ]
stackoverflow_0005882693_django_gettext_python.txt
Q: Django Model Formsets and named urls I'm having some problems with model formsets in django. # forms.py OppFormSet = modelformset_factory(Opportunity, fields=opp_fields) # views.py def index2(request): queryset = Opportunity.objects.for_user(request.user).filter(is_deleted=False) if request.method == '...
Django Model Formsets and named urls
I'm having some problems with model formsets in django. # forms.py OppFormSet = modelformset_factory(Opportunity, fields=opp_fields) # views.py def index2(request): queryset = Opportunity.objects.for_user(request.user).filter(is_deleted=False) if request.method == 'POST': formset = OppFormSet(reques...
[ "Use {% for form in formset.forms %} This \"blank form\" is ManagementForm\n" ]
[ 1 ]
[]
[]
[ "django", "django_forms", "python" ]
stackoverflow_0005882585_django_django_forms_python.txt
Q: Python: Inputting files in a directory to a list I understand that with the glob or listdir modules you can get a list of all the files in a directory. However, I need to know how assign the output from glob or listdir to a variable, in list form, like listdir("/some/file/") = list and then be able to print list a...
Python: Inputting files in a directory to a list
I understand that with the glob or listdir modules you can get a list of all the files in a directory. However, I need to know how assign the output from glob or listdir to a variable, in list form, like listdir("/some/file/") = list and then be able to print list and see a list of all files in /some/file/. Please help...
[ "Are you looking for\nfilelist = os.listdir(\"/some/path/\")\nprint filelist\n\nIf so, consider to work through a Python tutorial :)\n" ]
[ 2 ]
[]
[]
[ "glob", "list", "python" ]
stackoverflow_0005883063_glob_list_python.txt
Q: Pause before retry connection in Python I am trying to connect to a server. Sometimes I cannot reach the server and would like to pause for a few seconds before trying again. How would I implement the pause feature in Python. Here is what I have so far. Thank you. while True: try: response =...
Pause before retry connection in Python
I am trying to connect to a server. Sometimes I cannot reach the server and would like to pause for a few seconds before trying again. How would I implement the pause feature in Python. Here is what I have so far. Thank you. while True: try: response = urllib.request.urlopen(http) except ...
[ "This will block the thread for 2 seconds before continuing:\nimport time\ntime.sleep(2)\n\n", "In case you want to run lots of these in parallel, it would be much more scalable to use an asynchronous networking framework such as Twisted, where \"sleeping\" doesn't mean blocking a valuable and expensive OS thread...
[ 7, 4 ]
[]
[]
[ "python", "python_3.x", "urllib" ]
stackoverflow_0005876159_python_python_3.x_urllib.txt
Q: How to retry urlfetch.fetch a few more times in case of error? Quite often GAE is not able to upload the file and I am getting the following error: ApplicationError: 2 Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call...
How to retry urlfetch.fetch a few more times in case of error?
Quite often GAE is not able to upload the file and I am getting the following error: ApplicationError: 2 Traceback (most recent call last): File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 636, in __call__ handler.post(*groups) File "/base/data/home/apps/picasa2vko...
[ "If you can, move this work into the task queue. When tasks fail, they retry automatically. If they continue to fail, the system gradually backs off retry frequency to as slow as once-per hour. This is an easy way to handle API requests to rate-limited services without implementing one-off retry logic.\nIf you real...
[ 9 ]
[]
[]
[ "exception_handling", "google_app_engine", "python" ]
stackoverflow_0005883116_exception_handling_google_app_engine_python.txt
Q: Python: Add item to list until a condition is true Normal list comprehensions occur this way: new_list = [f(x) for x in l] What is the most succinct and readable way to create new list in Python similar to this: new_list = [f(x) while condition is True] A: Keep it simple: new_list = [] while condition: new_...
Python: Add item to list until a condition is true
Normal list comprehensions occur this way: new_list = [f(x) for x in l] What is the most succinct and readable way to create new list in Python similar to this: new_list = [f(x) while condition is True]
[ "Keep it simple:\nnew_list = []\nwhile condition:\n new_list.append(f(x))\n\nThere is no benefit to forcing something into a single expression when it is more clearly written as separate statements.\n", "Use itertools:\nimport itertools as it\n\nnew_list = map(f, it.takewhile(condition, l))\n\nit is the same l...
[ 12, 8, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0005883265_list_python.txt
Q: How to decorate a GTK window like eg. the gnome-panel? I would like to make a panel-like application, in appearance much like the gnome-panel. I would like to use GTK for this (although i've looked into Qt), preferably using Python. How can i decorate the window in such a way a color/gradient/bitmap/svg is applied...
How to decorate a GTK window like eg. the gnome-panel?
I would like to make a panel-like application, in appearance much like the gnome-panel. I would like to use GTK for this (although i've looked into Qt), preferably using Python. How can i decorate the window in such a way a color/gradient/bitmap/svg is applied to it?
[ "One way is to use styles (the example below uses inline style strings):\n#!/usr/bin/env python\n\nimport gtk\n\npixmap_rc = \"\"\"\npixmap_path \"/home/foo/images\"\nstyle \"bar\" {\n bg_pixmap[NORMAL] = \"logo.svg\"\n} widget \"*foo\" style \"bar\"\n\"\"\"\n\ncolor_rc= \"\"\"\nstyle \"bar\" {\n bg[NORMAL] =...
[ 1 ]
[]
[]
[ "gtk", "panel", "python", "window_decoration" ]
stackoverflow_0005868114_gtk_panel_python_window_decoration.txt
Q: Same Django templates getting rendered differently? I have this in urlconf (r'^places/(\w+)/(\w+)/$', shopinfo), View codes: def shopinfo(request,c,s): if c == 'eat': shop=Eat.objects.get(slug=s) nearby = Eat.objects.filter(location=shop.location.all()[0]).exclude(id=shop.id) return render_to_respon...
Same Django templates getting rendered differently?
I have this in urlconf (r'^places/(\w+)/(\w+)/$', shopinfo), View codes: def shopinfo(request,c,s): if c == 'eat': shop=Eat.objects.get(slug=s) nearby = Eat.objects.filter(location=shop.location.all()[0]).exclude(id=shop.id) return render_to_response('shopinfo.html',{'s':shop,'c':c,'nearby':nearby,}) ...
[ "It's almost impossible to say anything useful about this without the template as well as an example of a \"good\" and a \"bad\" rendering.\nAt this point, my only guess is that one of your shop objects' attributes contains unescaped html.\n" ]
[ 1 ]
[]
[]
[ "django", "django_templates", "django_views", "python" ]
stackoverflow_0005883065_django_django_templates_django_views_python.txt
Q: Issue in Python Logging using dictConfig Below is the configuration dict i am using: LOGGING_CONF = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' }, 'simple': { 'format': '%(levelname)s %(mes...
Issue in Python Logging using dictConfig
Below is the configuration dict i am using: LOGGING_CONF = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handler': { 'file': { ...
[ "You have to add a handler so that something happens with all those loggers. For example, \nlogfile = logging.handlers.FileHandler(\"mylog.log\")\nlogfile.setLevel(logging.DEBUG)\nlogfile.setFormatter(logging.Formatter('%(asctime)s %(levelname)-8s %(module)s: %(message)s'))\nlogging.getLogger('').addHandler(logfile...
[ 2 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0005883467_django_logging_python.txt
Q: Updating shared data with Twisted How can I share a blob of data using a Twisted server, while at the time time periodically updating that data in the background?: from twisted.internet import reactor from twisted.internet import task from twisted.web.server import Site from twisted.web.resource import Resource d...
Updating shared data with Twisted
How can I share a blob of data using a Twisted server, while at the time time periodically updating that data in the background?: from twisted.internet import reactor from twisted.internet import task from twisted.web.server import Site from twisted.web.resource import Resource data = 1 def update_data(): data +=...
[ "Add a global def to update_data():\ndef update_data():\n global data\n data += 1\n\n" ]
[ 3 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0005883483_python_twisted.txt
Q: How do I set XML attributes in SOAPpy with python? I am forming a SOAPpy request but I can't figure out how to set the attributes in a tag. Here is my code: url = wsdlfile = 'https://stats2.overture.com/ExternalSOAP/statsPMCAPI_1_0.wsdl' n = 'urn:yahoo:overture:stats:3.0' server = WSDL.Proxy(wsdlfile) server.soap...
How do I set XML attributes in SOAPpy with python?
I am forming a SOAPpy request but I can't figure out how to set the attributes in a tag. Here is my code: url = wsdlfile = 'https://stats2.overture.com/ExternalSOAP/statsPMCAPI_1_0.wsdl' n = 'urn:yahoo:overture:stats:3.0' server = WSDL.Proxy(wsdlfile) server.soapproxy.config.dumpSOAPOut = 1 server.soapproxy.config.dum...
[ "You can do this by passing a typed value for the ReportRequest keyword argument. For example, if I change the getAvailablePmcReports line to this:\nfrom SOAPpy import Types\nresult = server.getAvailablePmcReports(\n ReportAuth = {'username': username, 'cookie': YBY},\n ReportRequest= Types.stringType('', at...
[ 3 ]
[]
[]
[ "python", "soappy" ]
stackoverflow_0003445352_python_soappy.txt
Q: Generating a frequency heatmap in Python MatPlotLib reading in X and Y coordinates from a .csv file I recently stumbled upon a similar question about how to generate a heatmap of frequencies in Python using the MatPlotLib module. This post was very useful and I could get the individual scripts to run and create he...
Generating a frequency heatmap in Python MatPlotLib reading in X and Y coordinates from a .csv file
I recently stumbled upon a similar question about how to generate a heatmap of frequencies in Python using the MatPlotLib module. This post was very useful and I could get the individual scripts to run and create heatmaps for the random test data that was inherently generated by the code. However, I am having trouble a...
[ "Since you have numpy at your disposal and assuming your csv files are well behaved, you can use numpy.loadtxt(),\nimport numpy as np \nimport matplotlib.pyplot as plt \n\ndat = np.loadtxt('mydata.csv')\n\nx, y = dat[:,0], dat[:,1]\n\nheatmap, xedges, yedges = np.histogram2d(x, y, bins=50) \nextent = [xedges[0]...
[ 5 ]
[ "Python has an absolutely spectacular csv file library:\n\nhttp://docs.python.org/library/csv.html\n\nWhile I don't know the details of matplotlib, the following code will loop over a tab delimited csv file and execute your code on each first and second column.\nimport numpy as np\nimport numpy.random\nimport matpl...
[ -2 ]
[ "csv", "matplotlib", "python" ]
stackoverflow_0005873823_csv_matplotlib_python.txt
Q: Recursion over a list of lists without isinstance() I have just read "isinstance() considered harmful", and it seems reasonable. In short, it argues for avoiding the use of this function. Well, just now I happen to be writing a program which takes inputs structured as a tree, and needs the tree's structure informa...
Recursion over a list of lists without isinstance()
I have just read "isinstance() considered harmful", and it seems reasonable. In short, it argues for avoiding the use of this function. Well, just now I happen to be writing a program which takes inputs structured as a tree, and needs the tree's structure information. Without time to implement a GUI, I impose on the us...
[ "Your situation is one of those where I would use isinstance. Your data structure is well-constrained, and you need to distinguish between a list and not a list. Use isinstance to ask if it is a list. You don't say, but I imagine strings might be among the leaves of your tree, and they are iterable as lists are,...
[ 10, 5, 2, 0, 0 ]
[]
[]
[ "isinstance", "python" ]
stackoverflow_0005882728_isinstance_python.txt
Q: Unexpected relative import behavior in Python I ran into a very surprising relative import behavior today (unfortantely after nearly 4 hours of pulling my hair out). I have always been under the impression that if you have "Class A" inside of a module name "module_a.py" within a package named "package" that you co...
Unexpected relative import behavior in Python
I ran into a very surprising relative import behavior today (unfortantely after nearly 4 hours of pulling my hair out). I have always been under the impression that if you have "Class A" inside of a module name "module_a.py" within a package named "package" that you could equivalently use either: from package.module_a ...
[ "Since implicit relative imports have caused problems they have been removed in Python 3. You often don't get expected behavior with them. See PEP-328 for a discussion. This is especially true if you define a subpackage name with the same name as a base (stock) module. \n", "(1) Yes, this is expected behaviour.\n...
[ 4, 0 ]
[]
[]
[ "python", "python_import" ]
stackoverflow_0005878541_python_python_import.txt
Q: Python: could a script compiled with py2exe freeze the operating system? I am using py2exe to compiling python scripts in executable files on Windows Xp/7/2000. I am wondering if such executable scripts could freeze the operating system, and I have to reboot Windows. I suppose such problems could occur if I try to...
Python: could a script compiled with py2exe freeze the operating system?
I am using py2exe to compiling python scripts in executable files on Windows Xp/7/2000. I am wondering if such executable scripts could freeze the operating system, and I have to reboot Windows. I suppose such problems could occur if I try to manage driver library. What do you think about?
[ "Theoretically, yes. Windows is not the most stable OS out there, and programs sometime \"freeze\" it even without mucking with drivers and kernel-mode code. Python programs aren't any different in this respect, whether packed with py2exe or not, since Python programs on Windows easily have access to the same Windo...
[ 3, 0 ]
[]
[]
[ "py2exe", "python", "windows" ]
stackoverflow_0005884037_py2exe_python_windows.txt
Q: Installing web2py on Solaris 10 : "ImportError: No module named _md5" I'm using python 2.6.2 on solaris 10 on a sparc. And this is the only python version. $PATH is pretty clean : /usr/bin::/usr/local/bin:/var/opt/python2.6.2/usr/local/bin Any ideas ? Edit : Just Found this link which talks about resolving t...
Installing web2py on Solaris 10 : "ImportError: No module named _md5"
I'm using python 2.6.2 on solaris 10 on a sparc. And this is the only python version. $PATH is pretty clean : /usr/bin::/usr/local/bin:/var/opt/python2.6.2/usr/local/bin Any ideas ? Edit : Just Found this link which talks about resolving the issue on Linux : http://johnsofteng.wordpress.com/2009/06/21/python-imp...
[ "Install the OpenSSL development files and rebuild Python.\n" ]
[ 2 ]
[]
[]
[ "compiler_errors", "python", "python_2.6", "solaris", "web2py" ]
stackoverflow_0005875658_compiler_errors_python_python_2.6_solaris_web2py.txt
Q: How do I do a simple next() method on a M2M in SQLAlchemy? I have two models with a many to many, Group and Individual. I can access group.individuals and get a list of the related individuals. I have a 'last_individual_id' column on the Group models to keep track of the Last used individual. With this information...
How do I do a simple next() method on a M2M in SQLAlchemy?
I have two models with a many to many, Group and Individual. I can access group.individuals and get a list of the related individuals. I have a 'last_individual_id' column on the Group models to keep track of the Last used individual. With this information I was wandering how get get the next individual for a Group. I ...
[ "One possibility is using itertools.dropwhile (but this may be limited as the scope of your desired solution, as it is not clear, also itertools.dropwhile doesn't infinitely cycle through your list like itertools.cycle does). \nYou didn't provide a lot of detail of your data model. I'll presume that group.individ...
[ 0 ]
[]
[]
[ "cycle", "python", "python_itertools", "sqlalchemy" ]
stackoverflow_0005875547_cycle_python_python_itertools_sqlalchemy.txt
Q: Django view to be created with the previous request containing select tag I am developing a webapp in Django+Python. I have three radio button inputs, which are having the job of showing and hiding the required select tag's ( done in Jquery ). i.e. With the check of one of the radio option its respective select el...
Django view to be created with the previous request containing select tag
I am developing a webapp in Django+Python. I have three radio button inputs, which are having the job of showing and hiding the required select tag's ( done in Jquery ). i.e. With the check of one of the radio option its respective select element is visible and the rest is hidden. Now, with the select element having it...
[ "Since your numbers don't correspond in any mathematical way to the actual values, you'll need to simply map them via a dict. Then you can pass the result of that map to a __range query:\nVALUE_MAP = {\n \"1\", (0, 399),\n \"2\", (400, 599),\n \"3\", (600, 1000),\n ...\n}\nvalue_range = VALUE_MAP[price]...
[ 2 ]
[]
[]
[ "django_views", "form_submit", "python" ]
stackoverflow_0005883949_django_views_form_submit_python.txt
Q: What's the best way to retrieve the module path from the project in python? | foo | main.py |---- one | | __init__.py |------ two | | __init__.py Consider the __init__.py file situated in the foo/one/two/__init__.py. In this file, I want to print the module PATH : foo/one/two/ What the best way to do t...
What's the best way to retrieve the module path from the project in python?
| foo | main.py |---- one | | __init__.py |------ two | | __init__.py Consider the __init__.py file situated in the foo/one/two/__init__.py. In this file, I want to print the module PATH : foo/one/two/ What the best way to do that ?
[ "Each module will have a __name__ attribute, which will give you the dot syntax attribute name of the module. e.g.:\n\nfrom one import two\nprint two.__name__\n\nThis should yield:\n\none.two\n\nYou could then simply replace the dots with the relevant file separater:\n\nimport os.path\nfrom one import two\nprint t...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005884498_python.txt
Q: is it possible to Only pull related users through foreign key relationship, once in django Hi im fairly new to the amazing world of django! Basically im working on a project that requires me to create a fairly unique email notifications system that users can use to refine the updates they recieve via email when ne...
is it possible to Only pull related users through foreign key relationship, once in django
Hi im fairly new to the amazing world of django! Basically im working on a project that requires me to create a fairly unique email notifications system that users can use to refine the updates they recieve via email when new blog posts are made on the site. I think im gonna have a ton of questions about this project a...
[ "You can do a single query for users that have at least one blog entry:\nUser.objects.exclude(blog=None)\n\n", "I'm not sure how Daniel's solution works since there is no blog field in the User model related to your Blog model (that I'm aware of). But if it works, that's great.\nIf you find you're still having a ...
[ 1, 1 ]
[]
[]
[ "django", "django_models", "django_users", "python" ]
stackoverflow_0005884454_django_django_models_django_users_python.txt
Q: how to transform a OpenCV cvMat back to ndarray in numpy ? I follow the code in OpenCV cookbook for python interface to transform cvMat to numpy array: mat = cv.CreateMat(3,5,cv.CV_32FC1) cv.Set(mat,7) a = np.asarray(mat) but with OpenCV 2.1 on my PC, it does not work. The result a here is a object array, using ...
how to transform a OpenCV cvMat back to ndarray in numpy ?
I follow the code in OpenCV cookbook for python interface to transform cvMat to numpy array: mat = cv.CreateMat(3,5,cv.CV_32FC1) cv.Set(mat,7) a = np.asarray(mat) but with OpenCV 2.1 on my PC, it does not work. The result a here is a object array, using "print a" does not print all element in a, only print <cvmat(typ...
[ "Try using appending [:,:] to the matrix (ie. use mat[:,:] instead of mat) in your call to np.asarray - doing this will also allows asarray to work on images.\nYour example:\n>>> import cv\n>>> import numpy as np\n>>> mat = cv.CreateMat( 3 , 5 , cv.CV_32FC1 )\n>>> cv.Set( mat , 7 )\n>>> a = np.asarray( mat[:,:] )\n...
[ 9, 2, 2 ]
[]
[]
[ "numpy", "opencv", "python" ]
stackoverflow_0005762440_numpy_opencv_python.txt
Q: Calculate the current location longitude and latitude I have a hard-coded address for particular place but i want to calculate current location longitude and latitude (using jquery or python script). This is my Django view at the moment: def maps(request): school = School.objects.get(id=1) dictte={'latitud...
Calculate the current location longitude and latitude
I have a hard-coded address for particular place but i want to calculate current location longitude and latitude (using jquery or python script). This is my Django view at the moment: def maps(request): school = School.objects.get(id=1) dictte={'latitude':school.latitute,'longitude':school.longitude} print ...
[ "You can use the W3 geolocation API to do this client-side in JavaScript. \nnavigator.geolocation.getCurrentPosition(\n function(pos){\n var lat = pos.coords.latitude;\n var long = pos.coords.longitude;\n // send coordinates to server, or display on map, if you wish\n },\n function(){\n /* Handler if...
[ 2 ]
[]
[]
[ "django", "javascript", "python", "view" ]
stackoverflow_0005884644_django_javascript_python_view.txt
Q: Interactive Python Network/Graph Modeling I'm looking for a python library that will allow me to interactively draw networks and graphs and attach data to nodes and edges. I have found two libraries for Java that seem to do what I need: JUNG and piccolo2d. Are there any python equivalents to these? A: Have a loo...
Interactive Python Network/Graph Modeling
I'm looking for a python library that will allow me to interactively draw networks and graphs and attach data to nodes and edges. I have found two libraries for Java that seem to do what I need: JUNG and piccolo2d. Are there any python equivalents to these?
[ "Have a look at:\n\nmatplotlib - Here are some graphs made with it.\nnetworkx \nigraph\n\n", "Using GNU/Radio Companion, I was able to accomplish what I needed by performing some extensions here and there. \nIt is not the best solution since it introduces some ugly dependencies, but it works for now.\n" ]
[ 4, 0 ]
[]
[]
[ "graph", "jung", "piccolo", "python" ]
stackoverflow_0005718204_graph_jung_piccolo_python.txt
Q: Splicing files fast in Python and getting their md5 I'm trying to split up a file into smaller pieces of +/- 300 kilobytes a piece. This is quite slow for a file of 300 megabytes (+/- 1000 pieces) I'm not using any threading yet, I 'm not sure if that would make it run any faster cs = 1 pieces = 1000 ...
Splicing files fast in Python and getting their md5
I'm trying to split up a file into smaller pieces of +/- 300 kilobytes a piece. This is quite slow for a file of 300 megabytes (+/- 1000 pieces) I'm not using any threading yet, I 'm not sure if that would make it run any faster cs = 1 pieces = 1000 # Open the file f = open(self.file, 'rb') result ...
[ "You're reading the chunk, saving it to a temporary file, then reading the temporary file and computing its md5. That's unnecessary, though - you can compute the md5 while the chunk is still in memory. That means you won't have to open the temp file and read it, which should be faster.\nAlso I'd recommend a smaller...
[ 4 ]
[]
[]
[ "file_io", "md5", "python" ]
stackoverflow_0005885342_file_io_md5_python.txt
Q: mysqldb doesn't write on db I'm trying to execute a query in a Magento database, the problem is that the Python API doesn't write to my database. It seems that the query is never executed. I suppose that the queries are correctly generated, they work in mysql cli. Maybe I don't use the API correctly, here is the c...
mysqldb doesn't write on db
I'm trying to execute a query in a Magento database, the problem is that the Python API doesn't write to my database. It seems that the query is never executed. I suppose that the queries are correctly generated, they work in mysql cli. Maybe I don't use the API correctly, here is the code: http://pastebin.com/5pUJc7ve...
[ "I think you forgot the commit.\nAdd\nconnessione.commit()\nconnessione.close()\n\n" ]
[ 2 ]
[]
[]
[ "mysql", "mysql_python", "python" ]
stackoverflow_0005885400_mysql_mysql_python_python.txt
Q: Is it possible to pre-create a virtualenv for use in hudson builds? I'm following the outline of the hudson/python/virtualenv CI solution described at heisel.org but one step of this is really chafing, and that's the part where the virtualenv, created just for the CI run, is configured: pip install -q -E ./ve -r r...
Is it possible to pre-create a virtualenv for use in hudson builds?
I'm following the outline of the hudson/python/virtualenv CI solution described at heisel.org but one step of this is really chafing, and that's the part where the virtualenv, created just for the CI run, is configured: pip install -q -E ./ve -r requirements.pip pip install -q -E ./ve -r requirements-test.pip This tak...
[ "Here are a couple options:\n\nHave an archive in your source repository that blows up into the\nvirtualenv/pip install. You'll need to make the virtualenv starting point relocatable. \nUse whatever SCM option is appropriate to not wipe out the workspace\nbetween builds (e.g. Use svn update, or don't check Mercuria...
[ 1, 0, 0 ]
[]
[]
[ "continuous_integration", "hudson", "pip", "python", "virtualenv" ]
stackoverflow_0003937464_continuous_integration_hudson_pip_python_virtualenv.txt
Q: In Python, why do I get an 'undefined local variable' error for counters but not for lists? If I alter a variable declared at the top of the file/module from within a method (no classes involved), it only works in the case of lists/containers, but not if my variable was a simple counter. See the following code for...
In Python, why do I get an 'undefined local variable' error for counters but not for lists?
If I alter a variable declared at the top of the file/module from within a method (no classes involved), it only works in the case of lists/containers, but not if my variable was a simple counter. See the following code for example: counter = 0 counterList = [] def incrementCounter(): counter += 1 def addToList()...
[ "Try\ndef incrementCounter():\n global counter\n counter += 1\n\nThe assignment to counter inside incrementCounter() otherwise implicitely makes counter local to that function.\nThe line counter += 1 does not actually change the integer object counter points to -- integers are immutable in Python. The line i...
[ 10, 3 ]
[]
[]
[ "python" ]
stackoverflow_0005885978_python.txt
Q: implement a database application with GUI for Windows, written with Linux I have the following data scheme that I want to turn into an application. A regular desktop GUI would probably the best. UML Diagram http://img217.imageshack.us/img217/341/56836587.jpg big version The whole thing would be developed on a Linu...
implement a database application with GUI for Windows, written with Linux
I have the following data scheme that I want to turn into an application. A regular desktop GUI would probably the best. UML Diagram http://img217.imageshack.us/img217/341/56836587.jpg big version The whole thing would be developed on a Linux (Ubuntu, Gnome) machine, and then used on a Windows Vista computer. If Window...
[ "You might want to check out Dabo.\n\nDabo is a 3-tier, cross-platform application development framework, written in Python atop the wxPython GUI toolkit\n\n", "Camelot\n", "If you are set on using Python them I think Qt would be am excellent choice. It's a fantastic framework that looks good and runs on many p...
[ 3, 2, 1 ]
[]
[]
[ "database", "orm", "python", "user_interface" ]
stackoverflow_0005885680_database_orm_python_user_interface.txt
Q: pylons/pyramid code completion with gedit and virtualenv I am working through the pyramid documentation and would really like code completion. I installed gedit-plugin-codecompletion I am using virtualenv, once created I use the 'activate' file in the bin/ folder to switch over my terminal window. When I launch g...
pylons/pyramid code completion with gedit and virtualenv
I am working through the pyramid documentation and would really like code completion. I installed gedit-plugin-codecompletion I am using virtualenv, once created I use the 'activate' file in the bin/ folder to switch over my terminal window. When I launch gedit I see these errors: (env)agd@hephaestus:~/Dev/projects/Le...
[ "You should create your virtualenv without --no-site-packages argument to allow access to python packages installed system-wide.\n", "If I were you, I just wouldn't run gedit from within your virtualenv. Start a new terminal window if you must. It just seems cleaner than installing non-development packages into...
[ 2, 1, 0 ]
[]
[]
[ "gedit", "pylons", "pyramid", "python", "virtualenv" ]
stackoverflow_0005804605_gedit_pylons_pyramid_python_virtualenv.txt
Q: for loop problem For loop issue: in1 = open('file_1', 'r') in2 = open('file_2', 'r') outf = open('out_file', 'w') for line in in1: s = line.split('\t') A = s[1][:-1] B = s[0] counter = 0 for line in in2: ss = line.split('\t') if A == ss[0] or A == ss[1]: counter += ...
for loop problem
For loop issue: in1 = open('file_1', 'r') in2 = open('file_2', 'r') outf = open('out_file', 'w') for line in in1: s = line.split('\t') A = s[1][:-1] B = s[0] counter = 0 for line in in2: ss = line.split('\t') if A == ss[0] or A == ss[1]: counter += 1 outf.write('%s\...
[ "You can iterate over a file only once. To start from the beginning again, use\nin2.seek(0)\n\nbefore the inner loop.\n", "The first time you loop over in2, you consume it. Either reopen it, or seek back to the beginning.\n", "Once you have read each line from file_2 in the inner loop then in2 is at end-of-fil...
[ 6, 2, 0, 0 ]
[]
[]
[ "for_loop", "python" ]
stackoverflow_0005886193_for_loop_python.txt
Q: thread dying without exception I'm having an issue with some of my worker threads. I've added a catchall exception statement in the thread's run method like so: try: """Runs the worker process, which is a state machine""" while self._set_exitcode is None : assert self._state in Worker....
thread dying without exception
I'm having an issue with some of my worker threads. I've added a catchall exception statement in the thread's run method like so: try: """Runs the worker process, which is a state machine""" while self._set_exitcode is None : assert self._state in Worker.STATES state_methodname ...
[ "You could try examining the execution trace of your program using the trace module. For example:\n% python -m trace -c -t -C ./coverage test_exit.py\n\nSource:\nimport sys\nimport threading\n\nclass Worker(object):\n def run(self):\n try:\n sys.exit(1)\n except:\n print sys.e...
[ 11, 1 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005885928_multithreading_python.txt
Q: Windows XP GTK App Glib Import Error I am trying to run my GTK app on Windows XP and I am having troubles with an import. I have installed the following as needed and recommended: python-2.6.msi gtk2-runtime.2-16.6.exe pycairo-1.8.6.exe pygobject-2.20.0 pygtk-2.16.0.exe pyserial-2.5.exe However, I am getting th...
Windows XP GTK App Glib Import Error
I am trying to run my GTK app on Windows XP and I am having troubles with an import. I have installed the following as needed and recommended: python-2.6.msi gtk2-runtime.2-16.6.exe pycairo-1.8.6.exe pygobject-2.20.0 pygtk-2.16.0.exe pyserial-2.5.exe However, I am getting the following error when running my script: ...
[ "I was getting the same issue - I'm not sure why, but I suspect it has something to do with some of the install/lookup paths. I tried adding all sorts of stuff to my path, but nothing seemed to work.\nWhat I did to fix it was to uninstall python et. al. and reinstall using the Python (x,y) package. It's a fairly la...
[ 3, 0 ]
[]
[]
[ "gtk", "pygtk", "python", "windows", "windows_xp" ]
stackoverflow_0003333601_gtk_pygtk_python_windows_windows_xp.txt
Q: 400 error on 'dumpdata' command with django-disqus Receiving 400 error when issuing a 'disqus_dumpdata' command (link). Searched Google and github but I seem to be the only person whos ever had this problem. Below is my traceback. I thought it was going to be 'line 32' of 'disqus_dumpdata.py' and my shortname or a...
400 error on 'dumpdata' command with django-disqus
Receiving 400 error when issuing a 'disqus_dumpdata' command (link). Searched Google and github but I seem to be the only person whos ever had this problem. Below is my traceback. I thought it was going to be 'line 32' of 'disqus_dumpdata.py' and my shortname or api key, but it's not: (pinax073)[user@web142 mysite]$ py...
[ "I would suggest that you actually read the error you're getting. Add try/except around that line:\ntry:\n response = urllib2.urlopen(url)\nexcept urllib2.HTTPError, error:\n contents = error.read()\n logging.debug(contents)\n raise \n\n" ]
[ 0 ]
[]
[]
[ "disqus", "django", "json", "python" ]
stackoverflow_0005880361_disqus_django_json_python.txt
Q: How to make a query that filters rows in which one column equals another one of the same table? Say I have a model that looks like: class StockRequest(models.Model): amount_requested = models.PositiveIntegerField(null=True) amount_approved = models.PositiveIntegerField(null=True) Is there any way to make...
How to make a query that filters rows in which one column equals another one of the same table?
Say I have a model that looks like: class StockRequest(models.Model): amount_requested = models.PositiveIntegerField(null=True) amount_approved = models.PositiveIntegerField(null=True) Is there any way to make a django query that would show me all requests where there is some relationship between amount_reque...
[ "from django.db.models import F\nStockRequest.objects.filter(amount_requested=F(\"amount_approved\"))\n\nhttp://docs.djangoproject.com/en/dev/topics/db/queries/#filters-can-reference-fields-on-the-model\n", "Yes, you can. You can use the built in \"F\" object to do this.\nThe syntax would be:\nfrom django.db.mode...
[ 15, 2, 0 ]
[]
[]
[ "django", "django_queryset", "python" ]
stackoverflow_0005886819_django_django_queryset_python.txt
Q: Checking XML Nodes with Script using REGEX Bit of a problem here, basically I have a web address that I use a GET with. for example 111.244.25.633/Data.XML (Don't worry about the IP, it's just made up for a device) that returns an XML file. In Data.XML we have some Nodes and sub-nodes. (like a tree I suppose) For ...
Checking XML Nodes with Script using REGEX
Bit of a problem here, basically I have a web address that I use a GET with. for example 111.244.25.633/Data.XML (Don't worry about the IP, it's just made up for a device) that returns an XML file. In Data.XML we have some Nodes and sub-nodes. (like a tree I suppose) For example the entire Data is encapsulated like thi...
[ "Please see this response: Regular Expressions to parse template tags in XML\nA demonstration for your project...\nfrom xml.etree import ElementTree\nimport re\n\ndef proper_SN(elem):\n if re.search('\\d{6}', elem.text):\n return True\n return False\n\ntree = ElementTree.parse('data.xml')\nrows = tree....
[ 3, 2, 2 ]
[]
[]
[ "bash", "lxml", "python", "xml" ]
stackoverflow_0005886188_bash_lxml_python_xml.txt
Q: put a class in a list. python i have to write a class which in that class can addShapes heres the class I have to do class Drawing(Circle, Square): list = [] def addShape(self, theShape, colour, x, y, side): self.list += [self.theShape(colour, x, y, side)] def display(self): return s...
put a class in a list. python
i have to write a class which in that class can addShapes heres the class I have to do class Drawing(Circle, Square): list = [] def addShape(self, theShape, colour, x, y, side): self.list += [self.theShape(colour, x, y, side)] def display(self): return self.list def move(self): ...
[ "I don't think it's totally clear what you're trying to accomplish, but here's what I think:\n\nYou should show us what you have written so far\nYou should mark it as homework if it is homework\nYou can add anything to a list in Python, so just give it a shot:\nmyList = [circle_instance, CircleClass, 'some-color', ...
[ 1, 0, 0 ]
[]
[]
[ "class", "list", "python" ]
stackoverflow_0005886343_class_list_python.txt
Q: Backspace does not seem to work in python network={1:[2,3,4],2:[1,3,4], 3:[1,2], 4:[1,3,5], 5:[6,7,8], 6:[5,8],7:[5,6], 8:[5,6,7]} str1='network.csv' output = open(str1,'w') for ii1 in network.keys(): output.write(repr(ii1)+":[") for n in network[ii1]: output.write(' %s,'%(repr(n))) output.writ...
Backspace does not seem to work in python
network={1:[2,3,4],2:[1,3,4], 3:[1,2], 4:[1,3,5], 5:[6,7,8], 6:[5,8],7:[5,6], 8:[5,6,7]} str1='network.csv' output = open(str1,'w') for ii1 in network.keys(): output.write(repr(ii1)+":[") for n in network[ii1]: output.write(' %s,'%(repr(n))) output.write('\b'+']\n') output.close() What I expect is ...
[ "The \"\\b\" simply inserts the ASCII backspace character; it does not remove the just-written character from the output file. This is why your code doesn't behave as you expect.\nNow, to fix it you could replace\nfor ii1 in network.keys():\n output.write(repr(ii1)+\":[\")\n for n in network[ii1]:\n ou...
[ 5, 4, 1, 0, 0, 0 ]
[]
[]
[ "backspace", "dictionary", "file", "io", "python" ]
stackoverflow_0005886985_backspace_dictionary_file_io_python.txt
Q: Pros and cons to using sparse matrices in python/R? I'm working with large, sparse matrices (document-feature matrices generated from text) in python. It's taking quite a bit of processing time and memory to chew through these, and I imagine that sparse matrices could offer some improvements. But I'm worried that...
Pros and cons to using sparse matrices in python/R?
I'm working with large, sparse matrices (document-feature matrices generated from text) in python. It's taking quite a bit of processing time and memory to chew through these, and I imagine that sparse matrices could offer some improvements. But I'm worried that using a sparse matrix library is going to make it harder...
[ "Using sparse matrices in Python might not be a great idea in itself.\nHave you checked out sparse matrices in numpy / scipy?\nNumpy brings the immense benefit of using mainly C code to provide performance gains in Python.\nFrom my limited experience of doing text processing in R, the performance makes it pretty mu...
[ 1, 1 ]
[]
[]
[ "python", "r", "sparse_matrix" ]
stackoverflow_0005749479_python_r_sparse_matrix.txt
Q: PyS60 : An always running app.. Hanging the Phones UI ? (How to tackle that ?) I am testing my application in the Python Shell on Symbian S60 Platform. Functionally, the application just runs great on the shell.. but its seems so hang the interface ? Even when : It does not include heavy processing !! The loop loo...
PyS60 : An always running app.. Hanging the Phones UI ? (How to tackle that ?)
I am testing my application in the Python Shell on Symbian S60 Platform. Functionally, the application just runs great on the shell.. but its seems so hang the interface ? Even when : It does not include heavy processing !! The loop looks like : while 1: // Application Functions called here. // Nothing processo...
[ "You are preventing the process scheduler from switching to UI thread by calling the native python sleep. It doesn't do what you think it does on PyS60. You should use e32.ao_yield or e32.Ao_timer to manage application loop. RTFM carefully or you won't get any responsive UI.\n" ]
[ 3 ]
[]
[]
[ "here_api", "pys60", "python" ]
stackoverflow_0005887012_here_api_pys60_python.txt
Q: install plpython in postgresql 8 or 9 i want to install plpython on postgresql to have python trigger when i restore my DB (my db has some python trigger) this error apears (error message was too big so i paste first lines of it): C:/Program Files/PostgreSQL/9.0/bin/pg_restore.exe --host localhost --port 543...
install plpython in postgresql 8 or 9
i want to install plpython on postgresql to have python trigger when i restore my DB (my db has some python trigger) this error apears (error message was too big so i paste first lines of it): C:/Program Files/PostgreSQL/9.0/bin/pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "mfa...
[ "It looks like you need to put plpython.dll in C:/Program Files/PostgreSQL/9.0/lib. I just tried the following commands on my system, and it worked.\ncd C:\\Program Files\\PostgreSQL\\8.2\\bin\ncreatelang --dbname=MyDb plpythonu -U myuser\n\nChecking into my C:\\Program Files\\PostgreSQL\\8.2\\lib reveals that I ha...
[ 6 ]
[]
[]
[ "installation", "plpython", "postgresql", "python" ]
stackoverflow_0005887387_installation_plpython_postgresql_python.txt
Q: OAuth authentication fails for google data APIs for hosted domains using gdata I'm creating a django app that creates a calendar and a google docs folder for the users, and uses the API to insert events and add documents. A few months ago, it worked nice enough; now I'm doing a major refactoring of my code and, wh...
OAuth authentication fails for google data APIs for hosted domains using gdata
I'm creating a django app that creates a calendar and a google docs folder for the users, and uses the API to insert events and add documents. A few months ago, it worked nice enough; now I'm doing a major refactoring of my code and, while testing the aforementioned components, I discovered that they don't work anymore...
[ "The reason is layed out in the json response: 'reason': 'Unknown authorization header'\nOne possible cause is your machine's local time. Make sure that the time on your local machine is correct, as oauth uses the current unix timestamp to sign and verify requests. Google support forum\nHere's a list of bugs logged...
[ 0 ]
[]
[]
[ "django", "gdata_python_client", "google_docs_api", "python" ]
stackoverflow_0003170329_django_gdata_python_client_google_docs_api_python.txt
Q: How can I move forward to a subsequent portion of text once I've already printed a searched portion of text in Python? I would like to search through a text file and print out a line and its subsequent 3 lines if a keyword is found in the line AND a different keyword is found within the subsequent 3 lines. My code...
How can I move forward to a subsequent portion of text once I've already printed a searched portion of text in Python?
I would like to search through a text file and print out a line and its subsequent 3 lines if a keyword is found in the line AND a different keyword is found within the subsequent 3 lines. My code right now prints too much information. Is there a way to move forward to the next section of text once a portion is alread...
[ "So you want to print out all blocks of 4 lines containing more than 2 keywords?\nAnyway, thats what I've just came up with. Maybe you can use it:\ntext = \"\"\"\n\nhere is some text 1\nI want to print out this line and the following 3 lines only once keyword 2\nprint this line since it has a keyword2 3\nprint this...
[ 1, 1, 0, 0 ]
[]
[]
[ "printing", "python", "search", "text" ]
stackoverflow_0005885846_printing_python_search_text.txt
Q: django , list of models to list of string I have a list of model objects: just an example (I'm not really doing a list of all()): class Tag(models.Model): name = models.CharField(max_length=50,primary_key=True) #Some other fields.... def __str__(self): return self.name mylist = list(Tag.objec...
django , list of models to list of string
I have a list of model objects: just an example (I'm not really doing a list of all()): class Tag(models.Model): name = models.CharField(max_length=50,primary_key=True) #Some other fields.... def __str__(self): return self.name mylist = list(Tag.objects.all()) What's the best way of converting th...
[ "This\nnewList = [ str(t) for t in mylist ]\n\nor\nnewList = map( str, myList )\n\nBut generally, we don't bother. We just leave it to the template to convert the query set into strings when the template is rendered.\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "list", "python" ]
stackoverflow_0005887715_django_django_models_list_python.txt
Q: Logging null bytes via apache There is a problem with logging a binary data to stdout via Apache. After configuring logging I try to log string '\x31\x00': logging.getLogger().info('\x31\x00') All going well if I use python console - I see expected: 2011-05-01 22:21:27,430 INFO [test_logging:9][test_logging] 1 Bu...
Logging null bytes via apache
There is a problem with logging a binary data to stdout via Apache. After configuring logging I try to log string '\x31\x00': logging.getLogger().info('\x31\x00') All going well if I use python console - I see expected: 2011-05-01 22:21:27,430 INFO [test_logging:9][test_logging] 1 But if I use logging via Apache and m...
[ "You could just use\nlogging.getLogger().info('%r', binary_bytes)\n\nand it should do the right thing.\nNothing is wrong with Apache/mod_wsgi - it's just that console output streams are not supposed to be used for binary data.\n", "The error is stated right there: stream.write cannot take a string argument contai...
[ 1, 0, 0 ]
[]
[]
[ "apache", "logging", "python" ]
stackoverflow_0005885948_apache_logging_python.txt
Q: Python: How to loop a process I'm working on making a small app/script for putting my mp3's in a folder hierarchy the way I want it, as I haven't found a solution for Unix that is just quite right. So I decided to work on my own. This is an excerpt if musfile[0]: m = musfile[0] tag.link(m) mar = str(ta...
Python: How to loop a process
I'm working on making a small app/script for putting my mp3's in a folder hierarchy the way I want it, as I haven't found a solution for Unix that is just quite right. So I decided to work on my own. This is an excerpt if musfile[0]: m = musfile[0] tag.link(m) mar = str(tag.getArtist()) mal = str(tag.ge...
[ "import os, os.path\nimport shutil\n\nfor m in musfile:\n tag.link(m)\n mar = str(tag.getArtist())\n mal = str(tag.getAlbum())\n mti = str(tag.getTitle())\n new_name = mar + ' - ' + mti + '.mp3'\n os.rename(m, new_name)\n new_dir = os.path.join(newmusicdir, mar, mal) #use os.path.join instea...
[ 4 ]
[ "This doesn't answer your original question, but here's my solution to a similar problem: Importer\n" ]
[ -1 ]
[ "file_organization", "loops", "python" ]
stackoverflow_0005887675_file_organization_loops_python.txt
Q: What's a convenient way of resolving a path /bar/foo/baz/../.. into /bar? Is there a module capable of doing this, or should I write something myself? A: What's about this : >>> os.path.normpath("/bar/foo/baz/../..") "/bar"
What's a convenient way of resolving a path /bar/foo/baz/../.. into /bar?
Is there a module capable of doing this, or should I write something myself?
[ "What's about this :\n>>> os.path.normpath(\"/bar/foo/baz/../..\")\n\"/bar\"\n\n" ]
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005888074_python.txt
Q: Communicating multiple times w/ subprocess (multiple calls to stdout) There's a similar question to mine on [this thread][1]. I want to send a command to my subprocess, interpret the response, then send another command. It would seem a shame to have to start a new subprocess to accomplish this, particularly if s...
Communicating multiple times w/ subprocess (multiple calls to stdout)
There's a similar question to mine on [this thread][1]. I want to send a command to my subprocess, interpret the response, then send another command. It would seem a shame to have to start a new subprocess to accomplish this, particularly if subprocess2 must perform many of the same tasks as subprocess1 (e.g. ssh, op...
[ "Your choices are:\n\nUse a line-oriented protocol (and use readline() rather than read()), and ensure that every possible line sent is a valid message; \nUse read(1) and a parser to tell you when you've read a full message; or\nPickle message objects into the stream from the subprocess, then unpickle them in the p...
[ 2, 1, 1 ]
[]
[]
[ "pipe", "python", "stream", "subprocess" ]
stackoverflow_0005861466_pipe_python_stream_subprocess.txt
Q: Extra Python libraries on phone I have Python installed on my S60 phone...but I require some addtional libraries like pyaudio and lightblue to be installed on my phone...is there a way I can do this? Also where are the Python libraries installed on my phone? A: I don't thinks those libraries will run on PyS60 if...
Extra Python libraries on phone
I have Python installed on my S60 phone...but I require some addtional libraries like pyaudio and lightblue to be installed on my phone...is there a way I can do this? Also where are the Python libraries installed on my phone?
[ "I don't thinks those libraries will run on PyS60 if they are not designed for that platform.\n" ]
[ 0 ]
[]
[]
[ "pys60", "python", "s60", "symbian" ]
stackoverflow_0004427623_pys60_python_s60_symbian.txt
Q: How to use mercurial (Hg) within a Python application? Aloha! Hg is a fine DVCS that is also a python module. This allows us to do ''import mercurial'' and load hg into our own application. My idea was to use mercurial within a Python application to create a revision controlled storage for my application. However ...
How to use mercurial (Hg) within a Python application?
Aloha! Hg is a fine DVCS that is also a python module. This allows us to do ''import mercurial'' and load hg into our own application. My idea was to use mercurial within a Python application to create a revision controlled storage for my application. However my google-fu semms to fail me. I can't find any documentatio...
[ "API is mostly undocumented, and using it might require you to release your code as GPL — see https://www.mercurial-scm.org/wiki/MercurialApi. The preferred (and more backwards compatible) way is to call hg CLI frontend.\n" ]
[ 6 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0005888632_mercurial_python.txt
Q: How do you add a string to a deque without breaking the string up into characters? I am trying to create a deque of strings, but when I add a string to the deque it always breaks the string up into individual characters. Here is my code so far: from collections import deque my_string = "test" my_queue = deque(my_...
How do you add a string to a deque without breaking the string up into characters?
I am trying to create a deque of strings, but when I add a string to the deque it always breaks the string up into individual characters. Here is my code so far: from collections import deque my_string = "test" my_queue = deque(my_string) print my_queue The output I get is: deque(['t', 'e', 's', 't']) I would like ...
[ "The deque constructor takes an iterable as a parameter, if you just give the string to it, it will interpret it as a sequence of characters.\nIn order to do what you want you should wrap your string into a list:\nyour_string = 'string'\nwrap_list = [your_string]\n#Now create the deque\nd = deque(wrap_list)\n\nOf c...
[ 8, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005888680_python.txt
Q: Buildout: use a "package" as an entry-point? I have a directory named ./foo in my project which contains an __init__.py file, which contains a method named main(). I'd like to use buildout to create an executable which will execute the main() method (eg: ./bin/foo). I've achieved something similar at the "top-leve...
Buildout: use a "package" as an entry-point?
I have a directory named ./foo in my project which contains an __init__.py file, which contains a method named main(). I'd like to use buildout to create an executable which will execute the main() method (eg: ./bin/foo). I've achieved something similar at the "top-level" of my directory structure using the following b...
[ "Normally, python finds modules and packages via the python path, via the sys.path variable. When buildout creates scripts in the bin/ directory, it'll add to the sys.path variable, listing all the eggs for the given part.\nIn order for python to find your ./bar.py module, or your ./foo package, the current directo...
[ 1 ]
[]
[]
[ "buildout", "python" ]
stackoverflow_0005883046_buildout_python.txt
Q: What is this doing (Python) I came across a piece of code today that looks like this: class ClassName(object): def __init__(self): self._vocabulary = None def vocabulary(self): self._vocabulary = self._vocabulary or self.keys() return self._vocabulary What exactly is the line...
What is this doing (Python)
I came across a piece of code today that looks like this: class ClassName(object): def __init__(self): self._vocabulary = None def vocabulary(self): self._vocabulary = self._vocabulary or self.keys() return self._vocabulary What exactly is the line self._vocabulary = self._vocabul...
[ "A line like this:\nself._vocabulary = self._vocabulary or self.keys()\n\nIs what's called lazy initialization, when you are retrieving the value for the first time it initializes. So if it has never been initialized self._vocabulary will be None (because the __init__ method had set this value) resulting in the eva...
[ 8, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005888771_python.txt
Q: i18n with webpy i Have a problem with i18n, using webpy. I have followed this : http://webpy.org/cookbook/i18n_support_in_template_file So, in my .wsgi there is : #i18n gettext.install('messages',I18N_PATH,unicode=True) gettext.translation('messages',I18N_PATH,languages=['fr_FR','en_US']).install(True) So i ran :...
i18n with webpy
i Have a problem with i18n, using webpy. I have followed this : http://webpy.org/cookbook/i18n_support_in_template_file So, in my .wsgi there is : #i18n gettext.install('messages',I18N_PATH,unicode=True) gettext.translation('messages',I18N_PATH,languages=['fr_FR','en_US']).install(True) So i ran : pygettext.py -a -v -...
[ "web.py documentation explains it in here.\nhttp://webpy.org/cookbook/runtime-language-switch\n" ]
[ 0 ]
[]
[]
[ "gettext", "internationalization", "python", "web.py" ]
stackoverflow_0002999365_gettext_internationalization_python_web.py.txt
Q: Can use Berkeley DB in mobile phone Can i use Berkeley DB python classes in mobile phone directly , i mean Do DB python classes and methods are ready to be used in any common mobile phone like Nokia,Samsong (windows mobile)..etc. If a phone system supports python language, does that mean that it is easy and strai...
Can use Berkeley DB in mobile phone
Can i use Berkeley DB python classes in mobile phone directly , i mean Do DB python classes and methods are ready to be used in any common mobile phone like Nokia,Samsong (windows mobile)..etc. If a phone system supports python language, does that mean that it is easy and straightforward to use Berkeley DB on it...
[ "Berkeley DB is a library that needs to be available. What you may have is Python bindings to Berkeley DB. If the library is not present, having Python will not help.\nLook for SQLite, which may be present (it is for iPhone) as it has SQL support and its library size is smaller than Berkeley DB, which makes it bett...
[ 1 ]
[]
[]
[ "berkeley_db", "database", "mobile", "python", "windows_mobile" ]
stackoverflow_0005888854_berkeley_db_database_mobile_python_windows_mobile.txt
Q: Regexp beginner: how to remove comma before a keyword? I have a string "THIS IS, A STRING, FROM" How can I remove a comma before the FROM statement? A: You may use a lookahead: ,(?=\s*FROM\b) Or, with many keywords: ,(?=\s*(?:FROM|TO|COUNT)\b) In Python (case insensitive): remove_commas = re.compile(r',(?=\s*F...
Regexp beginner: how to remove comma before a keyword?
I have a string "THIS IS, A STRING, FROM" How can I remove a comma before the FROM statement?
[ "You may use a lookahead:\n,(?=\\s*FROM\\b)\n\nOr, with many keywords:\n,(?=\\s*(?:FROM|TO|COUNT)\\b)\n\nIn Python (case insensitive):\nremove_commas = re.compile(r',(?=\\s*FROM\\b)', re.IGNORECASE)\nstr = remove_commas.sub('', str)\n\nWorking example: http://ideone.com/etEnt\n", "A Perl Example:\n$text = \"THIS ...
[ 5, 2, 0 ]
[]
[]
[ "perl", "python", "regex" ]
stackoverflow_0005889111_perl_python_regex.txt
Q: Dictionary+Queue Data Structure with Active Removal of Old Messages I would like to create a data structure which represents a set of queues (ideally a hash, map, or dict like lookup) where messages in the queues are being actively removed after they've reached a certain age. The ttl value would be global; message...
Dictionary+Queue Data Structure with Active Removal of Old Messages
I would like to create a data structure which represents a set of queues (ideally a hash, map, or dict like lookup) where messages in the queues are being actively removed after they've reached a certain age. The ttl value would be global; messages would not need nor have individual ttl's. The resolution for the ttl do...
[ "I'd start by just modeling the behavior you're looking for in a single class, expressed as simply as possible. Performance can come later on through iterative optimization, but only if necessary (you may not need it).\nThe class below does something roughly like what you're describing. Queues are simply lists th...
[ 4, 1 ]
[]
[]
[ "data_structures", "python", "queue" ]
stackoverflow_0005888734_data_structures_python_queue.txt
Q: Save M2M "Through" Inlines in Django Admin Apparently Django's ModelAdmin/ModelForm doesn't allow you to use save_m2m() if there's an intermediate through table for a ManyToManyField. models.py: from django.db import models def make_uuid(): import uuid return uuid.uuid4().hex class MyModel(models.Model):...
Save M2M "Through" Inlines in Django Admin
Apparently Django's ModelAdmin/ModelForm doesn't allow you to use save_m2m() if there's an intermediate through table for a ManyToManyField. models.py: from django.db import models def make_uuid(): import uuid return uuid.uuid4().hex class MyModel(models.Model): id = models.CharField(default=make_uuid, ...
[ "In your MyModelAdmin you might try overriding the save_formset method. This way you can choose the order in which you save.\n" ]
[ 0 ]
[]
[]
[ "admin", "django", "inline", "many_to_many", "python" ]
stackoverflow_0005872861_admin_django_inline_many_to_many_python.txt
Q: One liner to determine if dictionary values are all empty lists or not I have a dict as follows: someDict = {'a':[], 'b':[]} I want to determine if this dictionary has any values which are not empty lists. If so, I want to return True. If not, I want to return False. Any way to make this a one liner? A: Per ...
One liner to determine if dictionary values are all empty lists or not
I have a dict as follows: someDict = {'a':[], 'b':[]} I want to determine if this dictionary has any values which are not empty lists. If so, I want to return True. If not, I want to return False. Any way to make this a one liner?
[ "Per my testing, the following one-liner (my original answer) has best time performance in all scenarios. See edits below for testing information. I do acknowledge that solutions using generator expressions will be much more memory efficient and should be preferred for large dicts. \nEDIT: This is an aging answer...
[ 16, 13, 6, 4, 2, 2 ]
[]
[]
[ "python" ]
stackoverflow_0005889611_python.txt
Q: django 1.3 admin site problem itself I have got a really strange issue with the admin site. When I enter to the site the address is:http://127.0.0.1:8000/admin/ and I see the front-admin-site, hmm looks fine. But when I click to any "+Add button" or any link on the site I see still the admin site:p but with addres...
django 1.3 admin site problem itself
I have got a really strange issue with the admin site. When I enter to the site the address is:http://127.0.0.1:8000/admin/ and I see the front-admin-site, hmm looks fine. But when I click to any "+Add button" or any link on the site I see still the admin site:p but with address f.e. http://127.0.0.1:8000/admin/categor...
[ "It's a problem with your urls.py configuration, the way to have admin in there is:\nfrom django.contrib import admin\nadmin.autodiscover()\n\n...\n url(r'^admin/', include(admin.site.urls)),\n\n99% of the time that's what that is.\n" ]
[ 6 ]
[]
[]
[ "admin", "django", "python" ]
stackoverflow_0005889638_admin_django_python.txt
Q: Python: Windows registry hive access NOT using registry APIs I am trying to extract some data out of the Windows registry, both the software hive and ntuser.dat from XP computers. Currently I'm using reg.exe to load the hive and _winreg to extract the data. I need to use reg.exe as the computers I'm backing up d...
Python: Windows registry hive access NOT using registry APIs
I am trying to extract some data out of the Windows registry, both the software hive and ntuser.dat from XP computers. Currently I'm using reg.exe to load the hive and _winreg to extract the data. I need to use reg.exe as the computers I'm backing up data from are usually offline and I'm putting the hard drive from t...
[ "I'm not sure how much better it is, but the pywin32 library supplies bindings to most of the windows API. I don't know the windows API well enough to know if you can open arbitrary hive files, however it could be worth a quick look (the release contains a CHM with the full API mapping). \n", "Did you have a loo...
[ 1, 0, 0 ]
[]
[]
[ "python", "registry", "windows", "winreg" ]
stackoverflow_0005887694_python_registry_windows_winreg.txt
Q: AttributeError: 'module' object has no attribute 'maketrans' while running cProfile Using python 2.7 I get this error: Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72...
AttributeError: 'module' object has no attribute 'maketrans' while running cProfile
Using python 2.7 I get this error: Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/lib/python2.7/cProfile.py", line...
[ "As the Python tutorial on modules explains: \n\nActually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation- dependent default. This allows Python programs th...
[ 7 ]
[]
[]
[ "profiler", "python" ]
stackoverflow_0005889466_profiler_python.txt
Q: How to run different child process independently in python? I have various python function which i intend to run independently. For exmaple , def graphic() is responsible for all GUI elements and renders GUI def connect() this function constantly listens and connects to other system The problem is these 2 func...
How to run different child process independently in python?
I have various python function which i intend to run independently. For exmaple , def graphic() is responsible for all GUI elements and renders GUI def connect() this function constantly listens and connects to other system The problem is these 2 functions are not running in parallel. I have used multiprocessing mo...
[ "Possibly because you're calling the functions instead of passing a reference to them? ie, the first two lines should be:\np = Process(target=graphic, args=())\np1 = Process(target=connect, args=())\n\n" ]
[ 4 ]
[]
[]
[ "python" ]
stackoverflow_0005889530_python.txt
Q: Delete duplicates from GoogleAppEngine Model? I have two Google App Engine Models. I ran my cron's a few times and now there are duplicate entries in my datastore. If it was easy to just delete my entire datastore and upload my data again I would. BUT it took 4 hours to upload last time so I am wondering is the...
Delete duplicates from GoogleAppEngine Model?
I have two Google App Engine Models. I ran my cron's a few times and now there are duplicate entries in my datastore. If it was easy to just delete my entire datastore and upload my data again I would. BUT it took 4 hours to upload last time so I am wondering is there a quick way of deleting entries with duplicate n...
[ "Quick? Probably not.\nIf you did want to delete dupes, my approach would be to write a remote_api script. Query the model for all entities, sort by title, and fetch batches of 100. Keep a local Python dictionary of titles. If you encounter a new title, add it to the dictionary. If you encounter a known title, add ...
[ 3 ]
[]
[]
[ "duplicates", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005890023_duplicates_google_app_engine_google_cloud_datastore_python.txt
Q: Full text searching XML data with Python: best practices, pros & cons Task I want to use Python for doing full text searches of XML data. Example data <elements> <elem id="1">some element</elem> <elem id="2">some other element</elem> <elem id="3">some element <nested id="1"> other nested element ...
Full text searching XML data with Python: best practices, pros & cons
Task I want to use Python for doing full text searches of XML data. Example data <elements> <elem id="1">some element</elem> <elem id="2">some other element</elem> <elem id="3">some element <nested id="1"> other nested element </nested> </elem> </elements> Basic functionality The most basic functio...
[ "Not sure if that will be enough for your needs, but lxml has support for regular expressions in xpath (meaning: you can use xpath 1.0 plus the EXSLT extension functions for regular expressions)\nCompared to the feature list that was added later:\n\nsearch nested elements (infinite depth): yes\nsearch attributes: y...
[ 6, 2, 1, 1, 1, 0 ]
[]
[]
[ "full_text_search", "python", "search", "xml", "xpath" ]
stackoverflow_0005790943_full_text_search_python_search_xml_xpath.txt