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: Django python pisa no module utils No module named utils python2.7/pisa-3.0.33-py2.7.egg/sx/pisa3/pisa_parser.py in <module>, line 29 I'm trying to use pisa to generate pdfs from html. please let me know if you've encountered this error before. __author__ = "$Author: holtwick $" __date__ = "$Date: 2007-10-09 12:...
Django python pisa no module utils
No module named utils python2.7/pisa-3.0.33-py2.7.egg/sx/pisa3/pisa_parser.py in <module>, line 29 I'm trying to use pisa to generate pdfs from html. please let me know if you've encountered this error before. __author__ = "$Author: holtwick $" __date__ = "$Date: 2007-10-09 12:58:24 +0200 (Di, 09 Okt 2007) $" from pi...
[ "You probably have no module Utils installed. See your \"pisa\" dependencies documentation. It usually says what does it need.\n", "Maybe you need python setup tools\n" ]
[ 0, 0 ]
[]
[]
[ "django", "pisa", "python" ]
stackoverflow_0006591182_django_pisa_python.txt
Q: Why can't I utilize other model objects in my custom Manager? I want to implement a custom django.db.models.manager.Manager (let's call it MyManager) for MyModel. The methods in MyManager needs to invoke filter methods on AnotherModel. Is this possible ? I'm getting an ImportError because of this. A: In your MyM...
Why can't I utilize other model objects in my custom Manager?
I want to implement a custom django.db.models.manager.Manager (let's call it MyManager) for MyModel. The methods in MyManager needs to invoke filter methods on AnotherModel. Is this possible ? I'm getting an ImportError because of this.
[ "In your MyModel, you need to add your MyManager as an explicit manager.\nclass MyModel(models.Model):\n objects = MyManager()\n\nYou can retain the standard Manager and have your manager both, by including this manager by another name.\nclass MyModel(models.Model):\n myobjects = MyManager()\n\nIf you are usi...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006592153_django_python.txt
Q: wxPython CollapsiblePane strange clipping issue This is a follow up from allocating more size in sizer to wx.CollapsiblePane when expanded. EDIT: The answer to that question solved my original problem, which was that nothing moved when I expanded or collapsed a pane, but now I've encountered another bug. While th...
wxPython CollapsiblePane strange clipping issue
This is a follow up from allocating more size in sizer to wx.CollapsiblePane when expanded. EDIT: The answer to that question solved my original problem, which was that nothing moved when I expanded or collapsed a pane, but now I've encountered another bug. While things do move properly, the buttons seem to smear out ...
[ "If I am getting you right, you want the code here - allocating more size in sizer to wx.CollapsiblePane when expanded to work properly. The reason it did not work was you forgot to bind the wx.EVT_COLLAPSIBLEPANE_CHANGED. Here is a code which worked for me - \nimport wx\n\nclass SampleCollapsiblePane(wx.Collapsibl...
[ 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0006591562_python_wxpython.txt
Q: How can I combine two fields into one when importing from a file into numpy array? I have a data file which I am reading into a numpy array which looks like the following. #RIC,Date[G],Time[G],GMT Offset,Type,Open,High,Low,Last,Volume ADH0,20100103,22:18:00.000,-6,Intraday 1Min,0.8915,0.8915,0.8915,0.8915,0 ADH0,2...
How can I combine two fields into one when importing from a file into numpy array?
I have a data file which I am reading into a numpy array which looks like the following. #RIC,Date[G],Time[G],GMT Offset,Type,Open,High,Low,Last,Volume ADH0,20100103,22:18:00.000,-6,Intraday 1Min,0.8915,0.8915,0.8915,0.8915,0 ADH0,20100103,22:22:00.000,-6,Intraday 1Min,0.89,0.89,0.89,0.89,0 I am reading it using the n...
[ "Not directly, it might be easier if you just slice'n'dice the csv file before loading, for example with a very stupid script like this:\ngawk -F, '{print $1\",\"$2\"_\"$3\",\"$4\",\"$5\",\"$6\",\"$7\",\"$8\",\"$9\",\"$10}' input.csv\n\nThis will combine field 2 and 3 with an underscore, and you can use a timestamp...
[ 2, 0, 0 ]
[]
[]
[ "numpy", "python" ]
stackoverflow_0006524875_numpy_python.txt
Q: How do I write a write() method in a pkl file that I can use in my python scrpits? I am trying a share a boolean between different scripts. In one script, I want to edit the boolean if a certain function is called. In the other scripts, I want to use the boolean. I'm trying to use pickling, but I'm in way over my ...
How do I write a write() method in a pkl file that I can use in my python scrpits?
I am trying a share a boolean between different scripts. In one script, I want to edit the boolean if a certain function is called. In the other scripts, I want to use the boolean. I'm trying to use pickling, but I'm in way over my head. I have no idea what to write in my pkl file. My code kinda looks like this: one....
[ "The arguments required for dump and load need a file object, so you cannot simply pass the filename as a string. (and you should use the non-s version as mentioned by other answers)\nTry something like this: pickle.dump(boolean, open(\"filename.pkl\", \"w\")) \nand boolean = pickle.load(open(\"filename.pkl\", \"r\...
[ 4, 0, 0 ]
[]
[]
[ "methods", "pickle", "python" ]
stackoverflow_0006592429_methods_pickle_python.txt
Q: How to handle "duck typing" in Python? I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time. One way to go is to force people to subclass an "interface" class. To me, this feels more like ...
How to handle "duck typing" in Python?
I usually want to keep my code as generic as possible. I'm currently writing a simple library and being able to use different types with my library feels extra important this time. One way to go is to force people to subclass an "interface" class. To me, this feels more like Java than Python and using issubclass in eac...
[ "I'm not a python pro but I believe that unless you can try an alternative for when the parameter doesn't implement a given method, you shoudn't prevent exceptions from being thrown. Let the caller handle these exceptions. This way, you would be hidding problems from the developers.\nAs I have read in Clean Code, i...
[ 18, 12, 8, 6, 3 ]
[]
[]
[ "duck_typing", "oop", "python", "types" ]
stackoverflow_0006589967_duck_typing_oop_python_types.txt
Q: OpenCL producing incorrect calculations I've been trying to use openCL to do some calculations, but the results are incorrect. I input three float3's that look like this: [300000,0,0] [300000,300000,0] [300000,300000,300000] into this kernel: __kernel void gravitate(__global const float3 *position,__global const ...
OpenCL producing incorrect calculations
I've been trying to use openCL to do some calculations, but the results are incorrect. I input three float3's that look like this: [300000,0,0] [300000,300000,0] [300000,300000,300000] into this kernel: __kernel void gravitate(__global const float3 *position,__global const float3 *momentum,__global const float3 *mass,...
[ "float3 are 16-byte aligned. See OpenCL 1.1 spec, 6.1.5.\n" ]
[ 6 ]
[]
[]
[ "gpgpu", "opencl", "python" ]
stackoverflow_0006591144_gpgpu_opencl_python.txt
Q: wikitools, wikipedia and python Does anybody have experience in getting a wikipedia page using wikitools for python (and django)? I am trying to get the article but I get a few first lines and that's it. I need to fetch the whole article and I can't seem to figure it out. The documentation is not very helpful eith...
wikitools, wikipedia and python
Does anybody have experience in getting a wikipedia page using wikitools for python (and django)? I am trying to get the article but I get a few first lines and that's it. I need to fetch the whole article and I can't seem to figure it out. The documentation is not very helpful either. My code is: wikiobj = wiki.Wiki("...
[ "I'm using wikitools im my project, not for getting text on the page, but I initialize wiki object in a different way:\nwikiobj = wiki.Wiki(\"http://en.wikipedia.org/w/api.php\")\nwikipage = page.Page(wikiobj, title=\"Some_Title\")\n\nYou don't need to supply any query to after api.php in the Wiki class.\nNext, loo...
[ 1 ]
[]
[]
[ "django", "mediawiki", "python", "wikipedia" ]
stackoverflow_0006589873_django_mediawiki_python_wikipedia.txt
Q: Following links, Scrapy web crawler framework After several readings to Scrapy docs I'm still not catching the diferrence between using CrawlSpider rules and implementing my own link extraction mechanism on the callback method. I'm about to write a new web crawler using the latter approach, but just becuase I had ...
Following links, Scrapy web crawler framework
After several readings to Scrapy docs I'm still not catching the diferrence between using CrawlSpider rules and implementing my own link extraction mechanism on the callback method. I'm about to write a new web crawler using the latter approach, but just becuase I had a bad experience in a past project using rules. I'd...
[ "CrawlSpider inherits BaseSpider. It just added rules to extract and follow links.\nIf these rules are not enough flexible for you - use BaseSpider:\nclass USpider(BaseSpider):\n \"\"\"my spider. \"\"\"\n\n start_urls = ['http://www.amazon.com/s/?url=search-alias%3Dapparel&sort=relevance-fs-browse-rank']\n ...
[ 11, 1 ]
[]
[]
[ "python", "scrapy", "web_crawler" ]
stackoverflow_0006591255_python_scrapy_web_crawler.txt
Q: QTextEdit.find() doesn't work in Python Simple code demonstrating the problem: #!/usr/bin/env python import sys from PyQt4.QtCore import QObject, SIGNAL from PyQt4.QtGui import QApplication, QTextEdit app = QApplication(sys.argv) def findText(): print(textEdit.find('A')) textEdit = QTextEdit() textEdit.sho...
QTextEdit.find() doesn't work in Python
Simple code demonstrating the problem: #!/usr/bin/env python import sys from PyQt4.QtCore import QObject, SIGNAL from PyQt4.QtGui import QApplication, QTextEdit app = QApplication(sys.argv) def findText(): print(textEdit.find('A')) textEdit = QTextEdit() textEdit.show() QObject.connect(textEdit, SIGNAL('textCha...
[ "The problem is the position of the cursor in the window.\nBy default - unless you specify some flags to be passed to the find() function, the search only happens forward (= from the position of the cursor onwards).\nIn order to make your test work, you should do something like this:\n\nRun the program.\nGo to the ...
[ 4 ]
[]
[]
[ "pyqt4", "python", "qt", "qt4", "qtextedit" ]
stackoverflow_0006593096_pyqt4_python_qt_qt4_qtextedit.txt
Q: What are some good ways of estimating 'approximate' semantic similarity between sentences? I have been looking at the nlp tag on SO for the past couple of hours and am confident I did not miss anything but if I did, please do point me to the question. In the mean time though, I will describe what I am trying to d...
What are some good ways of estimating 'approximate' semantic similarity between sentences?
I have been looking at the nlp tag on SO for the past couple of hours and am confident I did not miss anything but if I did, please do point me to the question. In the mean time though, I will describe what I am trying to do. A common notion that I observed on many posts is that semantic similarity is difficult. For i...
[ "Latent Semantic Modeling could be useful. It's basically just yet another application of the Singular Value Decomposition. The SVDLIBC is a pretty nice C implementation of this approach, which is an oldie but a goodie, and there are even python binding in the form of sparsesvd. \n", "I suggest you try a topic...
[ 5, 2 ]
[]
[]
[ "data_mining", "machine_learning", "nlp", "nltk", "python" ]
stackoverflow_0006593030_data_mining_machine_learning_nlp_nltk_python.txt
Q: Biopython not working on Window 7 64 (import bio function not working) I am having trouble using biopython as my 'import bio' does not work. I have Window 7 , 64-bit system with Python 2.7.1 with Piston, Django and NumPy site packages installed and they all work well with the import function. Any ideas? A: From ...
Biopython not working on Window 7 64 (import bio function not working)
I am having trouble using biopython as my 'import bio' does not work. I have Window 7 , 64-bit system with Python 2.7.1 with Piston, Django and NumPy site packages installed and they all work well with the import function. Any ideas?
[ "From the biopython download page.\n\nNote we don't (yet) have official 64 bit Windows Installers - however, Christoph Gohlke has kindly made Windows 64bit installers for NumPy and Biopython (and other tools) available for testing.\n\nDid you install the 32bit package? If so, try uninstalling it and installing the ...
[ 0 ]
[]
[]
[ "biopython", "import", "python" ]
stackoverflow_0006592127_biopython_import_python.txt
Q: How to sleep in an embedded Python in a QT-application I am embedding Python into a GUI QT-Application. I assigned a signal to one of my buttons in my UI-file, and when it is clicked I run the script. This works when using the approach from http://docs.python.org/py3k/extending/embedding.html I also added some f...
How to sleep in an embedded Python in a QT-application
I am embedding Python into a GUI QT-Application. I assigned a signal to one of my buttons in my UI-file, and when it is clicked I run the script. This works when using the approach from http://docs.python.org/py3k/extending/embedding.html I also added some functions to an embedded module as demonstrated in section 5....
[ "This answer is general, and may not be workable with the QT framework. (I don't use QT myself)\nThe reason sleep doesn't work is it basically looks like the following code in C++\nstatic PyObject* mysleep(PyObject *self, PyObject *args)\n{\n int secs = 0;\n if (!PyArg_ParseTuple(args, \"l\", &secs))\n ...
[ 0 ]
[]
[]
[ "c++", "embedding", "python", "qt", "sleep" ]
stackoverflow_0006157594_c++_embedding_python_qt_sleep.txt
Q: Django from the point of view of Zend Framework developer I mostly work in ZF. However, for next project I want to try Django. Does anyone have experience of moving from ZF to Django? What are the most striking differences or difficulties in the switch from ZF to Django (except programming language)? Was it easy ...
Django from the point of view of Zend Framework developer
I mostly work in ZF. However, for next project I want to try Django. Does anyone have experience of moving from ZF to Django? What are the most striking differences or difficulties in the switch from ZF to Django (except programming language)? Was it easy to change or not?
[ "I'm currently porting an application written in ZF to Django. In my experience the main difference between the two frameworks is the coupling between their internal components. ZF takes it's concept of loose coupling to the extreme where you have to figure out the best way to fit them together. Django on the other...
[ 7 ]
[]
[]
[ "django", "php", "python", "zend_framework" ]
stackoverflow_0006593282_django_php_python_zend_framework.txt
Q: Regular Expression in Python I don't know how to find the string using regular expression, the format of string is below. [ any symbol 0~n times any number 1~n times] 1~n times. It's seems like phone number matched. But the difference is that can insert any symbols and white space between numbers, for example 458#...
Regular Expression in Python
I don't know how to find the string using regular expression, the format of string is below. [ any symbol 0~n times any number 1~n times] 1~n times. It's seems like phone number matched. But the difference is that can insert any symbols and white space between numbers, for example 458###666###2##111####111 OR (123)))44...
[ "If you need to gather all the groups of digits from the string you can use \\d+ regex:\n>>> re.findall('\\d+', '458###666###2##111####111 OR (123)))444###555%%6222%%%%')\n['458', '666', '2', '111', '111', '123', '444', '555', '6222']\n\n", "I think this represents the pattern you described\n^(?:(\\D?)\\1*\\d+)+$...
[ 2, 2, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0006594220_python_regex.txt
Q: how python test binary data inside some plain text which was extract from database I have to extract some product information from mysql database, then construct a SOAP request and use python's suds library to send this SOAP request to a remote server. But some of the information extract is combine with binary dat...
how python test binary data inside some plain text which was extract from database
I have to extract some product information from mysql database, then construct a SOAP request and use python's suds library to send this SOAP request to a remote server. But some of the information extract is combine with binary data and text data, such as: ... Some plain data ... Content-Type: image/pjpeg ? JFIF H ...
[ "Mixed text and binary?! Sounds awful...\nHowever if all data is in the format you presented in your example (i.e. with a Content-type declaration) you could do something along the lines of:\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndata = '''Some plain data!Content-Type: image/pjpeg ? JFIF H H  C  C...
[ 2 ]
[]
[]
[ "binary", "mysql", "python" ]
stackoverflow_0006593504_binary_mysql_python.txt
Q: What should I put in the tp_name field when defining a type in a Python extension? I am developing an interface so that Python programs can call into an existing C++ library. If I understand correctly, such an interface (and the C++ library) should be imported as a module, say abc. The types in the interface are...
What should I put in the tp_name field when defining a type in a Python extension?
I am developing an interface so that Python programs can call into an existing C++ library. If I understand correctly, such an interface (and the C++ library) should be imported as a module, say abc. The types in the interface are defined as static variables on the C++ side of the interface, and registered with Pytho...
[ "By doing\nPyModule_AddObject(module, type->tp_name, as<PyObject>(type));\n\nyou are adding the type to the module (which means setting an attribute) using \"abc.MyType\" as the attribute name. Which means you would need to access it using getattr(abc, 'abc.MyType') if you wanted to access it on the abc module (you...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0006594554_python.txt
Q: Proxy setting for zope.testbrowser In mechanize we can set proxy like this: br = mechanize.Browser() br.set_proxies({"http": "joe:password@myproxy.example.com:3128", "ftp": "proxy.example.com",}) How do we do the same for zope.testbrowser? Many thanks! A: zope.testbrowser is a wrapper around mechanize, and you ...
Proxy setting for zope.testbrowser
In mechanize we can set proxy like this: br = mechanize.Browser() br.set_proxies({"http": "joe:password@myproxy.example.com:3128", "ftp": "proxy.example.com",}) How do we do the same for zope.testbrowser? Many thanks!
[ "zope.testbrowser is a wrapper around mechanize, and you can reach the wrapped mechanize browser via the mech_browser attribute:\n browser.mech_browser.set_proxies(dict(\n http=\"joe:password@myproxy.example.com:3128\",\n ftp=\"proxy.example.com\",\n ))\n\nNot tested, but the above should work.\n" ]
[ 1 ]
[]
[]
[ "django", "mechanize", "proxy", "python", "zope" ]
stackoverflow_0006595035_django_mechanize_proxy_python_zope.txt
Q: What are equivalents to R's "phyper" function in Python? In R, I use the phyper function to do a hypergeometric test for bioinformatics analysis. However I use a lot of Python code and using rpy2 here is quite slow. So, I started looking for alternatives. It seemed that scipy.stats.hypergeom had something similar....
What are equivalents to R's "phyper" function in Python?
In R, I use the phyper function to do a hypergeometric test for bioinformatics analysis. However I use a lot of Python code and using rpy2 here is quite slow. So, I started looking for alternatives. It seemed that scipy.stats.hypergeom had something similar. Currently, I call phyper like this: pvalue <- 1-phyper(45, 92...
[ "From the docs, you could try:\n\nhypergeom.sf(x,M,n,N,loc=0) :\n survival function (1-cdf — sometimes\n more accurate)\n\nAlso, I think you might have the values mixed up.\n\nModels drawing objects from a bin. M\n is total number of objects, n is total\n number of Type I objects. RV counts\n number of Type I ...
[ 9 ]
[]
[]
[ "python", "statistics" ]
stackoverflow_0006594840_python_statistics.txt
Q: Importing in functions instead of at the beginning or the script? Quick background: writing a module. One of my objects has methods that may or may not be successfully completed - depending on the framework used underneath my module. So a few methods first need to check what framework they actually have under thei...
Importing in functions instead of at the beginning or the script?
Quick background: writing a module. One of my objects has methods that may or may not be successfully completed - depending on the framework used underneath my module. So a few methods first need to check what framework they actually have under their feet. Current way of tackling this is: def framework_dependent_functi...
[ "This version may be faster, because not every call to the function needs to try to import the necessary functionality:\ntry:\n import module.that.may.not.be.available\n def framework_dependent_function():\n # whatever\nexcept ImportError:\n def framework_dependent_function():\n # the require...
[ 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006596281_python.txt
Q: Strange error calling java program from python via command line As part of my python-based program, I have to call a Java program - solved that perfectly with os.system(). It worked well, until I moved the entire thing from one directory to the other. I changed all the filepaths in the python code, and the java pr...
Strange error calling java program from python via command line
As part of my python-based program, I have to call a Java program - solved that perfectly with os.system(). It worked well, until I moved the entire thing from one directory to the other. I changed all the filepaths in the python code, and the java program - as best I can tell, I don't really understand java - relies o...
[ "Not a direct answer but ...\nI think it is better to call .bat file instead of direct call to java with many command line option. This way you will not need to change Python program to add some other options (like -Xms2048m or -Dfile.encoding=utf8).\nSuch .bat file is also much easier to debug.\n", "Your problem...
[ 1, 0, 0, 0 ]
[]
[]
[ "command_line", "java", "python" ]
stackoverflow_0006596049_command_line_java_python.txt
Q: no module named pywinauto when I type the following on python2.5 IDLE (windows vista 32-bit)-- from pywinauto import Application I get this error message-- Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import pywinauto ImportError: No module named pywinauto I followed the instr...
no module named pywinauto
when I type the following on python2.5 IDLE (windows vista 32-bit)-- from pywinauto import Application I get this error message-- Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> import pywinauto ImportError: No module named pywinauto I followed the instructions from this site, and did...
[ "Do you have multiple versions of Python installed? Maybe the python.exe that was used for python.exe setup.py install is not Python 2.5. To check, open a command prompt and run python.exe -V.\nIf that is the problem, you need to go to the directory where you extracted the pywinauto zip file, and run C:\\python25...
[ 1 ]
[]
[]
[ "python", "pywinauto" ]
stackoverflow_0006594787_python_pywinauto.txt
Q: Python Multiprocess diff between Windows and Linux I have a script called jobrunner.py that calls class methods in main.py. See below... # jobrunner.py from multiprocessing import Process import main from main import BBOX def _a(arg): f = main.a() print f.run() def _b(arg): p = main.b() print p.r...
Python Multiprocess diff between Windows and Linux
I have a script called jobrunner.py that calls class methods in main.py. See below... # jobrunner.py from multiprocessing import Process import main from main import BBOX def _a(arg): f = main.a() print f.run() def _b(arg): p = main.b() print p.run() if __name__ == '__main__': world = '-180,180,-...
[ "You shouldn't expect the values of global variables that you set in the parent process to be automatically propagated to the child processes.\nYour code happens to work on Unix-like platforms because on those platforms multiprocessing uses fork(). This means that every child processes gets a copy of the parent pro...
[ 22 ]
[]
[]
[ "global", "multiprocessing", "python" ]
stackoverflow_0006596617_global_multiprocessing_python.txt
Q: How do I convert a python function/class/module object to a python code object I have been looking around for some way to convert a function or class or module object in python to a python code object. A few people accomplish this by doing inspect.getsource() and compile(), but the problem with this is that you ar...
How do I convert a python function/class/module object to a python code object
I have been looking around for some way to convert a function or class or module object in python to a python code object. A few people accomplish this by doing inspect.getsource() and compile(), but the problem with this is that you are reading a potentially changed file, or if it was composed in the interactive pytho...
[ "For a function you can use the func_code attribute:\nimport dis\n\ndef func(arg):\n x = 5\n arg = 3\n return x + arg\n\ndef function_to_code_obj(func):\n return func.func_code\n\ncode_obj = function_to_code_obj(func)\ndis.disassemble(code_obj)\n\n" ]
[ 3 ]
[]
[]
[ "compilation", "function", "object", "python" ]
stackoverflow_0006596573_compilation_function_object_python.txt
Q: dir() a __class__ attribute? class Foo: pass >>> f = test.Foo() Lets look into the class instance ... >>> dir(f) ['__add__', [__class__] ...] Oooh! Lets look into the class instance metadata ... >>> dir(f.__class__) ['__add__', [__class__] ...] hmm ... was expecting attributes of __class__ ; but returns back...
dir() a __class__ attribute?
class Foo: pass >>> f = test.Foo() Lets look into the class instance ... >>> dir(f) ['__add__', [__class__] ...] Oooh! Lets look into the class instance metadata ... >>> dir(f.__class__) ['__add__', [__class__] ...] hmm ... was expecting attributes of __class__ ; but returns back attributes of f Trying a hit and ...
[ "dir(f) and dir(f.__class__) are showing the attributes of two different things. It's just that your empty object has the same attributes as its own class. Try this:\n>>> class Foo:\n... def __init__(self):\n... self.a = 17\n...\n>>> f = Foo()\n>>> 'a' in dir(f)\nTrue\n>>> 'a' in dir(f.__class__)\nFalse\n\n" ]
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0006596769_python.txt
Q: Selecting elements in numpy array using regular expressions One may select elements in numpy arrays as follows a = np.random.rand(100) sel = a > 0.5 #select elements that are greater than 0.5 a[sel] = 0 #do something with the selection b = np.array(list('abc abc abc')) b[b==a] = 'A' #convert all the a's to A's T...
Selecting elements in numpy array using regular expressions
One may select elements in numpy arrays as follows a = np.random.rand(100) sel = a > 0.5 #select elements that are greater than 0.5 a[sel] = 0 #do something with the selection b = np.array(list('abc abc abc')) b[b==a] = 'A' #convert all the a's to A's This property is used by the np.where function to retrive indices:...
[ "There's some setup involved here, but unless numpy has some kind of direct support for regular expressions that I don't know about, then this is the most \"numpytonic\" solution. It tries to make iteration over the array more efficient than standard python iteration.\nimport numpy as np\nimport re\n\nr = re.compi...
[ 21 ]
[]
[]
[ "numpy", "python", "regex" ]
stackoverflow_0006595759_numpy_python_regex.txt
Q: $post and Cherrypy I'm currently working on a project where we previously used Django. However this proved a bit to heavyweight for our needs so we are shifting the project over to use cherrypy as we only really need to handle requests. my problem is this. I have a form on the html page (index.html) when the user ...
$post and Cherrypy
I'm currently working on a project where we previously used Django. However this proved a bit to heavyweight for our needs so we are shifting the project over to use cherrypy as we only really need to handle requests. my problem is this. I have a form on the html page (index.html) when the user clicks submit the follow...
[ "I have discovered the solution to this. JQuery:\n$(document).ready(function() {\n $(\"#loginform\").submit(function() {\n $.post('/request',{username:$(\"#username\").val(),password:\"test\"}, \n function(data) {\n $(\"#error\").html(data['response']);\n });\n ...
[ 6 ]
[]
[]
[ "cherrypy", "jquery", "python" ]
stackoverflow_0006518595_cherrypy_jquery_python.txt
Q: Python calendar, counting empty days of the week before the first of the month I did something like this : import datetime nb_blank_days = (int(datetime.date(year, month, 1).strftime('%w'))+6)%7 But I doesn't looks very pythonic. Any help ? The goal is to say that because the first of July is a friday, there is ...
Python calendar, counting empty days of the week before the first of the month
I did something like this : import datetime nb_blank_days = (int(datetime.date(year, month, 1).strftime('%w'))+6)%7 But I doesn't looks very pythonic. Any help ? The goal is to say that because the first of July is a friday, there is 4 blanks in the week before displaying the first.
[ "How about just\ndatetime.date(year, month, 1).weekday()\n\nSince 0 is Monday, I think this does what you want.\n" ]
[ 3 ]
[]
[]
[ "date", "datetime", "python", "strftime" ]
stackoverflow_0006598209_date_datetime_python_strftime.txt
Q: Python global exception handling I want to catch KeyboardInterrupt globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement. Is there any way to do this? A: You could change sys.excepthook if you really don't want to use a try/except. import sys def my_except_ho...
Python global exception handling
I want to catch KeyboardInterrupt globally, and deal with it nicely. I don't want to encase my entire script in a huge try/except statement. Is there any way to do this?
[ "You could change sys.excepthook if you really don't want to use a try/except.\nimport sys\ndef my_except_hook(exctype, value, traceback):\n if exctype == KeyboardInterrupt:\n print \"Handler code goes here\"\n else:\n sys.__excepthook__(exctype, value, traceback)\nsys.excepthook = my_except_hoo...
[ 145, 25, 18, 10, 0 ]
[]
[]
[ "exception", "python" ]
stackoverflow_0006598053_exception_python.txt
Q: Facebook app on app engine showing as blank page on canvas iframe I'm trying to get a FB app to show up on it's app page inside facebook, but the iFrame is just coming up blank. The app works perfectly on localhost and appspot, but when it loads inside facebook nothing happens. If I view the source of the iframe, ...
Facebook app on app engine showing as blank page on canvas iframe
I'm trying to get a FB app to show up on it's app page inside facebook, but the iFrame is just coming up blank. The app works perfectly on localhost and appspot, but when it loads inside facebook nothing happens. If I view the source of the iframe, nothing comes up, but then if I refresh this page, all the code shows u...
[ "The problem was that the first request from facebook comes as a post request,\n//initial facebook request comes in as a POST with a signed_request\nif u'signed_request' in self.request.POST:\n facebook.load_signed_request(self.request.get('signed_request'))\n\nhttp://developers.facebook.com/docs/samples/canvas/...
[ 3 ]
[]
[]
[ "facebook", "google_app_engine", "iframe", "python" ]
stackoverflow_0006594568_facebook_google_app_engine_iframe_python.txt
Q: How can I create two unique, queriable fields for a GAE Datastore Data Model? First a little setup. Last week I was having trouble implementing a specific methodology that I had constructed which would allow me to manage two unique fields associated with one db.Model object. Since this isn't possible, I created...
How can I create two unique, queriable fields for a GAE Datastore Data Model?
First a little setup. Last week I was having trouble implementing a specific methodology that I had constructed which would allow me to manage two unique fields associated with one db.Model object. Since this isn't possible, I created a parent entity class and a child entity class, each having the key_name assigned ...
[ "The system you describe will work, at the cost of transactionality. Note that the second entity is no longer a child entity - it's just another entity with a ReferenceProperty.\nThis solution may be sufficient to your needs - for instance, if you need to enforce that every user has a unique email address, but this...
[ 1, 0 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "transactions" ]
stackoverflow_0006584435_google_app_engine_google_cloud_datastore_python_transactions.txt
Q: Efficient writing to a Compact Flash in python I'm writing a gui to do perform a glorified 'dd'. I could just subprocess to 'dd' but I thought I might as well use python's open()/read()/write() if I can as it'll let me display progress much more easily. Prompted by this link here I have: input = open('filename.img...
Efficient writing to a Compact Flash in python
I'm writing a gui to do perform a glorified 'dd'. I could just subprocess to 'dd' but I thought I might as well use python's open()/read()/write() if I can as it'll let me display progress much more easily. Prompted by this link here I have: input = open('filename.img', 'rb') output = open("/dev/sdc", 'wb') while True:...
[ "Speed depending on buffer size is unrelated to the specific characteristics of compact flash, but inherent to all I/O with (relatively) slow devices, even to all kinds of system calls. You should make the buffer size as large as possible without exhausting memory - 2MiB should be enough for a Flash drive.\nYou sho...
[ 1, 0 ]
[]
[]
[ "python", "python_2.4" ]
stackoverflow_0006597020_python_python_2.4.txt
Q: Python removing items from list I have a list in the given format: [['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']] There are some elements like this in the list ['Linus Torvalds', ''] and I want to remove those. So why doesn't the following code remove them? for i in people: if(i[0] == '' or ...
Python removing items from list
I have a list in the given format: [['John', 'Smith'], ['Linus', 'Torvalds'], ['Bart', 'Simpson']] There are some elements like this in the list ['Linus Torvalds', ''] and I want to remove those. So why doesn't the following code remove them? for i in people: if(i[0] == '' or i[1] == ''): print people.pop...
[ "You are changing the list while iterating over it and this is the source of your problems. An approach that works is\npeople[:] = [p for p in people if p[0] != '' and p[1] != '']\n\nthis way a new temporary list containing only the elements you want is built and then assigned to the original list object when the o...
[ 10, 4, 3, 1 ]
[]
[]
[ "nested_lists", "python" ]
stackoverflow_0006598622_nested_lists_python.txt
Q: Python - code not processing all files in directory The code below is only processing one file in my 'textpath' directory. I am using "for .. in ..:" statement so it should process all the files in the directory. I'm a Python newbie so any help would really be appreciated! textpath = "C:\Users\SL\Documents\FF Proj...
Python - code not processing all files in directory
The code below is only processing one file in my 'textpath' directory. I am using "for .. in ..:" statement so it should process all the files in the directory. I'm a Python newbie so any help would really be appreciated! textpath = "C:\Users\SL\Documents\FF Project\scratchpad\Text" newpath = "C:\Users\SL\Documents\FF ...
[ "textfile=open(file) statement takes only the last value of the iteration since its outside the loop\nYou loop should be something like this : \nfor text2break in text2breaks:\n file = os.path.join(textpath, text2break)\n textfile=open(file)\n textFileContent=textfile.read()\n textFileList = re.split(\"...
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0006598862_python.txt
Q: "Method overloading" in python I think the concept is called overloading. Right now I'm writing a class that will provide getter and setter methods, and am stuck on a design issue. Both methods are one-liners that simply set a value, or return a value. def set_number(self, num): self.count = num def get_numb...
"Method overloading" in python
I think the concept is called overloading. Right now I'm writing a class that will provide getter and setter methods, and am stuck on a design issue. Both methods are one-liners that simply set a value, or return a value. def set_number(self, num): self.count = num def get_number(self): return self.count Wou...
[ "In Python, you should prefer not to use getters and setters at all. Instead simply reference the count attribute directly, e.g. print instance.count or instance.count = 5\nThe point of getters and setters in other languages is for encapsulation and for future-proofing in case you need to add logic to the getters o...
[ 10, 2 ]
[ "I would leave it as two separate methods for the sake of code readabilty and maintainabilty.\n" ]
[ -1 ]
[ "overloading", "python" ]
stackoverflow_0006598835_overloading_python.txt
Q: How to access nested union members using SWIG? I have a structure like this in C: struct print_arg { struct print_arg *next; enum print_arg_type type; union { struct print_arg_atom atom; struct print_arg_field field; struct print_arg_typecast typecast; ...
How to access nested union members using SWIG?
I have a structure like this in C: struct print_arg { struct print_arg *next; enum print_arg_type type; union { struct print_arg_atom atom; struct print_arg_field field; struct print_arg_typecast typecast; struct print_arg_flags flags; str...
[ "My suggestion is to feed the C code and SWIG two different header files. Try this code:\nunion {\n struct print_arg_atom atom;\n struct print_arg_field field;\n ...\n} /*SWIG_VALUE*/;\n\nWhen you run SWIG to create the JNI code, replace /*SWIG_VALUE*/ with value. This should not change the addr...
[ 1 ]
[]
[]
[ "c", "python", "swig", "unions" ]
stackoverflow_0006597769_c_python_swig_unions.txt
Q: ViewDoesNotExist in webfaction I upload my project using FTP on webfaction and now using putty i logged in. But same project is working fine but after uploading it is giving error viewdoesnotexist i dont know what changes i have to do i am a newbie. And yeah! a have made changes in apache httpd.conf and created sc...
ViewDoesNotExist in webfaction
I upload my project using FTP on webfaction and now using putty i logged in. But same project is working fine but after uploading it is giving error viewdoesnotexist i dont know what changes i have to do i am a newbie. And yeah! a have made changes in apache httpd.conf and created scene_finder.wsgi. ViewDoesNotExist at...
[ "In your scene_finder.wsgi there'll probably be some code that sets up your PYTHONPATH. Make sure it includes /home/webapps/django/scene_finder/scene.\n" ]
[ 0 ]
[]
[]
[ "django", "python", "webfaction" ]
stackoverflow_0006597113_django_python_webfaction.txt
Q: Explanation of a decorator class in python While reading up about some python module I encountered this decorator class: # this decorator lets me use methods as both static and instance methods class omnimethod(object): def __init__(self, func): self.func = func def __get__(self, i...
Explanation of a decorator class in python
While reading up about some python module I encountered this decorator class: # this decorator lets me use methods as both static and instance methods class omnimethod(object): def __init__(self, func): self.func = func def __get__(self, instance, owner): return functool...
[ "that omnimethod is very clever. It uses some very subtle tricks to do it's job. Let's start at the beginning.\nYou probably already know that decorator syntax is just sugar for function application, ie:\n@somedecorator\ndef somefunc(...):\n pass\n\n# is the same thing as \n\ndef somefunc(...):\n pass\n...
[ 5, 1 ]
[]
[]
[ "decorator", "properties", "python" ]
stackoverflow_0006598534_decorator_properties_python.txt
Q: Python Packet Sniffer What Python module should I be using to sniff packets? I don't need anything too complex, I just need to get the data out of some packets being sent to my computer. I am using Python 2.6 and Windows 7, and I have installed WinPcap 4.1.2. So far I've seen people suggest pcapy and pypcap, but ...
Python Packet Sniffer
What Python module should I be using to sniff packets? I don't need anything too complex, I just need to get the data out of some packets being sent to my computer. I am using Python 2.6 and Windows 7, and I have installed WinPcap 4.1.2. So far I've seen people suggest pcapy and pypcap, but when I try to install those...
[ "py-pcap from dirtbags.net doesn't depend on a pcap lib so it might work for you. Though, I'm not sure how fast it is or if it works on windows.\nhttp://dirtbags.net/py-pcap.html\n", "Obviously you want to use a ready-made wrapper, but keep in mind that you can always use Ctypes to directly access the capture fun...
[ 0, 0 ]
[]
[]
[ "packet_capture", "packet_sniffers", "pcap", "python", "winpcap" ]
stackoverflow_0006598904_packet_capture_packet_sniffers_pcap_python_winpcap.txt
Q: Python splitting big lists into smaller lists for check performance? What is the best way to split a large list (over 1000 items) for performance purposes? And use "parts" of a large list? For example; I have a list of 10k addresses I want to scan. How can I split this list into a 4th, and finish the list by secti...
Python splitting big lists into smaller lists for check performance?
What is the best way to split a large list (over 1000 items) for performance purposes? And use "parts" of a large list? For example; I have a list of 10k addresses I want to scan. How can I split this list into a 4th, and finish the list by sections to increase performance?
[ "If you're reading all elements of the list, splitting will actually decrease your performance. You should profile your program (maybe post it in a question here, if you can sufficiently simplify it).\nIf you're not reading all elements, why are you using a list in the first place? Use a set or dict. Operations on ...
[ 2, 1, 0 ]
[]
[]
[ "list", "performance", "python" ]
stackoverflow_0006599593_list_performance_python.txt
Q: Mpdboot: Deprecation Warning I am trying to use the mpdboot command to start 4 processors on which to run my MPI program. I created a mpd.hosts file with 4 nodes (75, 77, 79 and 80). Each of them run python 2.3.4. I also modified the bashrc and cshrc files to ensure that the variables contain the path to the direc...
Mpdboot: Deprecation Warning
I am trying to use the mpdboot command to start 4 processors on which to run my MPI program. I created a mpd.hosts file with 4 nodes (75, 77, 79 and 80). Each of them run python 2.3.4. I also modified the bashrc and cshrc files to ensure that the variables contain the path to the directory of the compiler libraries. I ...
[ "A few points:\n\nYou really don't want to use MPD anymore. That process manager has been deprecated and replaced with the hydra process manager.\nYou must be using an old version of MPD (old version of MPICH2) because AFAIK all of those deprecation warnings were fixed as of the 1.1 release. I doubt you are actua...
[ 1, 0 ]
[]
[]
[ "mpi", "mpich", "mpiexec", "python" ]
stackoverflow_0006590343_mpi_mpich_mpiexec_python.txt
Q: Can i access c++ or Java functions inside python I am mainly using python for extensive algorithms operations. Now i have my webiste in Django. I few libraries in c++ and few in Java which i don't have in python. Or you can say that i already have some c++ , Java files in which some algorithm is coded. can i call ...
Can i access c++ or Java functions inside python
I am mainly using python for extensive algorithms operations. Now i have my webiste in Django. I few libraries in c++ and few in Java which i don't have in python. Or you can say that i already have some c++ , Java files in which some algorithm is coded. can i call those function or do some calculation in my djnago sit...
[ "For C++, certainly. Either write a module that wraps the library, or use something like ctypes or SWIG.\nFor Java, you'd be best to move to Jython (and correspondingly use django-jython).\nNote that using both C++ and Java from Python is not trivial.\n", "You could check the http://www.scipy.org/Weave weave pack...
[ 2, 0, 0 ]
[]
[]
[ "c++", "java", "linux", "python" ]
stackoverflow_0006200076_c++_java_linux_python.txt
Q: Finding Top Twitter Friends Using Python What's the best way to find someone's top friends on twitter? I'm trying to figure out a way to see who they interact with the most, but I am not sure what the best way is of doing this. Also, there are obvious things to check (is the username following that person, etc et...
Finding Top Twitter Friends Using Python
What's the best way to find someone's top friends on twitter? I'm trying to figure out a way to see who they interact with the most, but I am not sure what the best way is of doing this. Also, there are obvious things to check (is the username following that person, etc etc). I imagine someone else has thought about ...
[ "I read a research paper about that. You can find it at http://arxiv.org/abs/1105.5170\nThe researchers where interested in studying the \"strong relationships\" in the twitter social graph and they are using metrics base on the number of message between the user (@... mentions).\nI'm not a twitter user, but this l...
[ 0 ]
[]
[]
[ "graph", "python", "twitter" ]
stackoverflow_0002830264_graph_python_twitter.txt
Q: Python Lists and Yielding I have the following (correct) solution to Project Euler problem 24. I'm relatively new to Python, and am stumped on a couple of Python points. First, the code: # A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4....
Python Lists and Yielding
I have the following (correct) solution to Project Euler problem 24. I'm relatively new to Python, and am stumped on a couple of Python points. First, the code: # A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. # If all of the permutations a...
[ "When you recursively call getLexicographicPermutationsOf, you need to yield results from there too.\nfor result in getLexicographicPermutationsOf(rest, state):\n yield result\n\npermutations.append(str(state)) creates a string representation of state, which is a list. This explains why it looks like a list when...
[ 3, 0 ]
[]
[]
[ "list", "python", "python_3.x", "yield" ]
stackoverflow_0006598726_list_python_python_3.x_yield.txt
Q: Django view testing I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? A: The django.test.client would be the way to go. From the django docs from django.test.client ...
Django view testing
I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object?
[ "The django.test.client would be the way to go.\nFrom the django docs\nfrom django.test.client import Client\nc = Client()\nresponse = c.post('/login/', {'username': 'john', 'password': 'smith'})\nresponse.status_code\n\n", "If you're using Django 1.3, take a look at the included RequestFactory.\n", "You should...
[ 5, 2, 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006600039_django_python.txt
Q: Reading input from a scanner using serial port in Python I'm working on reading input from a scanner but I want to ask a question first then read the incoming data. This is what I have now. ser = serial.Serial() ser.baudrate = 9600 PORT = 1 #for windows ser = serial.Serial(PORT, 19200, timeout=1) x = ser.read() s...
Reading input from a scanner using serial port in Python
I'm working on reading input from a scanner but I want to ask a question first then read the incoming data. This is what I have now. ser = serial.Serial() ser.baudrate = 9600 PORT = 1 #for windows ser = serial.Serial(PORT, 19200, timeout=1) x = ser.read() s = ser.read(11) line = ser.readline() #Read input station = in...
[ "The link in your post is broken, and you don't mention what kind of serial device you're using, it's hard to know what you want to do.\nI don't think raw_input will do what you want, as the way you are using it in the above code, it would use standard out and standard in, and I'm assuming you want to print a quest...
[ 0, 0 ]
[]
[]
[ "python", "serial_port" ]
stackoverflow_0006599589_python_serial_port.txt
Q: Race condition with Python mmap and multiprocessing.semaphore I am writing a script that processes some mmaps concurrently with multiprocessing.Process and updates a result list stored in an mmap and locked with a mutex. My function to write to the result list looks like this def update_result(result_mmap, new_val...
Race condition with Python mmap and multiprocessing.semaphore
I am writing a script that processes some mmaps concurrently with multiprocessing.Process and updates a result list stored in an mmap and locked with a mutex. My function to write to the result list looks like this def update_result(result_mmap, new_value, new_value_index, sema): sema.acquire() result_mmap.seek...
[ "Maybe I'm wrong, but are you sure that the semaphore really works between the processes (is it a system mutex?). Because if it's not, processes do not share the same memory space. What you might want to consider using would be the threading library, in order for the threads to use the same semaphore.\n" ]
[ 1 ]
[]
[]
[ "concurrency", "mmap", "python" ]
stackoverflow_0006599804_concurrency_mmap_python.txt
Q: Inner join from two not directly related models in Django Let's say I have model like this (all irrelevant fields removed for clarity): A(Model): someFields = ... #irrelevant in this case B(Model): a = ForeignKey(A) my_data = ... #the data I need to retrieve C(Model): user = ForeingKey(User) a = F...
Inner join from two not directly related models in Django
Let's say I have model like this (all irrelevant fields removed for clarity): A(Model): someFields = ... #irrelevant in this case B(Model): a = ForeignKey(A) my_data = ... #the data I need to retrieve C(Model): user = ForeingKey(User) a = ForeignKey(A) class Meta: unique_together = ('user', 'a...
[ "Lucky for you your query uses an existing relation.\nB.objects.filter(a__c__user=someuser).distinct().values('my_data')\n\n" ]
[ 3 ]
[]
[]
[ "django", "django_models", "inner_join", "python", "sql" ]
stackoverflow_0006600184_django_django_models_inner_join_python_sql.txt
Q: py2exe and QSplashScreen I want to add QSplashScreen to PyQT4 application. It works fine from Python, but when I create exe with py2exe, a splash image is invisible, the app waits 2 sec and shows the main window. What is wrong? Application code: if __name__ == "__main__": app = QtGui.QApplication(sys.argv) ...
py2exe and QSplashScreen
I want to add QSplashScreen to PyQT4 application. It works fine from Python, but when I create exe with py2exe, a splash image is invisible, the app waits 2 sec and shows the main window. What is wrong? Application code: if __name__ == "__main__": app = QtGui.QApplication(sys.argv) # Create and display the spl...
[ "PNG support comes by default, JPEG support is by a plugin which will need to be included in some way.\nThere was a thread recently on the PySide mailing list about this sort of thing with cx_freeze, starts at http://lists.pyside.org/pipermail/pyside/2010-December/001656.html. the solution will be approximately the...
[ 2, 1 ]
[]
[]
[ "py2exe", "pyqt4", "python" ]
stackoverflow_0006597225_py2exe_pyqt4_python.txt
Q: How do you use Binary conversion in Python/Bash/AWK? I am new in binary conversion. I use Python, Bash and AWK daily. I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work. Where do you use binary conversion in Python/Ba...
How do you use Binary conversion in Python/Bash/AWK?
I am new in binary conversion. I use Python, Bash and AWK daily. I would like to see binary conversion's applications in these languages. For example, I am interested in problems which you solve by it at your work. Where do you use binary conversion in Python/Bash/AWK? I would like to see examples of codes.
[ "Conversion of strings of binary digits to a number using Python on the commandline:\nbinary=00001111\nDECIMAL=$(python -c \"print int('$BINARY', 2)\")\necho $decimal\n\nSee the docs for the int function.\nOh, wait, I misread the question, you want to know what converting to binary gets you. Well, that depends on ...
[ 3, 2, 0 ]
[]
[]
[ "awk", "bash", "binary", "python" ]
stackoverflow_0000756630_awk_bash_binary_python.txt
Q: Django - Mac development, environment hell I was trying to setup Django dev environment on Mac and arrived into a hell. It all started when trying to install PIL, which failed after trying 15 or so different recipes I found on blogs. So I wanted to install the Python, this time 2.7, and reinstall setuptools, easy_...
Django - Mac development, environment hell
I was trying to setup Django dev environment on Mac and arrived into a hell. It all started when trying to install PIL, which failed after trying 15 or so different recipes I found on blogs. So I wanted to install the Python, this time 2.7, and reinstall setuptools, easy_install, pip from scratch. After just installin...
[ "It wouldn't hurt to run a VM with vagrant. This post should tell you more:\nhttp://stevelosh.com/blog/2011/06/django-advice/\nOf course using virtualenv should also help alleviate some of these issues.\n", "I've gone through the same hell 2 weeks ago :)\nI needed to make working python 2.7 and virtualenv on OSX ...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "django", "macos", "python", "python_imaging_library" ]
stackoverflow_0006589684_django_macos_python_python_imaging_library.txt
Q: django frontend to run subprocess output to browser window I basically have a backend program written in perl. This program pushes some configuration onto a network device. It gives a lot of output and I want users to be able to see the program as it runs. Up to now this has been easy as I have been running from t...
django frontend to run subprocess output to browser window
I basically have a backend program written in perl. This program pushes some configuration onto a network device. It gives a lot of output and I want users to be able to see the program as it runs. Up to now this has been easy as I have been running from the terminal. Now I am trying to write a django app. I basically ...
[ "You can read the output of the subprocess like so...\npipe = subprocess.Popen(command.split(), stdout=subprocess.PIPE)\nresult = pipe.stdout.read() # this is the output of the process\nreturn render_to_response('config/config.html', {'result': result})\n\nHowever, you will only be able to see the result after the ...
[ 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006599783_django_python.txt
Q: Python Idle and KeyboardInterrupts KeyboardInterrupts in Idle work for me 90% of the time, but I was wondering why they don't always work. In Idle, if I do import time time.sleep(10) and then attempt a KeyboardInterrupt using Ctrl+C, it does not interrupt the process until after sleeping for 10 seconds. The same ...
Python Idle and KeyboardInterrupts
KeyboardInterrupts in Idle work for me 90% of the time, but I was wondering why they don't always work. In Idle, if I do import time time.sleep(10) and then attempt a KeyboardInterrupt using Ctrl+C, it does not interrupt the process until after sleeping for 10 seconds. The same code and a KeyboardInterrupt via Ctrl+C ...
[ "A quick glance at the IDLE source reveals that KeyboardInterrupts have some special case handling: http://svn.python.org/view/python/tags/r267/Lib/idlelib/PyShell.py?annotate=88851\nOn top of that, code is actually executed in a separate process which the main IDLE gui process communicates with via RPC. You're go...
[ 8, 1 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0006598974_python_python_idle.txt
Q: Is there a way to determine if a python script was started by Cron? Possible Duplicate: How can I determine if a python script is executed from crontab? Is there a way to determine if a python script was started by cron or not? A: Not per se, but you could set an environment variable in the crontab and check i...
Is there a way to determine if a python script was started by Cron?
Possible Duplicate: How can I determine if a python script is executed from crontab? Is there a way to determine if a python script was started by cron or not?
[ "Not per se, but you could set an environment variable in the crontab and check it in the script.\n* * * * * CRONRUN=y /srv/cron/foo.py\n\n...\nif 'CRONRUN' in os.environ:\n ...\n\n", "Without knowing what your script does, I can give a couple of suggestions.\nIf the script runs then terminates, have the script...
[ 8, 0 ]
[]
[]
[ "cron", "python" ]
stackoverflow_0006600935_cron_python.txt
Q: Colorbar for matplotlib plot_surface command I have modified the mplot3d example code for my application with Paul's help. The code reads: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') u = np.linspace(0, 2...
Colorbar for matplotlib plot_surface command
I have modified the mplot3d example code for my application with Paul's help. The code reads: from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.add_subplot(111, projection='3d') u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x =...
[ "You can use a proxy mappable object since your surface array is not mapped. The mappable simply converts the values of any array to RGB colors defined by a colormap.\nIn your case you want to do this with the z1 array:\nimport matplotlib.cm as cm\nm = cm.ScalarMappable(cmap=cm.jet)\nm.set_array(z1)\nplt.colorbar(...
[ 49 ]
[]
[]
[ "matplotlib", "python" ]
stackoverflow_0006600579_matplotlib_python.txt
Q: How can I understand using of complex() function? In python documentation it is wrote for built-in function complex([real[imag]]): ..or convert a string or number to a complex number. But when I try: >>> complex('string') I get: Traceback (most recent call last): File "<interactive input>", line 1, in <modu...
How can I understand using of complex() function?
In python documentation it is wrote for built-in function complex([real[imag]]): ..or convert a string or number to a complex number. But when I try: >>> complex('string') I get: Traceback (most recent call last): File "<interactive input>", line 1, in <module> ValueError: complex() arg is a malformed string ...
[ "complex is a data type for complex numbers.\nhttp://en.wikipedia.org/wiki/Complex_number\nExamples on constructing them:\n>>> complex(1, 2)\n(1+2j)\n>>> complex('1+2j')\n(1+2j)\n>>> complex(0)\n0j\n>>> complex(1)\n(1+0j)\n>>> complex(1) + complex(0, 1)\n(1+1j)\n\nIf you aren't familiar with complex or imaginary nu...
[ 5, 4, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006601288_python.txt
Q: OpenCV Python Import Module I'm having some issues. I've installed OpenCV 2.3 on an ec2 ubuntu instance - and compiled with the necessaries for python integration. I realised that python was behind so upgraded that to 2.6 afterwards. All should be good. However, running a basic .py script and calling OpenCV in isn...
OpenCV Python Import Module
I'm having some issues. I've installed OpenCV 2.3 on an ec2 ubuntu instance - and compiled with the necessaries for python integration. I realised that python was behind so upgraded that to 2.6 afterwards. All should be good. However, running a basic .py script and calling OpenCV in isn't working. Forgive me if this is...
[ "You'll need to rebuild OpenCV against the new Python you've installed.\npython2.6 setup.py install\n\n" ]
[ 2 ]
[]
[]
[ "linux", "opencv", "python", "ubuntu" ]
stackoverflow_0006601395_linux_opencv_python_ubuntu.txt
Q: Using Python to send email, sourcing the recipient list from a text file I have been able to scrape together the below code, which I can now use to send an email via OSX10.6. What I wish to add to this script however is the ability to 'source' the recipient list directly from a text file within the same directory ...
Using Python to send email, sourcing the recipient list from a text file
I have been able to scrape together the below code, which I can now use to send an email via OSX10.6. What I wish to add to this script however is the ability to 'source' the recipient list directly from a text file within the same directory as the python file itself. I also wish to hard code the 'sender' element beca...
[ "You might want to replace this piece of code:\n# Variable to hold the recipients string\nrec = \"\"\n# Open recipients file\nf = open(opts.recipients)\n# Loop through each line of the file\nfor line in f:\n # Remove whitespace from line and add COMMASPACE\n rec += line.rstrip() + COMMASPACE\nf.close()\n\nby ...
[ 1, 0, 0 ]
[]
[]
[ "email", "osx_snow_leopard", "python" ]
stackoverflow_0006019736_email_osx_snow_leopard_python.txt
Q: Python/Scrapy question: How to get cleaner results? My task for a project is to data mine a website for specific names. My experience with python isn't high. When I scraped all the names, they come out in this format: [u'Bob Joe'] [u'Tim Tom'] [u'Anne Frank'] [u'superman'] How can I clean up these values? What d...
Python/Scrapy question: How to get cleaner results?
My task for a project is to data mine a website for specific names. My experience with python isn't high. When I scraped all the names, they come out in this format: [u'Bob Joe'] [u'Tim Tom'] [u'Anne Frank'] [u'superman'] How can I clean up these values? What does the 'u' signify? Is my xpath wrong? Would I have to c...
[ "In Python 2, the 'u' prefix indicates that it's a Unicode string. [u'Bob Joe'] is a list containing a Unicode string.\n" ]
[ 1 ]
[]
[]
[ "data_mining", "pipeline", "python", "scrapy" ]
stackoverflow_0006601565_data_mining_pipeline_python_scrapy.txt
Q: Django many-to-many relationships: prevailing naming convention I am hoping to hear from some people with experience developing Django sites as part of some sort of team. What is the naming convention most commonly seen for many-to-many relationships? Do most people stick with the entry_set default, or is it more...
Django many-to-many relationships: prevailing naming convention
I am hoping to hear from some people with experience developing Django sites as part of some sort of team. What is the naming convention most commonly seen for many-to-many relationships? Do most people stick with the entry_set default, or is it more common and easier to use a more symmetrical related_name='entries' a...
[ "The _set suffix indicates that the attribute is a manager rather than a model, and should be retained in order to minimize confusion.\n" ]
[ 4 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006601626_django_python.txt
Q: Execute Python script (that reads user data on computer) in Google Chrome extension - NPAPI http://code.google.com/chrome/extensions/npapi.html I have read through this, and am thoroughly confused. I have built the sample npapi .so plugin from http://www.firebreath.org/display/documentation/Building+on+Linux Ever...
Execute Python script (that reads user data on computer) in Google Chrome extension - NPAPI
http://code.google.com/chrome/extensions/npapi.html I have read through this, and am thoroughly confused. I have built the sample npapi .so plugin from http://www.firebreath.org/display/documentation/Building+on+Linux Everything worked fine (plugin is installed correctly and recognized) until I went to use it in my po...
[ "where is your extra () coming from? Most likely it should be this:\nconsole.log(document.getElementById(\"sample\").echo(\"asdf\"));\n\nWhat you were trying to do would probably end up trying to call the \"default\" method on the NPObject, which is probably nonexistent and will thus throw an exception.\n" ]
[ 0 ]
[]
[]
[ "cython", "firebreath", "google_chrome_extension", "npapi", "python" ]
stackoverflow_0006594019_cython_firebreath_google_chrome_extension_npapi_python.txt
Q: 'Not connected to the database' on Django admin site with MongoDB through django-nonrel I am trying to configure the Django admin site for my django application by following the instructions here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/ . I run the development server but when I try to access /admi...
'Not connected to the database' on Django admin site with MongoDB through django-nonrel
I am trying to configure the Django admin site for my django application by following the instructions here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/ . I run the development server but when I try to access /admin url I get an error with a stack trace saying that there is no connection to the database. I...
[ "(Posting as an answer so you can close the question)\nPer the docs, you do need to explicitly connect to MongoDB using the connect() method. This can be a simple\nconnect('dbname')\n\nIf you're running MongoDB on your local machine, and also accepts keyword arguments for host, port (should be an int), username, an...
[ 1 ]
[]
[]
[ "django", "django_nonrel", "mongodb", "python" ]
stackoverflow_0006597259_django_django_nonrel_mongodb_python.txt
Q: Checking whether some text consists only of some pattern I have the following problem: I'm trying to check whether some text consists only of a number of repetitions of some pattern. I.e I have a 1000 lines text and want to check if it consists only of asd 123 I tried matching not the pattern, but (pattern)+ hopi...
Checking whether some text consists only of some pattern
I have the following problem: I'm trying to check whether some text consists only of a number of repetitions of some pattern. I.e I have a 1000 lines text and want to check if it consists only of asd 123 I tried matching not the pattern, but (pattern)+ hoping that it will match whatever there is to match but it was to...
[ "Try matching the string with ^(?:asd|123)+$, if it matches, then it only contains combinations of asd or 123 (at least one).\n", "Perhaps you meant: ^(abc|123)+$\n", "I haven't tried this in Python, but the regex for what you are asking for would be the following:\n.asd$\n.123$\n\nTry reading through the follo...
[ 1, 1, 1 ]
[]
[]
[ "matching", "python", "regex" ]
stackoverflow_0006602005_matching_python_regex.txt
Q: Detecting graceful shut downs of sockets in python I'm trying to determine if a server socket was shut down gracefully or not in python. The program received files and if some error occurs during the send the file should be removed. I know your first suggestion will be to let the client send either the length of t...
Detecting graceful shut downs of sockets in python
I'm trying to determine if a server socket was shut down gracefully or not in python. The program received files and if some error occurs during the send the file should be removed. I know your first suggestion will be to let the client send either the length of the file or some terminating data to let the server know ...
[ "If the other end has finished sending data, they should shutdown (2) the socket for writing. Then in your multiplexing loop you would be able to check if the socket has been shutdown for writing or has just be closed (writing & reading) by the remote end. This is a graceful shutdown and you can use select/poll/kqu...
[ 1, 0 ]
[]
[]
[ "python", "serversocket", "sockets" ]
stackoverflow_0006590400_python_serversocket_sockets.txt
Q: How to make a parent thread wait either specified amount of time or until the child thread finishes? Right now, my parent thread starts the child thread and then proceeds to time.sleep() a certain amount of time. Is there any way I can get my parent thread to sleep OR thread.join()? (If I remember right thread.joi...
How to make a parent thread wait either specified amount of time or until the child thread finishes?
Right now, my parent thread starts the child thread and then proceeds to time.sleep() a certain amount of time. Is there any way I can get my parent thread to sleep OR thread.join()? (If I remember right thread.join() is the one that waits for the child thread to finish) thread = threading.Thread(target=whatever, args=...
[ "Pass a 60 second timeout to the join() function:\nthread.join(60)\n\nAfter that call has returned, you can check if the thread joined or timed out based on the isAlive() call.\n" ]
[ 6 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0006602368_multithreading_python.txt
Q: How to group a list of tuples/objects by similar index/attribute in python? Given a list old_list = [obj_1, obj_2, obj_3, ...] I want to create a list: new_list = [[obj_1, obj_2], [obj_3], ...] where obj_1.some_attr == obj_2.some_attr. I could throw some for loops and if checks together, but this is ugly. Is the...
How to group a list of tuples/objects by similar index/attribute in python?
Given a list old_list = [obj_1, obj_2, obj_3, ...] I want to create a list: new_list = [[obj_1, obj_2], [obj_3], ...] where obj_1.some_attr == obj_2.some_attr. I could throw some for loops and if checks together, but this is ugly. Is there a pythonic way for this? by the way, the attributes of the objects are all str...
[ "defaultdict is how this is done.\nWhile for loops are largely essential, if statements aren't.\nfrom collections import defaultdict\n\n\ngroups = defaultdict(list)\n\nfor obj in old_list:\n groups[obj.some_attr].append(obj)\n\nnew_list = groups.values()\n\n", "Here are two cases. Both require the following im...
[ 89, 37, 16 ]
[]
[]
[ "grouping", "list", "python" ]
stackoverflow_0006602172_grouping_list_python.txt
Q: Dynamically loading and static loading modules in Django Is any difference between the dynamically loading and static loading modules in Django? How about its efficiency? Who can tell me the principles about the mechanism of dynamically loading and static loading modules in Django? A: First, this is a Python que...
Dynamically loading and static loading modules in Django
Is any difference between the dynamically loading and static loading modules in Django? How about its efficiency? Who can tell me the principles about the mechanism of dynamically loading and static loading modules in Django?
[ "First, this is a Python question, not a Django one as modules are a Python concept.\nSecondly, there is no such thing as static loading in Python because it's an dynamic language by essence.\nTherefor, loading a module in Python is always dynamic.\nThe only thing you should know are:\n\nonce a module is imported, ...
[ 0, 0 ]
[]
[]
[ "django", "django_models", "loading", "python" ]
stackoverflow_0006569721_django_django_models_loading_python.txt
Q: Save a table as text What i have right now: oname = open("1231.txt","w") def cC_(): d_=" fahrenheit celsius" print(d_) for i in range(-300,213,1): c_=(i-32)*(5/9) a_=str(i)+'°F' b_=str(round(c_,3))+'°C' ...
Save a table as text
What i have right now: oname = open("1231.txt","w") def cC_(): d_=" fahrenheit celsius" print(d_) for i in range(-300,213,1): c_=(i-32)*(5/9) a_=str(i)+'°F' b_=str(round(c_,3))+'°C' print("%10s" % (a_), ' ...
[ "def cC_(fout=sys.stdout):\n ...\n print(..., file=fout)\n ...\n\nwith open(..., 'w') as oname:\n cC_(oname)\n\n", "You are writing functions return value, not the strings printed in function.\nYou should change print calls to oname.write.\nwith open(\"1231.txt\",\"w\") as oname:\n oname.write(\" fahre...
[ 2, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0006600852_python.txt
Q: How can I determine a Unicode character from its name in Python, even if that character is a control character? I'd like to create an array of the Unicode code points which constitute white space in JavaScript (minus the Unicode-white-space code points, which I address separately). These characters are horizontal...
How can I determine a Unicode character from its name in Python, even if that character is a control character?
I'd like to create an array of the Unicode code points which constitute white space in JavaScript (minus the Unicode-white-space code points, which I address separately). These characters are horizontal tab, vertical tab, form feed, space, non-breaking space, and BOM. I could do this with magic numbers: whitespace = ...
[ "Kerrek SB's comment is a good one: just put the names in a comment. \nBTW, Python also supports a named unicode literal: \n>>> u\"\\N{NO-BREAK SPACE}\"\nu'\\xa0'\n\nBut it uses the same unicode name database, and the control characters are not in it.\n", "You could roll your own \"database\" for the control ch...
[ 13, 2, 2, 1, 0, 0 ]
[ "You can extend the lookup function to handle the characters that aren't included.\ndef unicode_lookup(x):\n try:\n ch = unicodedata.lookup(x)\n except KeyError:\n control_chars = {'LINE FEED':unichr(0x0a),'CARRIAGE RETURN':unichr(0x0d)}\n if x in control_chars:\n ch = control_...
[ -1 ]
[ "python", "unicode" ]
stackoverflow_0006589586_python_unicode.txt
Q: How to start a Python script from Django website? I've made a Django website, whence I would like to call a Python program that I currently start from the command line. I imagine doing it by clicking on a link or button. I know this must be a one-liner, but I'm stumped. A: Here is an article from Guido Van Rossu...
How to start a Python script from Django website?
I've made a Django website, whence I would like to call a Python program that I currently start from the command line. I imagine doing it by clicking on a link or button. I know this must be a one-liner, but I'm stumped.
[ "Here is an article from Guido Van Rossum, who created python, on doing this. Essentially, you just want to invoke your main() function from your controller.\n", "import yourscript # is in yourscript.py\n\nyourclass = yourscript.Yourclass()\nyourclass.run()\n\nOr something like that?\n" ]
[ 3, 2 ]
[]
[]
[ "button", "django", "hyperlink", "python" ]
stackoverflow_0006602913_button_django_hyperlink_python.txt
Q: Logging into Facebook without a Browser I'm working on a script currently that needs to pull information down from a specific user's wall. The only problem is that it requires authentication, and the script needs to be able to run without any human interference. Unfortunately all I can find thus far tells me that ...
Logging into Facebook without a Browser
I'm working on a script currently that needs to pull information down from a specific user's wall. The only problem is that it requires authentication, and the script needs to be able to run without any human interference. Unfortunately all I can find thus far tells me that I need to register an application, and then d...
[ "What you are trying to do is not possible. You are going to have to use a browser to get an access token one way or another. You cannot collect username and passwords (a big violation of Facebook's TOS). If you need a script that runs without user interaction you will still need to use a browser to authenticate, b...
[ 5, 3, 2 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0004000896_facebook_python.txt
Q: Twisted server TLS hanging on connection I have a twisted webserver with TLS authentication, and it appears to hang when I connect to it over SMTP. Here is the block of twisted code to start the server: (Note: certificateData is our private key and public key concatenated together, that appeared to be the only wa...
Twisted server TLS hanging on connection
I have a twisted webserver with TLS authentication, and it appears to hang when I connect to it over SMTP. Here is the block of twisted code to start the server: (Note: certificateData is our private key and public key concatenated together, that appeared to be the only way to get a self signed certificate to work) cu...
[ "Your server starts TLS from the beginning of the connection. Try smtplib.SMTP_SSL instead, so your client expects this.\n" ]
[ 3 ]
[]
[]
[ "python", "smtp", "ssl", "twisted" ]
stackoverflow_0006602709_python_smtp_ssl_twisted.txt
Q: Diffrence between instance variables and attributes in python? So, the python docs for writing extension says this: "We want to expose our instance variables as attributes. There are a number of ways to do that. The simplest way is to define member definitions: static PyMemberDef Noddy_members[] = { {...
Diffrence between instance variables and attributes in python?
So, the python docs for writing extension says this: "We want to expose our instance variables as attributes. There are a number of ways to do that. The simplest way is to define member definitions: static PyMemberDef Noddy_members[] = { {"first", T_OBJECT_EX, offsetof(Noddy, first), 0, "first name"},...
[ "Writing a C extension is a complex process, because you have to write C code, and you have to provide enough information to Python so that it can manipulate your C data as if it were Python data. You have to mention the members of the struct twice: once for the C compiler to know how to make the struct, and then ...
[ 3, 1 ]
[]
[]
[ "c", "cython", "python", "python_c_api", "python_c_extension" ]
stackoverflow_0006539271_c_cython_python_python_c_api_python_c_extension.txt
Q: Ajax AutoComplete Feature with Prototype and Django I would like to integrate Django, and the JavaScript prototype library to create an autocomplete feature for a form. Can anyone recommend a prototype feature that has been tried with Django? There is this code and also this and I'm wondering if anyone would recom...
Ajax AutoComplete Feature with Prototype and Django
I would like to integrate Django, and the JavaScript prototype library to create an autocomplete feature for a form. Can anyone recommend a prototype feature that has been tried with Django? There is this code and also this and I'm wondering if anyone would recommend one over the other for use with Django. Thanks!
[ "I downloaded the code from this site\nand followed the directions there, which was straightforward. Just include the prototype.js, scriptaculous.js, and AutoComplete.js files. Then copy paste from the directions, and change the url from assets/ac.php?m=text&s= to ?m=text&s= or even just ?s= if one query parameter ...
[ 1 ]
[]
[]
[ "ajax", "autocomplete", "django", "prototypejs", "python" ]
stackoverflow_0006589207_ajax_autocomplete_django_prototypejs_python.txt
Q: Python STILL won't allow Japanese Characters despite specifying the encoding #!/usr/bin/env python # -*- coding: utf8 -*- print "私" print u"私" the result: ç§ UnicodeEncodeError: 'ascii' codec can't encode character u'\u79c1' in position 0: ordinal not in range(128) Or, in Idle for both u"私" and "私": >>> print "...
Python STILL won't allow Japanese Characters despite specifying the encoding
#!/usr/bin/env python # -*- coding: utf8 -*- print "私" print u"私" the result: ç§ UnicodeEncodeError: 'ascii' codec can't encode character u'\u79c1' in position 0: ordinal not in range(128) Or, in Idle for both u"私" and "私": >>> print "私" Unsupported characters in input I've followed all the advice I could find whic...
[ "You specified the encoding of the source file and supposedly saved the files using UTF-8.\nStill your stdout is using ascii so it is normal to fail. \nYou have an encoding issue not a decoding issue, Python does read your Unicode characters just fine, probably will be able to save them inside a file if you choose ...
[ 6, 3, 2, 0 ]
[]
[]
[ "python", "unicode" ]
stackoverflow_0006584984_python_unicode.txt
Q: Javascript (and HTML rendering) engine without a GUI for automation? Are there any libraries or frameworks that provide the functionality of a browser, but do not need to actually render physically onto the screen? I want to automate navigation on web pages (Mechanize does this, for example), but I want the full b...
Javascript (and HTML rendering) engine without a GUI for automation?
Are there any libraries or frameworks that provide the functionality of a browser, but do not need to actually render physically onto the screen? I want to automate navigation on web pages (Mechanize does this, for example), but I want the full browser experience, including Javascript. Thus, I'd like to have a virtual ...
[ "PhantomJS and PyPhantomJS are what I use for tasks like these.\nWhat it is, is a headless WebKit based browser which is fully controllable via JavaScript. There's a C++ implementation (PhantomJS) and a Python one (PyPhantomJS). I prefer the Python one though, because it has a plugin system which allows you to add ...
[ 3, 2, 1, 1, 1, 1, 0 ]
[]
[]
[ "automation", "javascript", "mechanize", "python", "rendering" ]
stackoverflow_0002716230_automation_javascript_mechanize_python_rendering.txt
Q: Python- is there a module that will automatically scrape the content of an article off a webpage? I know there is lxml and BeautifulSoup, but that won't work for my project, because I don't know in advance what the HTML format of the site I am trying to scrape an article off of will be. Is there a python-type modu...
Python- is there a module that will automatically scrape the content of an article off a webpage?
I know there is lxml and BeautifulSoup, but that won't work for my project, because I don't know in advance what the HTML format of the site I am trying to scrape an article off of will be. Is there a python-type module similar to Readability that does a pretty good job at finding the content of an article and returnin...
[ "It's possible to do using PhantomJS (C++) or PyPhantomJS (Python).\nThey're both headless WebKit based browsers, which you can fully control from JavaScript. Because you can control it from JavaScript, I find it is really easy to do stuff such as scrape the content of an article.\nPyPhantomJS also has a plugin sys...
[ 1, 0, 0 ]
[]
[]
[ "algorithm", "beautifulsoup", "lxml", "python", "screen_scraping" ]
stackoverflow_0006543599_algorithm_beautifulsoup_lxml_python_screen_scraping.txt
Q: Can I change the base class value in a python subclass? When subclassing a base type, like float, is it possible to "recalculate" or "reassign" the original value? If I have the following class definition, import collections class MovingAverage(float): def __new__(self, initial_value, window): self.d ...
Can I change the base class value in a python subclass?
When subclassing a base type, like float, is it possible to "recalculate" or "reassign" the original value? If I have the following class definition, import collections class MovingAverage(float): def __new__(self, initial_value, window): self.d = collections.deque([initial_value], window) return f...
[ "No. Since these types are immutable, you should be using encapsulation, not inheritance.\n", "I don't think that Ignacios answer above needs any improvements, but since I had this class laying around I just thought I should share. It avoids doing big sum operations many times and also avoids rounding errors that...
[ 5, 2 ]
[]
[]
[ "python", "subclass" ]
stackoverflow_0006602791_python_subclass.txt
Q: Selenium 2.0rc3 click function too fast? First off, sorry for the cryptic question. My team is currently using Selenium 2.0rc3 (with python) for testing our web app with chrome. When we used the 2.02b version of Selenium, our test passed (it was a little slow and we had small hacks that we added to webdriver). Aft...
Selenium 2.0rc3 click function too fast?
First off, sorry for the cryptic question. My team is currently using Selenium 2.0rc3 (with python) for testing our web app with chrome. When we used the 2.02b version of Selenium, our test passed (it was a little slow and we had small hacks that we added to webdriver). After we upgraded, the test became extremely fast...
[ "Your problem is not really that it's clicking too fast. Just that it's clicking before that element is present. There are two ways to get round this:\n\nWait until the element is present before clicking\nIncrease the implicit wait time\n\nI'm afraid I haven't used the WebDriver Python bindings. However, I can tell...
[ 5, 1, 0 ]
[]
[]
[ "python", "selenium", "webdriver" ]
stackoverflow_0006602151_python_selenium_webdriver.txt
Q: How to define and fill a dict of dicts of lists I have to fill a dictionary of the type: partial[sequence][exp_id] = [item_1, ..., item_n] this can be done in this way: partial = defaultdict(dict) for sequence in sequences: for exp_id in exp_ids: for item in data: partial[sequence].setdefaul...
How to define and fill a dict of dicts of lists
I have to fill a dictionary of the type: partial[sequence][exp_id] = [item_1, ..., item_n] this can be done in this way: partial = defaultdict(dict) for sequence in sequences: for exp_id in exp_ids: for item in data: partial[sequence].setdefault(eid, []).append(item) Is there a more effective wa...
[ "partial = defaultdict(lambda: defaultdict(list))\n\n", "try:\npartial = defaultdict(lambda: defaultdict(list))\n\n" ]
[ 6, 6 ]
[]
[]
[ "defaultdict", "dictionary", "python" ]
stackoverflow_0006603718_defaultdict_dictionary_python.txt
Q: Writing a single table value in sqlite3 I have a Python 2.7 project, and I'm using (and learning) sqlite3. How do I save a variable from python to a single existing column and row in an sqlite3 database? A: Say you have a table named "records" with the column "X", and each entry has a different "X" value, and le...
Writing a single table value in sqlite3
I have a Python 2.7 project, and I'm using (and learning) sqlite3. How do I save a variable from python to a single existing column and row in an sqlite3 database?
[ "Say you have a table named \"records\" with the column \"X\", and each entry has a different \"X\" value, and let's say you want to change the value of column \"Y\". You would use this SQL query:\ncursor.execute(\"update records set y = ? where x = ?\", (y, x))\n\n", "If you are not familiar with SQL, you could ...
[ 4, 0 ]
[]
[]
[ "python", "sqlite" ]
stackoverflow_0006602390_python_sqlite.txt
Q: fetchone() is setting int variable to tuple I have a project with Python 2.7 and SQLite3. I am trying to store an integer variable in an SQLite3 database column, and then later be able to set a variable to the value of the SQLite column. The connection is fine, the column exists, and it is type "int". I am using t...
fetchone() is setting int variable to tuple
I have a project with Python 2.7 and SQLite3. I am trying to store an integer variable in an SQLite3 database column, and then later be able to set a variable to the value of the SQLite column. The connection is fine, the column exists, and it is type "int". I am using this code to pull the data: Trailcrest.fish_sc...
[ "fetchone() still returns a Row-like object, which you'll need to parse the lone field out of it, so you'll need to get the data out of it \nrow = c.execute(\"SELECT fish_score FROM roster WHERE agentnumber = ?;\", (AN,) ).fetchone()\nif row is not None: # or just \"if row\"\n Trailcrest.fish_score = row[0]\nel...
[ 7 ]
[]
[]
[ "integer", "python", "sqlite", "tuples", "variables" ]
stackoverflow_0006603796_integer_python_sqlite_tuples_variables.txt
Q: FFmpeg VS PyFFmpeg performance wise? Lets say for batch processing of over 10000 videos, is there any thing to be gained from using FFmpeg rather than the pyFFmpeg? A: Considering that pyFFmpeg is just a wrapper over the libraries, I'd say you shouldn't have any negligible performance difference between the 2, s...
FFmpeg VS PyFFmpeg performance wise?
Lets say for batch processing of over 10000 videos, is there any thing to be gained from using FFmpeg rather than the pyFFmpeg?
[ "Considering that pyFFmpeg is just a wrapper over the libraries, I'd say you shouldn't have any negligible performance difference between the 2, since they use the same libraries at the core.\n" ]
[ 5 ]
[]
[]
[ "ffmpeg", "python", "video_encoding" ]
stackoverflow_0006603810_ffmpeg_python_video_encoding.txt
Q: Javascript issue inside of a Python Module I'm trying to have Python run some Javascript, and I am running into a few issues. Namely that when I am trying to inject some text into a textarea of a page, it doesn't seem to work if and only if there is a newline (\n) as part of the variable inserted for the Javascrip...
Javascript issue inside of a Python Module
I'm trying to have Python run some Javascript, and I am running into a few issues. Namely that when I am trying to inject some text into a textarea of a page, it doesn't seem to work if and only if there is a newline (\n) as part of the variable inserted for the Javascript. Here's my line: br.runjs("document.getElement...
[ "Encode brag as JSON and then use that.\n" ]
[ 2 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0006603994_javascript_python.txt
Q: How to fetch the datastore(app engine) record without instantiating a model? Hi can anyone tell me how it can be done,i am a beginner. I tried using this: def get_entities(keys): rpc = datastore.GetRpcFromKwargs({}) keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys) entities = None try: ...
How to fetch the datastore(app engine) record without instantiating a model?
Hi can anyone tell me how it can be done,i am a beginner. I tried using this: def get_entities(keys): rpc = datastore.GetRpcFromKwargs({}) keys, multiple = datastore.NormalizeAndTypeCheckKeys(keys) entities = None try: entities = datastore.Get(keys, rpc=rpc) except datastore_errors.EntityNot...
[ "do you mean you want datastore.Entity objects instead of Model instances? if so, assuming keys is a list, you should be able to simplify your code to this:\nreturn datastore.Get(keys)\notherwise, if you just want to see which keys have matching entities in the datastore, try this:\nreturn db.GqlQuery('SELECT __key...
[ 1 ]
[]
[]
[ "google_cloud_datastore", "python" ]
stackoverflow_0006557606_google_cloud_datastore_python.txt
Q: Django In-Memory SQLite3 Database I'm trying to have a purely in-memory SQLite database in Django, and I think I have it working, except for an annoying problem: I need to run syncdb before using the database, which isn't too much of a problem. The problem is that it needs to create a superuser (in the auth_user t...
Django In-Memory SQLite3 Database
I'm trying to have a purely in-memory SQLite database in Django, and I think I have it working, except for an annoying problem: I need to run syncdb before using the database, which isn't too much of a problem. The problem is that it needs to create a superuser (in the auth_user table, I think) which requires interacti...
[ "Any inputs or prompts of django-admin.py may be suppressed using the --noinput option, such as \n./manage.py syncdb --noinput\n\nThis will skip the super user creation on the initial syncdb run and thus requires you to create one either using fixtures or an custom method as receiver of the post_syncdb signal.\nSee...
[ 6, 3, 1 ]
[]
[]
[ "database", "django", "in_memory_database", "python", "sqlite" ]
stackoverflow_0006599716_database_django_in_memory_database_python_sqlite.txt
Q: How to rename a directory in Mercurial and continue to track all file changes I decided to rename some directories in my home/hobby Python package (doc to docs, test to tests, util to utils) because, now that I've thought more about it, I think the new names are more appropriate. My general thinking now is that if...
How to rename a directory in Mercurial and continue to track all file changes
I decided to rename some directories in my home/hobby Python package (doc to docs, test to tests, util to utils) because, now that I've thought more about it, I think the new names are more appropriate. My general thinking now is that if containers are named after their contents their names should be plural nouns. Now ...
[ "Since you've already renamed the directories, this is perfectly OK. (It would have saved you a manual step if you'd let Mercurial rename them for you: hg rename doc docs, etc. instead of doing it yourself then letting Mercurial know about it).\nIf you don't have any other files to check in, the hg addremove is su...
[ 44, 17, 11 ]
[]
[]
[ "mercurial", "python" ]
stackoverflow_0003535676_mercurial_python.txt
Q: Sending multiline commands to Maya Through Python Socket I want to know is there a way to send a multiline command to maya through python socket and the Maya's own "commandPort" command? I'm using below code for sending the code to maya("message" value is the command): import socket #HOST = '192.168.1.122' # The ...
Sending multiline commands to Maya Through Python Socket
I want to know is there a way to send a multiline command to maya through python socket and the Maya's own "commandPort" command? I'm using below code for sending the code to maya("message" value is the command): import socket #HOST = '192.168.1.122' # The remote host HOST = '127.0.0.1' # the local host PORT = 54321 ...
[ "Try: \ncommand = 'import maya.cmds as mc\\n mc.polyCube()'\n\n", "For sending small commands to Maya, @pajton's method works, or you can use ; as a separator:\ncommand = \"import maya.cmds as mc; mc.polyCube()\"\n\nIf possible, the easiest way to send many lines at once is to create a separate .py file that Maya...
[ 2, 1 ]
[]
[]
[ "maya", "python" ]
stackoverflow_0006485059_maya_python.txt
Q: Is it ok to spawn threads in a wsgi-application? To achieve something similar to google app engines 'deferred calls' (i.e., the request is handled, and afterwards the deferred task is handled), i experimented a little and came up with the solution to spawn a thread in which my deferred call is handled. I am now tr...
Is it ok to spawn threads in a wsgi-application?
To achieve something similar to google app engines 'deferred calls' (i.e., the request is handled, and afterwards the deferred task is handled), i experimented a little and came up with the solution to spawn a thread in which my deferred call is handled. I am now trying to determine if this is an acceptable way. Is it ...
[ "WSGI does not specify the lifetime of an application process (as WSGI application is a Python callable object). You can run it in a way that is completely independent of the web server, in which case, only you control the lifetime.\nThere is also nothing in the WSGI that would prohibit you from spawning threads, o...
[ 13, 7 ]
[]
[]
[ "django", "flask", "multithreading", "python", "wsgi" ]
stackoverflow_0006579467_django_flask_multithreading_python_wsgi.txt
Q: How can I get the only element of a certain type out of a list more cleanly than what I am doing? I am working with some xml files. The schema for the files specifies that there can only be one of a certain type of element (in this case I am working with the footnotes element). There can be several footnote eleme...
How can I get the only element of a certain type out of a list more cleanly than what I am doing?
I am working with some xml files. The schema for the files specifies that there can only be one of a certain type of element (in this case I am working with the footnotes element). There can be several footnote elements in the footnotes element, I am trying to grab and process the footnotes element so that I can itera...
[ "Something like this should do the job:\nfrom lxml import etree\n\nxmltree = etree.fromstring(your_xml)\n\nfor footnote in xmltree.iterfind(\"//footnotes/footnote\"):\n # do something\n pass\n\nIt's easier to help if you provide some sample XML.\nEdit:\nIf you are working with really big files, you might want t...
[ 2 ]
[]
[]
[ "lxml", "python" ]
stackoverflow_0006604649_lxml_python.txt
Q: Python: How to know the number of row of a text file I want to know the number of row of a text file. How can I do this? A: if iterating over a file: for line_no, line in enumerate(f, start=1): or if counting the lines in a file (f): count = sum( 1 for line in f ) A: f = open('textfile.txt', 'rb') len(f.read...
Python: How to know the number of row of a text file
I want to know the number of row of a text file. How can I do this?
[ "if iterating over a file:\nfor line_no, line in enumerate(f, start=1):\n\nor if counting the lines in a file (f):\ncount = sum( 1 for line in f )\n\n", "f = open('textfile.txt', 'rb')\nlen(f.readlines())\n\nreadlines() method returns a list where each index holds a line of textfile.txt.\n", "f = open(\"file.te...
[ 4, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0006604736_python.txt
Q: Greek letters in a GUI - PYTHON I don't know how to write Greek letters in a GUI. I am working on a Physics program and I need to show units on the GUI. Do I have to download any extra libraries? Is there a module I have to use? What is the easiest way to write the letters in the GUI? I read a lot about UTF8 but...
Greek letters in a GUI - PYTHON
I don't know how to write Greek letters in a GUI. I am working on a Physics program and I need to show units on the GUI. Do I have to download any extra libraries? Is there a module I have to use? What is the easiest way to write the letters in the GUI? I read a lot about UTF8 but didn't figure out how to use it. I a...
[ "Unicode includes definitions for both the Greek alphabet and several mathematical symbols. If you are using any form of Unicode in your environment, it should be simple:\n>>> from Tkinter import *\n>>> root = Tk()\n>>> w = Label(root, text=u\"Hello, \\u03bc-world!\")\n>>> w.pack()\n>>> root.mainloop()\n\nThis will...
[ 6, 1, 0 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0006604802_python_tkinter.txt
Q: wxpython media.mediactrl.load question ok so im using LoadFromURI to load an mp3 file, the script works fine on one of my laptops running win64 but when i use it on the other laptop win32 it takes a while to load the song !, what does the command actually do ?i used LoadFromURI, Load, LoadURI and got the same resu...
wxpython media.mediactrl.load question
ok so im using LoadFromURI to load an mp3 file, the script works fine on one of my laptops running win64 but when i use it on the other laptop win32 it takes a while to load the song !, what does the command actually do ?i used LoadFromURI, Load, LoadURI and got the same results, when i use Load for example is the file...
[ "I'm pretty sure that streams the file, it doesn't actually download it. Someone wrapped the cross-platform media player, mplayer for wxPython. I think it's more robust than the included MediaCtrl. Here's one article on it: http://www.blog.pythonlibrary.org/2010/07/24/wxpython-creating-a-simple-media-player/ and he...
[ 1 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0006603987_python_wxpython_wxwidgets.txt
Q: SQLAlchemy ORM one-to-many relationship is not loading all records from DB Using the SqlAlchemy ORM, I've been trying to setup a one-to-many relationship between a parent table that has "child" records in a child table. The table and mapper declarations are below. The problem is, only one child record is read fr...
SQLAlchemy ORM one-to-many relationship is not loading all records from DB
Using the SqlAlchemy ORM, I've been trying to setup a one-to-many relationship between a parent table that has "child" records in a child table. The table and mapper declarations are below. The problem is, only one child record is read from the DB into the "children" attribute when there should be many records. child...
[ "The problem was in the child_table definition. I had only defined the fields with a foreign key relationship as being part of the primary key for the child_table. However, those fields (field_1 & field_2) weren't the complete primary key. So, it appears that SQLAlchemy was only loading one row. I added field_3...
[ 1 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0006604916_orm_python_sqlalchemy.txt
Q: Fabric parallel task not bound to a specific set I'm looking for a way to define a task with multirun, which will run on a set of servers defined in the commandline (via roles or hosts). All examples I've seen so far, try to do something like: env('app-nodes').multirun('some command') But I don't want to hardcode...
Fabric parallel task not bound to a specific set
I'm looking for a way to define a task with multirun, which will run on a set of servers defined in the commandline (via roles or hosts). All examples I've seen so far, try to do something like: env('app-nodes').multirun('some command') But I don't want to hardcode the role. I'd like to define it with fab -R ... inste...
[ "You'll prolly want to use task args and feed it into tav's env() that way:\nhttp://docs.fabfile.org/en/1.1.1/usage/fab.html#per-task-arguments\nAlso why would you expect an empty set for hosts to work?\n" ]
[ 0 ]
[]
[]
[ "fabric", "parallel_processing", "python" ]
stackoverflow_0006594906_fabric_parallel_processing_python.txt
Q: How to make Fabric execution follow the env.hosts list order? I have the following fabfile.py: from fabric.api import env, run host1 = '192.168.200.181' host2 = '192.168.200.182' host3 = '192.168.200.183' env.hosts = [host1, host2, host3] def df_h(): run("df -h | grep sda3") And I get the following output:...
How to make Fabric execution follow the env.hosts list order?
I have the following fabfile.py: from fabric.api import env, run host1 = '192.168.200.181' host2 = '192.168.200.182' host3 = '192.168.200.183' env.hosts = [host1, host2, host3] def df_h(): run("df -h | grep sda3") And I get the following output: [192.168.200.181] run: df -h | grep sda3 [192.168.200.181] out: /d...
[ "The exact reason that the order is not preserved from env.hosts is that there are three \"levels\" that the hosts to operate can be specified--env.hosts, the command line, and per function--which are merged together. In fabric/main.py on line 309, you can see that they use the set() type to remove duplicates in t...
[ 5, 1 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0001956717_fabric_python.txt
Q: Fabric script executing does not finish Here is my problem: I have got a Python build script that executes several commands to produce a .air package. This part of the job is done correctly but after that, I'd like to deploy this file to a server. I'm using a fabric script in ordrer to do that. Here are the lines:...
Fabric script executing does not finish
Here is my problem: I have got a Python build script that executes several commands to produce a .air package. This part of the job is done correctly but after that, I'd like to deploy this file to a server. I'm using a fabric script in ordrer to do that. Here are the lines: if os.system(os.environ["FAB"] + "\\fab.exe ...
[ "You can use the subprocess module to understand what happens\nimport subprocess\npipe = subprocess.Popen(command, stdout = subprocess.PIPE,\n stderr = subprocess.PIPE, shell = True)\nstdout, stderr = pipe.communicate()\npipexit = pipe.returncode\n\nThen you may need a timeout, and for this yo...
[ 2, 1, 0 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0006573701_fabric_python.txt
Q: Python's Fabric to use rsync locally, is it possible? Currently Fabric's 'rsync_projecct' requires a user and a host parameter to be specified. I'having a lot of issues copying user@127.0.0.1 because it is still asking me for the password for rsync. I've spent hours on this and am wondering if there is just a ...
Python's Fabric to use rsync locally, is it possible?
Currently Fabric's 'rsync_projecct' requires a user and a host parameter to be specified. I'having a lot of issues copying user@127.0.0.1 because it is still asking me for the password for rsync. I've spent hours on this and am wondering if there is just a way to use the rsync [src] [dest] without having to specify...
[ "you can just local() out and use rsync any way you want to.\n" ]
[ 4 ]
[]
[]
[ "fabric", "python" ]
stackoverflow_0006536862_fabric_python.txt
Q: Creating an autostart application on Ubuntu Linux I'm trying to setup a Python application that should automatically start when Linux boots. It should also start (unless not already running) if the computer resumes from standby mode - which is mainly the problem. Does anybody know where to integrate these require...
Creating an autostart application on Ubuntu Linux
I'm trying to setup a Python application that should automatically start when Linux boots. It should also start (unless not already running) if the computer resumes from standby mode - which is mainly the problem. Does anybody know where to integrate these requirements? Thanks, Marius
[ "If you want to guarantee it's always running, have a look at man inittab.\n", "The easiest way I've found to autostart apps is to use Upstart. It's way better than the cron solution above.\nhttp://upstart.ubuntu.com/getting-started.html\nhttps://help.ubuntu.com/community/UbuntuBootupHowto\n", "Configure a cro...
[ 1, 1, 0 ]
[]
[]
[ "autostart", "python", "ubuntu_10.04", "wakeup" ]
stackoverflow_0003839383_autostart_python_ubuntu_10.04_wakeup.txt
Q: How to find if large list of keywords is in Django TextField Say I have the following models: class NamedEntity(models.Model): name = models.CharField(max_length=100) NE_CHOICES = ( ('PER', 'Person'), ('TTL', 'Title / Role'), ('ORG', 'Organization'), ('LOC', 'Location') ...
How to find if large list of keywords is in Django TextField
Say I have the following models: class NamedEntity(models.Model): name = models.CharField(max_length=100) NE_CHOICES = ( ('PER', 'Person'), ('TTL', 'Title / Role'), ('ORG', 'Organization'), ('LOC', 'Location') ) ne_type = models.CharField(max_length=30, choices=NE_CHOICES...
[ "Based on my understanding, my thoughts are as followed:\n\n\nGet data from the content field\nSplit the data into the different words which should give you and array\n of words.\nEither group similar words - a dictionary can be used: {'mary': 5,\n 'mark': count}\nOr remove duplicate words using python's list dat...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0006565482_django_python.txt