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:
What is offered by coroutines in python that improve a naive consumer/producer setup?
I've read a little about coroutines, in particular with python, and something is not entirely obvious to me.
I have implemented a producer/consumer model, a basic version of which is as follows:
#!/usr/bin/env python
class MyCon... | What is offered by coroutines in python that improve a naive consumer/producer setup? | I've read a little about coroutines, in particular with python, and something is not entirely obvious to me.
I have implemented a producer/consumer model, a basic version of which is as follows:
#!/usr/bin/env python
class MyConsumer(object):
def __init__(self, name):
self.__name = name
def __call__(... | [
"When using the coroutines approach, both the consumer and the producer code can be simpler sometimes. In your approach, at least one of them must be written as a finite-state-machine (assuming some state is involved).\nWith the coroutines approach they are essentially independent processes. \nAn example would help... | [
4
] | [] | [] | [
"coroutine",
"observer_pattern",
"producer_consumer",
"python"
] | stackoverflow_0005677768_coroutine_observer_pattern_producer_consumer_python.txt |
Q:
Duplicating python27.dll as python25.dll
I have some Windows proprietary apps that insist on using Python 2.5. I'm already using python 2.7 rarely and on my way to 3.x, so I do not want to keep or force the team to keep yet another python version.
So, I cheated and created a python25.dll as a copy of the python27... | Duplicating python27.dll as python25.dll | I have some Windows proprietary apps that insist on using Python 2.5. I'm already using python 2.7 rarely and on my way to 3.x, so I do not want to keep or force the team to keep yet another python version.
So, I cheated and created a python25.dll as a copy of the python27.dll in the same bin folder of that app/ Some... | [
"Any differences relevant in this context would be the symbols exported by the two DLLs. I am not familiar with the windows toolsuite, but try using a windows equivalent of unix's nm or objdump to see whether there are any symbols exported in the 2.5 version but not 2.7. I wouldn't expect (m)any. \nAnother approach... | [
0,
0
] | [] | [] | [
"dll",
"python",
"windows"
] | stackoverflow_0005677106_dll_python_windows.txt |
Q:
How can I test my python module without installing it
I'm in the process of redesigning/refactoring my Python quantum chemistry package (pyquante). One of the things I don't like about the existing release is that I have to install the package to run the test suite. That is, the test suite has statements like from... | How can I test my python module without installing it | I'm in the process of redesigning/refactoring my Python quantum chemistry package (pyquante). One of the things I don't like about the existing release is that I have to install the package to run the test suite. That is, the test suite has statements like from PyQuante import SCF, and, of course, this PyQuante could r... | [
"Create a proper package for your stuff and use\npython setup.py develop\n\nto make it a proper dev-package.\nSee:\n\nhttps://stackoverflow.com/a/19048754/548039 \nhttp://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode\n\n",
"I would honestly insist on using virtualenv, its designed for this ... | [
29,
8,
1
] | [] | [] | [
"python",
"testing"
] | stackoverflow_0005677809_python_testing.txt |
Q:
trying to create a dictionary but do not know how to deal with \n
subject_dic = {}
inputFile = open(filename)
for line in inputFile:
split_line = string.split(line, ',')
subject_dic[split_line[0]] = tuple(split_line[1:3])
print subject_dic
I'm getting
{'6.08': ('1', '10\n'), '6.09': ('3', '7\n'), '6.19':... | trying to create a dictionary but do not know how to deal with \n | subject_dic = {}
inputFile = open(filename)
for line in inputFile:
split_line = string.split(line, ',')
subject_dic[split_line[0]] = tuple(split_line[1:3])
print subject_dic
I'm getting
{'6.08': ('1', '10\n'), '6.09': ('3', '7\n'), '6.19': ('8', '19'), '6.10': ('8', '18\n'), '6.00': ('10', '1\n'), '6.01': ('5... | [
"split_line = split_line.strip()\n\nSee here.\n",
"If you're not working with a ridiculously large file, you can actually avoid having to use .strip() at all. If you read in the entire file as a string using .read() and then perform .splitlines() on that string.\nHere is an example. I commented out your code whe... | [
6,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005678136_python.txt |
Q:
Pyramid and FormAlchemy admin interface
I have a pyramid project using the formalchemy admin interface. I added the basic ACL authentication and the pyramid_formalchemy plugin always denys even though I am authenticated.
Any thoughts on how only allow authenticated users to use the pyramid_formalchemy admin interf... | Pyramid and FormAlchemy admin interface | I have a pyramid project using the formalchemy admin interface. I added the basic ACL authentication and the pyramid_formalchemy plugin always denys even though I am authenticated.
Any thoughts on how only allow authenticated users to use the pyramid_formalchemy admin interface?
The authorization policy was add like th... | [
"pyramid_formalchemy uses the permissions 'view', 'edit', 'delete', 'new' to determine who can do what. The __acl__ is propagated down from your SQLAlchemy model object. Thus, you need to put an __acl__ on each of your model objects allowing your desired groups access to those permissions. For example, from the pyr... | [
11
] | [] | [] | [
"acl",
"authorization",
"formalchemy",
"pyramid",
"python"
] | stackoverflow_0005671300_acl_authorization_formalchemy_pyramid_python.txt |
Q:
Python Web Services
Possible Duplicate:
Python Web Services
What's the best SOAP client library for Python, and where is the documentation for it?
What tool would you recommend to use with Python to consume Web Services?
I have thought about using SOAP.py, but some of the libraries it relies on (PyXML) are out ... | Python Web Services |
Possible Duplicate:
Python Web Services
What's the best SOAP client library for Python, and where is the documentation for it?
What tool would you recommend to use with Python to consume Web Services?
I have thought about using SOAP.py, but some of the libraries it relies on (PyXML) are out of date. Plus, it seems ... | [
"I'd recommend suds. It is very simple and easy to use.\n\nSimple example:\nfrom suds.client import Client\n\nurl = 'http://localhost:7080/webservices/WebServiceTestBean?wsdl'\nclient = Client(url)\nresult = client.service.MyMethod(args)\n\nFor more examples / tutorial see their documentation page..\n"
] | [
1
] | [] | [] | [
"python",
"service",
"soap"
] | stackoverflow_0005678798_python_service_soap.txt |
Q:
Python how to search accross the lists
I have two lists:
a= [['tea','apple',1,1],['coffee','apple',0,1],['cola','mango',1,1],['lemon','banana',0,0]]
b=[[ 'apple','0','1','1','3'],[ 'ring','0','1','1','3'],[ 'tennis','1','0','0','3'],[ 'mango','0','1','0','3']]
I am trying to figure out the best possible way to :
... | Python how to search accross the lists | I have two lists:
a= [['tea','apple',1,1],['coffee','apple',0,1],['cola','mango',1,1],['lemon','banana',0,0]]
b=[[ 'apple','0','1','1','3'],[ 'ring','0','1','1','3'],[ 'tennis','1','0','0','3'],[ 'mango','0','1','0','3']]
I am trying to figure out the best possible way to :
List item
Locate/search the the common elem... | [
"for 1, the best is to use set():\na= [['tea','apple',1,1],\n ['coffee','apple',0,1],\n ['cola','mango',1,1],\n ['lemon','banana',0,0]]\nb=[[ 'apple','0','1','1','3'],\n [ 'ring','0','1','1','3'],\n [ 'tennis','1','0','0','3'],\n [ 'mango','0','1','0','3']]\n\na_columns = zip(*a)\n# union\na_set = se... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005678927_python.txt |
Q:
Python Sort Algorithm
I am implemented different sorting algorithms in Python to better understand them, and I was wondering what type of sort does Python's built-in sort method implement?
A:
It's an algorithm called Timsort developed by Tim Peters specifically for Python.
| Python Sort Algorithm | I am implemented different sorting algorithms in Python to better understand them, and I was wondering what type of sort does Python's built-in sort method implement?
| [
"It's an algorithm called Timsort developed by Tim Peters specifically for Python.\n"
] | [
18
] | [] | [] | [
"python",
"python_3.x",
"sorting"
] | stackoverflow_0005679161_python_python_3.x_sorting.txt |
Q:
how to parse big datasets using RDFLib?
I'm trying to parse several big graphs with RDFLib 3.0, apparently it handles first one and dies on the second (MemoryError)... looks like MySQL is not supported as store anymore, can you please suggest a way to somehow parse those?
Traceback (most recent call last):
File ... | how to parse big datasets using RDFLib? | I'm trying to parse several big graphs with RDFLib 3.0, apparently it handles first one and dies on the second (MemoryError)... looks like MySQL is not supported as store anymore, can you please suggest a way to somehow parse those?
Traceback (most recent call last):
File "names.py", line 152, in <module>
main()
... | [
"How many triples on those RDF files ? I have tested rdflib and it won't scale much further than few tens of ktriples - if you are lucky. No way it really performs well for files with millions of triples.\nThe best parser out there is rapper from Redland Libraries. My first advice is to not use RDF/XML and go for n... | [
10
] | [] | [] | [
"graph",
"parsing",
"python",
"rdf",
"rdflib"
] | stackoverflow_0005678623_graph_parsing_python_rdf_rdflib.txt |
Q:
How to debug a deadlock under mac osx?
I'm developing a port of audio player to Mac environment. It works fine under windows, but not with Mac. I got an unpredictable deadlock when I'm playing the music with the player, the only information I can get is to dump the stack of threads of the hanging process. Here ... | How to debug a deadlock under mac osx? | I'm developing a port of audio player to Mac environment. It works fine under windows, but not with Mac. I got an unpredictable deadlock when I'm playing the music with the player, the only information I can get is to dump the stack of threads of the hanging process. Here is the call stack I get:
Sampling process 18... | [
"Debugging multi-threaded apps is inherently difficult. A simple (and possibly simplistic) approach is to write all of your lock about-to-grab/blocked/released events to a log file. Nothing particularly OS X about that, but I've used it to good effect on similar problems.\n"
] | [
0
] | [] | [] | [
"deadlock",
"debugging",
"macos",
"python"
] | stackoverflow_0003334656_deadlock_debugging_macos_python.txt |
Q:
Django Models / SQLAlchemy are bloated! Any truly Pythonic DB models out there?
"Make things as simple as possible, but no simpler."
Can we find the solution/s that fix the Python database world?
Update: A 'lustdb' prototype has been written by Alex Martelli - if you know any somewhat lightweight, high-level datab... | Django Models / SQLAlchemy are bloated! Any truly Pythonic DB models out there? | "Make things as simple as possible, but no simpler."
Can we find the solution/s that fix the Python database world?
Update: A 'lustdb' prototype has been written by Alex Martelli - if you know any somewhat lightweight, high-level database libraries with multiple backends we could wrap in syntax sugar honey, please weig... | [
"What you request cannot be done in Python 2.whatever, for a very specific reason. You want to write:\nclass Task(model): \n title = ''\n isDone = False\n\nIn Python 2.anything, whatever model may possibly be, this cannot ever allow you to predict any \"ordering\" for the two fields, because the semantics of... | [
9,
3,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"database",
"nosql",
"python"
] | stackoverflow_0002978138_database_nosql_python.txt |
Q:
Link failures building TagPy on Windows
I'm a hapless Linux coder trying to get one of my projects working in Windows 7, which involves building TagPy. I'm using MSVC2008 and Python 2.7.1 (x86 version).
I have successfully installed CMake and built TagLib, and installed the Boost headers and Boost.Python binary fr... | Link failures building TagPy on Windows | I'm a hapless Linux coder trying to get one of my projects working in Windows 7, which involves building TagPy. I'm using MSVC2008 and Python 2.7.1 (x86 version).
I have successfully installed CMake and built TagLib, and installed the Boost headers and Boost.Python binary from the BoostPro installer. I have set the boo... | [
"See this answer, I think it's the same problem. The /Zc:wchar_t- flag will go away with the next TagLib release, but for now it's enabled in the default CMakeLists.txt file.\n"
] | [
0
] | [] | [] | [
"boost_python",
"python",
"taglib",
"windows"
] | stackoverflow_0005671116_boost_python_python_taglib_windows.txt |
Q:
PyQt4 multithreading using QThread
There is an endless block when xml.etree.ElementTree.fromstring() function is called in the QThread. Also lots of other calls makes the QThread blocked like multiprocessing.Process().
Important to say that it is a pure block, no exception or break.
Here is the code (a little edit... | PyQt4 multithreading using QThread | There is an endless block when xml.etree.ElementTree.fromstring() function is called in the QThread. Also lots of other calls makes the QThread blocked like multiprocessing.Process().
Important to say that it is a pure block, no exception or break.
Here is the code (a little edited but same principle as the source):
fr... | [
"The code as posted doesn't actually run, but with a couple minor changes it runs and works fine. Here is the code with modifications:\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\nimport sys\nimport xml.etree.ElementTree\n\nclass Bruton(QThread):\n def __init__(self, mw):\n super(Bruton, self).... | [
2,
0
] | [] | [] | [
"multithreading",
"pyqt",
"pyqt4",
"python",
"qthread"
] | stackoverflow_0005668027_multithreading_pyqt_pyqt4_python_qthread.txt |
Q:
django entry_set definition
I don't understand the following code on page 87 of Practical Django Projects:
from django.views.generic.list_detail import object_list
def category_detail(request, slug):
category = get_object_or_404(Category, slug=slug)
return object_list(request, queryset=category.entry_set.a... | django entry_set definition | I don't understand the following code on page 87 of Practical Django Projects:
from django.views.generic.list_detail import object_list
def category_detail(request, slug):
category = get_object_or_404(Category, slug=slug)
return object_list(request, queryset=category.entry_set.all(),
extr... | [
"It was created by the Entry model.\n\nIf a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased.\n\n",
"I don't have my copy in front of me,... | [
4,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005679408_django_python.txt |
Q:
Large PyPlot - avoid memory allocation
I'm doing a rather large PyPlot (Python matplotlib) (600000 values, each 32bit). Practically I guess I could simply do something like this:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
Two arrays, both allocated in memory. How... | Large PyPlot - avoid memory allocation | I'm doing a rather large PyPlot (Python matplotlib) (600000 values, each 32bit). Practically I guess I could simply do something like this:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
Two arrays, both allocated in memory. However I'll have to plot files, which contain ... | [
"If you're talking about gigabytes of data, you might consider loading and plotting the data points in batches, then layering the image data of each rendered plot over the previous one. Here is a quick example, with comments inline:\nimport Image\nimport matplotlib.pyplot as plt\nimport numpy\n\nN = 20\nsize = 4\nx... | [
5,
0
] | [] | [] | [
"file_io",
"memory_management",
"plot",
"python"
] | stackoverflow_0005673934_file_io_memory_management_plot_python.txt |
Q:
Matplotlib artists to stay the same size when zoomed in?
I'm using matplotlib to draw some artists (a couple rectangles, specifically) on a graph. I'd like to anchor these somehow so that they remain the same size no matter what zoom level is used. I've used google to search and I've read through most of the artis... | Matplotlib artists to stay the same size when zoomed in? | I'm using matplotlib to draw some artists (a couple rectangles, specifically) on a graph. I'd like to anchor these somehow so that they remain the same size no matter what zoom level is used. I've used google to search and I've read through most of the artist documentation and have had no luck finding what function I n... | [
"Simply apply the transform=ax.transAxes keyword to the Polygon or Rectangle instance. You could also use transFigure if it makes more sense to anchor the patch to the figure instead of the axis. Here is the tutorial on transforms.\nAnd here is some sample code:\nfrom matplotlib import pyplot as plt\nfrom matplot... | [
4
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0005678950_matplotlib_python.txt |
Q:
Binary List to PNG in Python
Forgive me for any naivety, but I am new to working with images. Say I have a list of binary values [1,0,0,0,1,0,1,0,0,0,0,1,1,0....] which represent pixels in a black and white image. How would I go about making a .png file from this list?
A:
Use Python Imaging Library for this pu... | Binary List to PNG in Python | Forgive me for any naivety, but I am new to working with images. Say I have a list of binary values [1,0,0,0,1,0,1,0,0,0,0,1,1,0....] which represent pixels in a black and white image. How would I go about making a .png file from this list?
| [
"Use Python Imaging Library for this purpose. \nThere is a img = Image.frombuffer(mode, size, data) method which creates an image from \"raw\" data (a string). You can then save it as PNG file via img.save('image.png', transparency=transparency)\n",
"Expanding on BasicWolf's example:\nfrom PIL import Image\nimpor... | [
4,
3
] | [] | [] | [
"image_manipulation",
"python"
] | stackoverflow_0005672756_image_manipulation_python.txt |
Q:
Installing a pip package from a local SVN checkout
I have a clone of another python project (that has a setup.py etc.) in my svn repository. I want to install tell pip to install from this directory. However it's an internal svn repo and is accessible via the svn:// scheme, not http://.
I can checkout the directo... | Installing a pip package from a local SVN checkout | I have a clone of another python project (that has a setup.py etc.) in my svn repository. I want to install tell pip to install from this directory. However it's an internal svn repo and is accessible via the svn:// scheme, not http://.
I can checkout the directory fine like so svn co svn://172.31.1.3/Development/Comm... | [
"It is an open bug right now. Paul Nasrat is taking a look at it and opened and issue.\nFollow the https://github.com/pypa/pip/issues/252\n"
] | [
3
] | [] | [] | [
"package",
"pip",
"python",
"svn"
] | stackoverflow_0005648017_package_pip_python_svn.txt |
Q:
Developing Python Module
I'd like to start developing an existing Python module. It has a source folder and the setup.py script to build and install it. The build script just copies the source files since they're all python scripts.
Currently, I have put the source folder under version control and whenever I make ... | Developing Python Module | I'd like to start developing an existing Python module. It has a source folder and the setup.py script to build and install it. The build script just copies the source files since they're all python scripts.
Currently, I have put the source folder under version control and whenever I make a change I re-build and re-ins... | [
"Use a virtualenv and use python setup.py develop to link your module to the virtual Python environment. This will make your project's Python packages/modules show up on the sys.path without having to run install.\nExample:\n% virtualenv ~/virtenv\n% . ~/virtenv/bin/activate\n(virtenv)% cd ~/myproject\n(virtenv)% p... | [
24,
7,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005679359_python.txt |
Q:
Python scripting in linux
We have around 250 identical linux server which runs a business critical web application for a bank. Basically we do a lot of scripting work but now i want to centralize that only in one location. That means run on one server and and deploy it in many. I know you guys must be thinking tha... | Python scripting in linux | We have around 250 identical linux server which runs a business critical web application for a bank. Basically we do a lot of scripting work but now i want to centralize that only in one location. That means run on one server and and deploy it in many. I know you guys must be thinking that this is an easy task and can ... | [
"This is a very general question, so I'll respond with two different frameworks that are made using Python to facilitate bulk system administration tasks.\n\nfunc - Func is part of the\nFedora project and so is specialized\nto their architecture. If your hosts\nare all RedHat/CentOS based, this is\nthe solution for... | [
6,
0
] | [] | [] | [
"django",
"fabric",
"linux",
"python"
] | stackoverflow_0005679203_django_fabric_linux_python.txt |
Q:
Unable to run Punjab
I downloaded Punjab from Github. I also have Python 2.7, Twisted Python 10.2, OpenSSL required to run Punjab. I was able to install Punjab successfully but while running it reports "twistd is not recognised as an internal or external command"
I have no knowledge of python; could someone please... | Unable to run Punjab | I downloaded Punjab from Github. I also have Python 2.7, Twisted Python 10.2, OpenSSL required to run Punjab. I was able to install Punjab successfully but while running it reports "twistd is not recognised as an internal or external command"
I have no knowledge of python; could someone please tell me what to do?
| [
"Have you installed twisted? http://twistedmatrix.com/trac/\nIf you have then it seems like it is not in your execution path. \n",
"\"twistd is not recognised as an internal or external command\", if you are using windows os \nthis is mean that the twistd is not in the PATH of searching ( environement variabls).... | [
1,
1
] | [] | [] | [
"python",
"strophe",
"xmpp"
] | stackoverflow_0005151377_python_strophe_xmpp.txt |
Q:
How to make an arbirtary number of windows using Python and Tkinter?
I'm writing an app that doesn't have a main window (it runs inside a Python interpreter in another app), and I thought I had a good solution for getting Tkinter to cooperate--I made the Tkinter.Tk class into a Borg.
class RootWindow(Tk):
"""... | How to make an arbirtary number of windows using Python and Tkinter? | I'm writing an app that doesn't have a main window (it runs inside a Python interpreter in another app), and I thought I had a good solution for getting Tkinter to cooperate--I made the Tkinter.Tk class into a Borg.
class RootWindow(Tk):
""" Invisible window that serves as the default parent
of all others... | [
"One problem appears to be that you are forgetting to start the event loop. Or, based on further edits of your question, you may be starting more than one main loop. You need exactly one main loop that is run from the root window.\nTkinter certainly allows an arbitrary number of top level windows, but your questio... | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface",
"window"
] | stackoverflow_0005672228_python_tkinter_user_interface_window.txt |
Q:
Implementing Bi-Directional relationships in MongoEngine
I'm building a Django application that uses MongoDB and MongoEngine to store data. To present a simplified version of my problem, say I want to have two classes: User and Page. Each page should associate itself with a user and each user a page.
from mongoeng... | Implementing Bi-Directional relationships in MongoEngine | I'm building a Django application that uses MongoDB and MongoEngine to store data. To present a simplified version of my problem, say I want to have two classes: User and Page. Each page should associate itself with a user and each user a page.
from mongoengine import *
class Page(Document):
pass
class User(Docum... | [
"This is the proper solution:\nfrom mongoengine import *\n\nclass User(Document):\n name = StringField()\n page = ReferenceField('Page')\n\nclass Page(Document):\n content = StringField()\n user = ReferenceField(User)\n\nUse single quotes ('Page') to denote classes that have not yet been defined.\n",
... | [
43,
12
] | [] | [] | [
"bidirectional_relation",
"circular_reference",
"mongodb",
"mongoengine",
"python"
] | stackoverflow_0003885487_bidirectional_relation_circular_reference_mongodb_mongoengine_python.txt |
Q:
Print exceptions in a file
How to print only the exceptions using python that is present in a file /tmp/exceptions.log ignoring all the debug statements.The snapshot of the exception is given below..
Traceback (most recent call last):
File "/usr/site/bank/views.py", line 1695, in importmydata
... | Print exceptions in a file | How to print only the exceptions using python that is present in a file /tmp/exceptions.log ignoring all the debug statements.The snapshot of the exception is given below..
Traceback (most recent call last):
File "/usr/site/bank/views.py", line 1695, in importmydata
o.save()
File "/usr/site... | [
"The simplest way is to use grep with exclusion flag , e.g. \ngrep -v DEBUG /tmp/exceptions.log\n\nThis will print the lines that don't contain the \"DEBUG\" string.\n",
">>> import re\n>>> pat = re.compile(r'(\\w+:\\s.*\\n)')\n>>> pat.findall(c) # c is your logs content\n['IntegrityError: (1048, \"Column \\'opti... | [
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005673294_python.txt |
Q:
Python: List Directories and Sizes
I'm trying to write some Python code that will traverse each directory in the current working directory and report the total size (in bytes) under each directory, regardless of how deep each directory itself goes.
This is just for a learning project, I realize there are already o... | Python: List Directories and Sizes | I'm trying to write some Python code that will traverse each directory in the current working directory and report the total size (in bytes) under each directory, regardless of how deep each directory itself goes.
This is just for a learning project, I realize there are already other ways to get this information throug... | [
"This will list the sizes of the directories in a given directory, plus the total:\nimport locale\nimport os\n\nlocale.setlocale(locale.LC_ALL, \"\")\n\ndef get_size(state, root, names):\n paths = [os.path.realpath(os.path.join(root, n)) for n in names]\n # handles dangling symlinks\n state[0] += sum(os.st... | [
4,
2
] | [] | [] | [
"directory",
"python",
"size"
] | stackoverflow_0005680165_directory_python_size.txt |
Q:
Python FTP uploading bar
I am uploading a file with FTPLib in python and have a cli loadingbar with progressbar 2.2.
I need to make a loading bar to tell the progress of the upload.
Does anyone have any info on the topic?
Thanks, giodamelio
As Senthil Kumaran pointed out, there is a callback parameter in the ftp... | Python FTP uploading bar | I am uploading a file with FTPLib in python and have a cli loadingbar with progressbar 2.2.
I need to make a loading bar to tell the progress of the upload.
Does anyone have any info on the topic?
Thanks, giodamelio
As Senthil Kumaran pointed out, there is a callback parameter in the ftplib.storbinary function but I ... | [
"Small change to your code:\nimport ftplib\n\ndef callback(p):\n print(\"This is the callback function\")\n\ns = ftplib.FTP('myserver.com','login','password') # Connect\n\nf = open('test.txt','rb') # file to send\ns.storbinary('STOR test.txt', f, 1024, callback) # Send the file\n\nf.close(... | [
4,
2
] | [] | [] | [
"file_upload",
"ftp",
"python"
] | stackoverflow_0005673170_file_upload_ftp_python.txt |
Q:
Python: create a compressed tar file for streamed writing
I need to produce the tar.gzipped text file. Is there a way to create a file for constant writing (to be able to do something like compressedFile.write("some text")), or do I need to create a raw text file first, and compress it aftewards?
This will be quit... | Python: create a compressed tar file for streamed writing | I need to produce the tar.gzipped text file. Is there a way to create a file for constant writing (to be able to do something like compressedFile.write("some text")), or do I need to create a raw text file first, and compress it aftewards?
This will be quite unfortunate, as the file should be really long and well compr... | [
"Here's an example of how to write a compressed tarfile from a Python script:\nimport StringIO\nimport tarfile\n\ntar = tarfile.open('example.tar.gz', 'w:gz')\n\n# create a file record\ndata = StringIO.StringIO('this is some text')\ninfo = tar.tarinfo()\ninfo.name = 'foo.txt'\ninfo.uname = 'pat'\ninfo.gname = 'user... | [
6
] | [] | [] | [
"file_io",
"gzip",
"python",
"tar"
] | stackoverflow_0005680264_file_io_gzip_python_tar.txt |
Q:
: for displaying all elements in a multidimensional array in python 3.1
I have a multidimensional array in python like:
arr = [['foo', 1], ['bar',2]]
Now, if I want to print out everything in the array, I could do:
print(arr[:][:])
Or I could also just do print(arr). However, If I only wanted to print out the f... | : for displaying all elements in a multidimensional array in python 3.1 | I have a multidimensional array in python like:
arr = [['foo', 1], ['bar',2]]
Now, if I want to print out everything in the array, I could do:
print(arr[:][:])
Or I could also just do print(arr). However, If I only wanted to print out the first element of each box (for arr, that would be 'foo', 'bar'), I would imagi... | [
"You can transpose the array, e.g.\n>>> list(zip(*arr))[0]\n('foo', 'bar')\n\n",
"zip() will be a little slower than your original solution. If you don't like your original solution because it requires multiple lines of code you can always do this:\n[i[0] for i in arr]\n\nzip() has a for loop inside so you cannot... | [
2,
2,
0
] | [] | [] | [
"arrays",
"python",
"python_3.x"
] | stackoverflow_0002961150_arrays_python_python_3.x.txt |
Q:
Efficient method for a grid of clickable images in wxPython?
Which is the most efficient method to display a grid of about 1000 clickable images in wxPython ?
Currently i am using a GridSizer filled with StaticBitmap objects. But its quite slow for 500+ images.
One more thing is that, i have a listbox of categori... | Efficient method for a grid of clickable images in wxPython? | Which is the most efficient method to display a grid of about 1000 clickable images in wxPython ?
Currently i am using a GridSizer filled with StaticBitmap objects. But its quite slow for 500+ images.
One more thing is that, i have a listbox of categories on the left. That is to filter the images. Categories will be l... | [
"I'm assuming that not all 1000 images are onscreen at the same time, correct? If so, you should be able to just load up the number you need and when the user scrolls, load up the next set as needed. I think the people on the wxPython list usually used DCs to blit their images onscreen or they use the FloatCanvas w... | [
1,
0
] | [] | [] | [
"image",
"performance",
"python",
"wxpython"
] | stackoverflow_0005680487_image_performance_python_wxpython.txt |
Q:
Using a if statement condition to see NULL user input and print: "sometext ..."
Python with its indents and no semi-colons and brackets is taking some time for me to get used to ... coming from C++. This, I'm sure is an easy fix, but I can't seem to find the problem. Your help is greatly appreciated. Here is what... | Using a if statement condition to see NULL user input and print: "sometext ..." | Python with its indents and no semi-colons and brackets is taking some time for me to get used to ... coming from C++. This, I'm sure is an easy fix, but I can't seem to find the problem. Your help is greatly appreciated. Here is what I have. When I run this code it acts like the second 'if' statement does not exist. ... | [
"The return value of raw_input() is always a string, and never None. If you want to check for an empty string \"\", you can use\nif not string_name:\n # whatever\n\n",
"raw_input always returns a string and never None. Check out raw_input help.\n\nraw_input([prompt]) -> string\nRead a string from standard inp... | [
9,
1
] | [] | [] | [
"if_statement",
"python",
"while_loop"
] | stackoverflow_0005681048_if_statement_python_while_loop.txt |
Q:
Having trouble updating the statusBar in PyQt4
I am new to PyQt4 and am trying to allow my program to set a different message on the statusbar ad different times throughout the program, but I can't ever seem to get any text to appear on it.
The GUI was designed in Qt Designer, in the file generated by pyuic, It gi... | Having trouble updating the statusBar in PyQt4 | I am new to PyQt4 and am trying to allow my program to set a different message on the statusbar ad different times throughout the program, but I can't ever seem to get any text to appear on it.
The GUI was designed in Qt Designer, in the file generated by pyuic, It gives me:
self.statusbar = QtGui.QStatusBar(MainWindow... | [
"You are not calling statusBar.\nWith self.statusBar.showMessage('Ready'), you are calling the showMessage attribute of the statusBar method.\nYou should use self.statusBar().showMessage('Ready'), where you get the status bar calling the statusBar method.\n"
] | [
4
] | [] | [] | [
"pyqt",
"python",
"qt",
"qt4",
"statusbar"
] | stackoverflow_0005680060_pyqt_python_qt_qt4_statusbar.txt |
Q:
OR statement handling two != clauses Python
(Using Python 2.7) I understand this is pretty elementary but why wouldn't the following statement work as written:
input = int(raw_input())
while input != 10 or input != 20:
print 'Incorrect value, try again'
bet = int(raw_input())
Basically I only want to acce... | OR statement handling two != clauses Python | (Using Python 2.7) I understand this is pretty elementary but why wouldn't the following statement work as written:
input = int(raw_input())
while input != 10 or input != 20:
print 'Incorrect value, try again'
bet = int(raw_input())
Basically I only want to accept 10 or 20 as an answer. Now, regardless of 'inp... | [
"You need and:\nwhile input != 10 and input != 20:\n\nThink it through: If the input is 10, then the first expression is false, causing Python to evaluate the second expression input != 20. 10 is different form 20, so this expressions evaluates to true. As false or true == true, the whole expression is true.\nSame ... | [
17,
10,
0,
0,
0
] | [] | [] | [
"clause",
"operator_keyword",
"python"
] | stackoverflow_0005681271_clause_operator_keyword_python.txt |
Q:
Is there a way to get a view into a python array.array()?
I'm generating many largish 'random' files (~500MB) in which the contents are the output of repeated calls to random.randint(...). I'd like to preallocate a large buffer, write longs to that buffer, and periodically flush that buffer to disk. I am currently... | Is there a way to get a view into a python array.array()? | I'm generating many largish 'random' files (~500MB) in which the contents are the output of repeated calls to random.randint(...). I'd like to preallocate a large buffer, write longs to that buffer, and periodically flush that buffer to disk. I am currently using array.array() but I can't see a way to create a view int... | [
"I guess you could use numpy: http://www.numpy.org - the fundamental array type in numpy at least supports no-copy views.\n",
"Numpy is incredibly flexible and powerful when it comes to views into arrays whilst minimising copies. For example:\nimport numpy\na = numpy.random.randint(0, 10, size=10)\nb = numpy.a[3:... | [
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0005681032_python.txt |
Q:
How to know a position (.txt)
i wonder how to know , a position inside the .txt when I read.
this is my txt
cat dog monkey bird
this my printing
Word: cat Position: line 1 , word 1 (1,1)
any idea?
A:
foo.txt:
asd
asd
asd
ad
I put returns between .......
asd
sad
asd
code:
>>> def position(file,word):
... ... | How to know a position (.txt) | i wonder how to know , a position inside the .txt when I read.
this is my txt
cat dog monkey bird
this my printing
Word: cat Position: line 1 , word 1 (1,1)
any idea?
| [
"foo.txt:\nasd\nasd\nasd\nad\nI put returns between .......\nasd\nsad\nasd\n\ncode:\n>>> def position(file,word):\n... for i,line in enumerate(file): #for every line; i=linenumber and line=text\n... s=line.find(word) #find word\n... if s!=-1: #if word found\n... return i,s # return l... | [
5,
4,
1
] | [] | [] | [
"python"
] | stackoverflow_0005681407_python.txt |
Q:
How to verify gnupg signature with Python gnupg module?
I have problem with verification signature with Python gnupg module.
With this module I can encrypt and sign file:
gpg.encrypt_file(stream, encrypt_for, sign=sign_by, passphrase=key_passwd, output=file_out)
Such encrypted file can be decrypted by command lin... | How to verify gnupg signature with Python gnupg module? | I have problem with verification signature with Python gnupg module.
With this module I can encrypt and sign file:
gpg.encrypt_file(stream, encrypt_for, sign=sign_by, passphrase=key_passwd, output=file_out)
Such encrypted file can be decrypted by command line gpg, output:
gpg: encrypted with 2048-bit ELG-E key, ID 518... | [
"See this gist for an example script showing you how to verify signatures when decrypting.\nCode (as of 2011-04-05) follows:\nfrom cStringIO import StringIO\nimport gnupg\nimport logging\nimport os\nimport shutil\n\ndef generate_key(gpg, first_name, last_name, domain, passphrase=None):\n \"Generate a key\"\n ... | [
4
] | [] | [] | [
"cryptography",
"gnupg",
"python",
"signature"
] | stackoverflow_0005673255_cryptography_gnupg_python_signature.txt |
Q:
Multiple chat rooms - Is using ports the only way ? What if there are hundreds of rooms?
Need some direction on this.
I'm writing a chat room browser-application, however there is a subtle difference.
These are collaboration chats where one person types and the other person can see live ever keystroke entered by t... | Multiple chat rooms - Is using ports the only way ? What if there are hundreds of rooms? | Need some direction on this.
I'm writing a chat room browser-application, however there is a subtle difference.
These are collaboration chats where one person types and the other person can see live ever keystroke entered by the other person as they type.
Also the the chat space is not a single line but a textarea sp... | [
"You could try doing something like IRC, where the current \"room\" is sent from the client to the server \"before\" the text (/PRIVMSG #room-name Hello World), delimited by a space. For example, you could send ROOMNAME Sample text from the browser to the server.\nUsing AJAX would be the most reasonable option. I'v... | [
1,
1
] | [] | [] | [
"livechat",
"python"
] | stackoverflow_0005672100_livechat_python.txt |
Q:
Compare equal length lists to find positions that share the same element
I want to compare a list of lists that have the same length, but differ in their content. My script should return only the positions that share exactly the same element (in all lists).
For example:
l = [[1,2,3,4,5,6,7,8],[9,8,8,4,3,4,5,7,8],[... | Compare equal length lists to find positions that share the same element | I want to compare a list of lists that have the same length, but differ in their content. My script should return only the positions that share exactly the same element (in all lists).
For example:
l = [[1,2,3,4,5,6,7,8],[9,8,8,4,3,4,5,7,8],[5,6,7,4,9,9,9,8],[0,0,1,4,7,6,3,8]]
and as a result I get a list of positions ... | [
"l = [[1,2,3,4,5,6,7,8],[9,8,8,4,3,4,5,7,8],[5,6,7,4,9,9,9,8],[0,0,1,4,7,6,3,8]]\n\np = [i for i, j in enumerate(zip(*l)) if all(j[0]==k for k in j[1:])]\n\n# p == [3] - because of some typo in your original list, probably too many elements in the second list.\n\nThis is just the one-liner (list comprehension) vers... | [
4,
2,
0,
0
] | [] | [] | [
"elements",
"list",
"python"
] | stackoverflow_0005679680_elements_list_python.txt |
Q:
executable files and django
Is it possible to use executable files with Django. For instance I have a Django form that takes input a file. I want to pass the file as an argument to a script/executable/program and output the results back with django. What would be a good starting point for this idea? Thanks a lot
... | executable files and django | Is it possible to use executable files with Django. For instance I have a Django form that takes input a file. I want to pass the file as an argument to a script/executable/program and output the results back with django. What would be a good starting point for this idea? Thanks a lot
| [
"subprocess\n",
"The question you should you be asking is it possible in python. Essentially all you would need to do it take in the inputs, into a python script which you can call from your django view or what not. Once there run the execute subprocess command with your executable, and take in the results. :)\nG... | [
5,
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005681705_django_python.txt |
Q:
Compiling Jython From Source generate org.python.parser directory
Hello I am trying to compile the Jython Java Source Code from subversion. But it fails because there is no parser directory it should be org.python.parser in org/python/parser. I read that this folder you need to generate. Any ideas how would be gre... | Compiling Jython From Source generate org.python.parser directory | Hello I am trying to compile the Jython Java Source Code from subversion. But it fails because there is no parser directory it should be org.python.parser in org/python/parser. I read that this folder you need to generate. Any ideas how would be great!
I found this link but its very dated and doesn't seem to explain an... | [
"The Jython Developer Guide is what you need. You should just able to run ant in the top-level directory to compile it.\n"
] | [
1
] | [] | [] | [
"java",
"jython",
"python"
] | stackoverflow_0005680534_java_jython_python.txt |
Q:
Keeping DRY with custom Django templatetags
I have an existing templatetag, show_next_event:
def show_next_event():
try:
e = Event.objects.filter(published='1').order_by('date').filter(date__gte=datetime.date.today())[0]
except IndexError:
e = ''
return {'event': e}
register.inclusion_t... | Keeping DRY with custom Django templatetags | I have an existing templatetag, show_next_event:
def show_next_event():
try:
e = Event.objects.filter(published='1').order_by('date').filter(date__gte=datetime.date.today())[0]
except IndexError:
e = ''
return {'event': e}
register.inclusion_tag('events/next_event.html')(show_next_event)
I'... | [
"Django is Python, not Ruby. You can't call a function just by specifying its name: you need to use the calling parentheses. And Python doesn't automatically return the value of the last expression in the function: you need to use the return statement.\nSo, this should work:\n@register.inclusion_tag('events/next_ev... | [
4,
1
] | [] | [] | [
"django",
"django_templates",
"dry",
"python"
] | stackoverflow_0005681875_django_django_templates_dry_python.txt |
Q:
OOP Python add some attribute to the base class?
I am learning OOP with python .trying with small console application Stock
class Stock(object):
def __init__(self, stockName, stockLimit, inStock, rentPrice):
self.stockName = stockName # private
self.stockLimit = stockLimit # private
... | OOP Python add some attribute to the base class? | I am learning OOP with python .trying with small console application Stock
class Stock(object):
def __init__(self, stockName, stockLimit, inStock, rentPrice):
self.stockName = stockName # private
self.stockLimit = stockLimit # private
self.inStock = inStock # private
sel... | [
"\nThe overloaded invoice in the derived class should work fine.\nYour base class constructor needs to have all the parameters, so :\nclass StockProduct(Stock):\n def __init__(self, stockName, stockLimit, inStock, rentPrice, factor):\n # the base-class constructor:\n Stock.__init__(self, stockName,... | [
6,
2
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0005681970_oop_python.txt |
Q:
CL-WHO in Python: clever or just stupid?
I can't tell if this is clever or just stupid. I like CL-WHO and I also like Python, so I've been fiddling with a way to mash the two up. What I want is to say this:
tag("html",
lst(
tag("head"),
tag("body",
lst(
tag("h1", "This is the head... | CL-WHO in Python: clever or just stupid? | I can't tell if this is clever or just stupid. I like CL-WHO and I also like Python, so I've been fiddling with a way to mash the two up. What I want is to say this:
tag("html",
lst(
tag("head"),
tag("body",
lst(
tag("h1", "This is the headline"),
tag("p", "This is the articl... | [
"You should html-escape every text node, attribute value, etc. or html injection and XSS will bite you.\nApart from full-featured templating systems (mako, genhi, chameleon, jinja, etc) the library more similar to what you do is probably lxml\n>>> from lxml.html.builder import HTML, HEAD, BODY, H1, P, A\n>>> from l... | [
1
] | [] | [] | [
"html",
"lisp",
"python"
] | stackoverflow_0005680697_html_lisp_python.txt |
Q:
Installing Python OpenCV with Precompiled Framework
I got the pre-compiled framework of OpenCV 2.0 for Mac, and it works great, but it didn't come with the python bindings. How can I now install the python bindings for OpenCV?
A:
Try http://thepetitegeek.blogspot.com/2009/09/installing-opencv-on-mac-os-x-with.ht... | Installing Python OpenCV with Precompiled Framework | I got the pre-compiled framework of OpenCV 2.0 for Mac, and it works great, but it didn't come with the python bindings. How can I now install the python bindings for OpenCV?
| [
"Try http://thepetitegeek.blogspot.com/2009/09/installing-opencv-on-mac-os-x-with.html\nThe version is pretty old, but the process might help you a bit.\n",
"Instead of using the pre-compiled framework, you'll be on the safe side using something like source-based framework using the source, MacPorts or HomeBrew. ... | [
0,
0,
0
] | [] | [] | [
"frameworks",
"macos",
"opencv",
"python"
] | stackoverflow_0005658115_frameworks_macos_opencv_python.txt |
Q:
What's wrong with this python script?
RAM=open('/root/arg2', 'r').read()
if RAM=="":
try:
if not sys.argv[2]=="":
f = open("/root/arg2","a")
f.write(sys.argv[2])
f.close()
if float(RAM) > 4096:
os.system("echo What the hell?")
What... | What's wrong with this python script? | RAM=open('/root/arg2', 'r').read()
if RAM=="":
try:
if not sys.argv[2]=="":
f = open("/root/arg2","a")
f.write(sys.argv[2])
f.close()
if float(RAM) > 4096:
os.system("echo What the hell?")
What's wrong with the script above? The line af... | [
"You need to have an except or finally block for your try.\nIf you don't want to do anything in the event of an exception just put pass in it.\n try:\n if not sys.argv[2]==\"\":\n f = open(\"/root/arg2\",\"a\")\n f.write(sys.argv[2])\n f.close()\n except:\n pass\... | [
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005682136_python.txt |
Q:
matrix multiplication of arrays in python
I feel a bit silly asking this, but I can't seem to find the answer
Using arrays in Numpy I want to multiply a 3X1 array by 1X3 array and get a 3X3 array as a results, but because dot function always treats the first element as a column vector and the second as a row vecto... | matrix multiplication of arrays in python | I feel a bit silly asking this, but I can't seem to find the answer
Using arrays in Numpy I want to multiply a 3X1 array by 1X3 array and get a 3X3 array as a results, but because dot function always treats the first element as a column vector and the second as a row vector I can' seem to get it to work, I have to ther... | [
"np.outer\nis a builtin to do that:\nA = array([1,2,3])\nprint( \"outer:\", np.outer( A, A ))\n\n(transpose doesn't work because A.T is exactly the same as A for 1d arrays:\nprint( A.shape, A.T.shape, A[:,np.newaxis].shape )\n>>> ( (3,), (3,), (3, 1) )\n\n)\nAdded: np.add.outer adds pairs of elements --\nnp.outer i... | [
8,
3,
0
] | [] | [] | [
"arrays",
"matrix",
"numpy",
"python"
] | stackoverflow_0005674050_arrays_matrix_numpy_python.txt |
Q:
Regex in Python
I am new to python and want to run a code in Python.
Code that I have written is
#!/usr/bin/python
import sys
import re
for line in sys.stdin:
results = re.search('ipAddress=([^&]*])', line)
if len(results.group(1)) != 0:
print results.group(1)
Requirement is finding IP address... | Regex in Python | I am new to python and want to run a code in Python.
Code that I have written is
#!/usr/bin/python
import sys
import re
for line in sys.stdin:
results = re.search('ipAddress=([^&]*])', line)
if len(results.group(1)) != 0:
print results.group(1)
Requirement is finding IP address in a string.String w... | [
"I think you've got one ] too many there. Try\nresults = re.search('ipAddress=([^&]*)', line)\n\n",
"Your input looks like URL query string. Don't parse it by regexp, consider to use urlparse.parse_qs or urlparse.parse_qsl (for Python version less than 2.6 use cgi.parse_qs or cgi.parse_qsl respectively). Those fu... | [
6,
4,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005681642_python_regex.txt |
Q:
Python Twitter - Get tweet URLS
I am using the python-twitter module to get my most recent twitter status updates:
for i in range(0, limit):
tweet = twitter.Api().GetUserTimeline(TWITTER_USERNAME)[i]
tweet.date = datetime.strptime( tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y" )
tweets.app... | Python Twitter - Get tweet URLS | I am using the python-twitter module to get my most recent twitter status updates:
for i in range(0, limit):
tweet = twitter.Api().GetUserTimeline(TWITTER_USERNAME)[i]
tweet.date = datetime.strptime( tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y" )
tweets.append(tweet)
It's working fine, but th... | [
"You'll likely have to parse the text to find and mark up the URLs yourself. Here's a question about that:\nWhat's the cleanest way to extract URLs from a string using Python?\n"
] | [
1
] | [] | [] | [
"django",
"python",
"python_twitter"
] | stackoverflow_0005678552_django_python_python_twitter.txt |
Q:
Easy SQLite wrappers for Python
Are there any other SQLite wrappers for Python available, comparable to Rococheting's mySQL wrapper for php?
http://www.ricocheting.com/code/php/mysql-database-class-wrapper-v3
If no such thing exists at the time I guess I'll create my own wrapper, but I want to make sure I'm not do... | Easy SQLite wrappers for Python | Are there any other SQLite wrappers for Python available, comparable to Rococheting's mySQL wrapper for php?
http://www.ricocheting.com/code/php/mysql-database-class-wrapper-v3
If no such thing exists at the time I guess I'll create my own wrapper, but I want to make sure I'm not doing redundant work.
| [
"SQLite is part of Python standard library since Python 2.5. The API is similar to your linked PHP MySQL class wrapper (you will be working with modules and functions instead of static class methods).\nIf you're looking for an alternative API, you can use SQLAlchemy. You don't have to use the ORM if you don't need ... | [
12,
3
] | [] | [] | [
"python",
"sqlite",
"wrapper"
] | stackoverflow_0005678032_python_sqlite_wrapper.txt |
Q:
Avoiding socket timeouts in SQLAlchemy
I'm new to SQLAlchemy, but I'm trying to use it to create and fill a database for a personal project. I've set pool_timeout to 43200 (twelve hours), but I'm still getting socket timeouts.
engine = sqlalchemy.create_engine(
'postgresql+pg8000://gdwatson:pass@local... | Avoiding socket timeouts in SQLAlchemy | I'm new to SQLAlchemy, but I'm trying to use it to create and fill a database for a personal project. I've set pool_timeout to 43200 (twelve hours), but I'm still getting socket timeouts.
engine = sqlalchemy.create_engine(
'postgresql+pg8000://gdwatson:pass@localhost/dbname',
pool_timeout=43200... | [
"I don't know if this is the recommended method, but you could periodically send a SELECT 1 statement and ensure the connection isn't idle.\nYou could also look into this for some guidance\n"
] | [
2
] | [] | [] | [
"python",
"python_3.x",
"sockets",
"sqlalchemy",
"timeout"
] | stackoverflow_0003516791_python_python_3.x_sockets_sqlalchemy_timeout.txt |
Q:
Fast way to check if a region overlaps another (1-d) region
I have a huge set of regionssically thousands of points with a start and an end. I.e.:
[(3015, 3701), (4011, 5890), ....]
I also have another set of points (both start and end) where I want a quick way to test whether or not a region in this set overlaps ... | Fast way to check if a region overlaps another (1-d) region | I have a huge set of regionssically thousands of points with a start and an end. I.e.:
[(3015, 3701), (4011, 5890), ....]
I also have another set of points (both start and end) where I want a quick way to test whether or not a region in this set overlaps a region in the other set. Is there a fast way to do this?
Thank... | [
"def test(lista, listb):\n a = 0\n b = 0\n found = False\n while a<len(lista) and b<len(listb):\n result = check( lista[a] , listb[b] )\n if result < 0:\n a += 1\n continue\n if result > 0:\n b += 1\n continue\n # we found overlappi... | [
0
] | [
"Find the min/max endpoints of both regions then see if those overlap.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0005682717_python.txt |
Q:
Using Subprocess with Python
I am creating a Django application that takes an input file from a user. I want to use the subprocess module to take the file and pass it as an argument to an external script and take back the results. What would be the format for the subprocess.Popen call. I would like, to also pass a... | Using Subprocess with Python | I am creating a Django application that takes an input file from a user. I want to use the subprocess module to take the file and pass it as an argument to an external script and take back the results. What would be the format for the subprocess.Popen call. I would like, to also pass an option to the script like -a.
In... | [
"subprocess.Popen has a pretty understandable syntax:\nsubprocess.Popen(['./myscript', '-option', 'file'])\n\nJust look through the examples and you'll get the pattern.\n",
"You simply pass a tuple or list of your binary name (in $PATH or relative) and its arguments.\nimport subprocess\np = subprocess.Popen(('./m... | [
5,
1,
1
] | [] | [] | [
"django",
"python",
"subprocess"
] | stackoverflow_0005682436_django_python_subprocess.txt |
Q:
Fastest way to update a dictionary & check for keys
I am building a dictionary of a very long string (~1G), where key is a fixed-length k-mer, and value is all the occurrence positions. When k is large (>9) it makes no sense to pre-build the k-mer dictionary, since not all values will occur & it inflates the tab... | Fastest way to update a dictionary & check for keys | I am building a dictionary of a very long string (~1G), where key is a fixed-length k-mer, and value is all the occurrence positions. When k is large (>9) it makes no sense to pre-build the k-mer dictionary, since not all values will occur & it inflates the table.
Currently I'm doing the task like this:
def hash_stri... | [
"I would use collections.defaultdict:\nimport collections\n...\nhash = collections.defaultdict(list)\nr = stsize-mersize+1\n\nfor i in range(0, r):\n mer = st[i:i+mersize]\n hash[mer].append(i)\n\nthough have never profiled it vs if ... else.\n",
"Generally, the method used will be dependent upon your data.... | [
8,
4,
3,
1
] | [] | [] | [
"append",
"dictionary",
"performance",
"python"
] | stackoverflow_0005654006_append_dictionary_performance_python.txt |
Q:
how to write a sorted function in python for version before 2.4
I am unfortunately having to use python with version before 2.4 So I don't have the sorted built-in function. I need to sort a list; I found it is not possibly to go with
for aName in mylist.sort(lambda x,y:cmp(x.getName,y.getName)):
because then I ... | how to write a sorted function in python for version before 2.4 | I am unfortunately having to use python with version before 2.4 So I don't have the sorted built-in function. I need to sort a list; I found it is not possibly to go with
for aName in mylist.sort(lambda x,y:cmp(x.getName,y.getName)):
because then I would get an error saying
TypeError: iteration over non-sequence
I wa... | [
"You said that you wanted to do for aName in sorted(mylist,key=lambda x:x.getName): but accepted an answer that did something else ...\nIt's quite possible to write code that will run on multiple versions of Python 2.x. Here's how to retrofit sorted() functionality to Python 2.1 to 2.3. It uses the DSU (decorate-so... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005681747_python.txt |
Q:
python Mysql data store
How to store data in MySQL after receiving it from Python?
A:
I don't think that you have provided much information, but here is my shot at an answer. You can use a database library (you can find a list here) to write data to mysql right from you python application.
| python Mysql data store | How to store data in MySQL after receiving it from Python?
| [
"I don't think that you have provided much information, but here is my shot at an answer. You can use a database library (you can find a list here) to write data to mysql right from you python application. \n"
] | [
1
] | [
"Step 1: Select and install the library you want to use to interface with MySQL from the list here. Personally I use MySQLdb.\nStep 2: Use the documentation, online tutorials etc. to attempt to save and retrieve the data. As this is a common task, a Google search shows plenty of examples.\nIf you have any specific ... | [
-1
] | [
"mysql",
"python"
] | stackoverflow_0005682819_mysql_python.txt |
Q:
python calendar with holidays
Possible Duplicate:
Holiday Calendars, File Formats, et al.
Hi,
Is there a calendar library in Python with which I can check for holidays, compute the number of business days from two dates (accounting for holidays in between)?
I'd love it if it is parameterized for the nation (e.g... | python calendar with holidays |
Possible Duplicate:
Holiday Calendars, File Formats, et al.
Hi,
Is there a calendar library in Python with which I can check for holidays, compute the number of business days from two dates (accounting for holidays in between)?
I'd love it if it is parameterized for the nation (e.g. US, Japan, etc) so that the holi... | [
"Here are a couple of other StackOverflow questions whose answers may help you on your quest:\n\nHoliday Calendars, File Formats, et al.\nBusiness days in Python\n\n"
] | [
0
] | [] | [] | [
"calendar",
"python"
] | stackoverflow_0005682771_calendar_python.txt |
Q:
timer objects (python) with arguments
How do you pass arguments between defs within a class using the timer object?
def onrepeat(self,user, arg):
args = arg.split()
messagearg = args[0]
colorarg = args[1]
if colorarg == "black":
color = "&0"
if colorarg == "dark blue" or "darkblue":
... | timer objects (python) with arguments | How do you pass arguments between defs within a class using the timer object?
def onrepeat(self,user, arg):
args = arg.split()
messagearg = args[0]
colorarg = args[1]
if colorarg == "black":
color = "&0"
if colorarg == "dark blue" or "darkblue":
color = "&1"
if colorarg == "dark ... | [
"Timer has the following signature\nclass threading.Timer(interval, function, args=[], kwargs={})\n\nNote that it accepts args and kwargs. So you send your args to Timer function by just mentioning them. Try this:\nTimer(3.0, self.repeat2,messagearg,color)\n\n"
] | [
0
] | [] | [] | [
"arguments",
"object",
"python",
"timer"
] | stackoverflow_0005683411_arguments_object_python_timer.txt |
Q:
Python 2.7 not working in Windows Console
I recently upgraded from python 2.6 to python 2.7 and everytime I try todo python setup.py install I get.
'python' is not recognized as an internal or external command,
operable program or batch file.
It worked fine with 2.6.
A:
That error sounds like the python (or pyt... | Python 2.7 not working in Windows Console | I recently upgraded from python 2.6 to python 2.7 and everytime I try todo python setup.py install I get.
'python' is not recognized as an internal or external command,
operable program or batch file.
It worked fine with 2.6.
| [
"That error sounds like the python (or python.exe in case you are on windows ) binary is not in your PATH.\n"
] | [
5
] | [] | [] | [
"python",
"python_2.7",
"windows_console"
] | stackoverflow_0005683440_python_python_2.7_windows_console.txt |
Q:
python len function question
I am a complete Python noob so please forgive my simple question. I am trying to write a script that will find all sequences in a huge string that match ATxxxCA, ATxxxxCA, ATxxxxxCA, or ATxxxxxxCA where x can be any character. When the ATxxxCA pattern is matched, I would then like the ... | python len function question | I am a complete Python noob so please forgive my simple question. I am trying to write a script that will find all sequences in a huge string that match ATxxxCA, ATxxxxCA, ATxxxxxCA, or ATxxxxxxCA where x can be any character. When the ATxxxCA pattern is matched, I would then like the script to then capture the previou... | [
"\nI seem to be doing something wrong in\n my if loop?\n\nPython doesn't know what the meaning of \"is\" is (in this context). \nRemove \"is\" from your if check,\nif len(s) < 10:\n print(s)\nelse:\n print('no sequence matches')\n\nYou also said:\n\nWhen the ATxxxCA pattern is matched, I\n would then like t... | [
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005682775_python_regex.txt |
Q:
Path between two nodes
I'm using networkx to work with graphs. I have pretty large graph (it's near 200 nodes in it) and I try to find all possible paths between two nodes. But, as I understand, networkx can find only shortest path. How can I get not just shortest path, but all possible paths?
UPD: path can contai... | Path between two nodes | I'm using networkx to work with graphs. I have pretty large graph (it's near 200 nodes in it) and I try to find all possible paths between two nodes. But, as I understand, networkx can find only shortest path. How can I get not just shortest path, but all possible paths?
UPD: path can contain each node only once.
UPD2:... | [
"igraph, another graph module for Python can calculate all the shortest paths between a given pair of nodes. Calculating all the paths does not make sense as you have infinitely many such paths.\nAn example for calculating all the shortest paths from vertex 0:\n>>> from igraph import Graph\n>>> g = Graph.Lattice([1... | [
13,
11,
0
] | [] | [] | [
"igraph",
"networkx",
"python"
] | stackoverflow_0002606018_igraph_networkx_python.txt |
Q:
list of all paths from source to sink in directed acyclic graph
Possible Duplicate:
[python]: path between two nodes
Can anyone point me to some resources on how to do this? I'm using networkx as my python library.
Thanks!
A:
This is based on Alex Martelli's answer, but it should work. It depends on the expre... | list of all paths from source to sink in directed acyclic graph |
Possible Duplicate:
[python]: path between two nodes
Can anyone point me to some resources on how to do this? I'm using networkx as my python library.
Thanks!
| [
"This is based on Alex Martelli's answer, but it should work. It depends on the expression source_node.children yielding an iterable that will iterate over all the children of source_node. It also relies on there being a working way for the == operator to compare two nodes to see if they are the same. Using is m... | [
6,
2,
1
] | [] | [] | [
"directed_acyclic_graphs",
"networkx",
"python"
] | stackoverflow_0003278481_directed_acyclic_graphs_networkx_python.txt |
Q:
reCATPCHA redirect isHuman=false
Hi I added reCAPTCHA to a page so far that it can verify a client. Now I want a more graceful failure when isHuman = Falsewith a redirect to the form page in such case with a message on the form page that reCAPTCHA failed. Can you inform what to do rather than just outputting "capt... | reCATPCHA redirect isHuman=false | Hi I added reCAPTCHA to a page so far that it can verify a client. Now I want a more graceful failure when isHuman = Falsewith a redirect to the form page in such case with a message on the form page that reCAPTCHA failed. Can you inform what to do rather than just outputting "captcha failed?" so that it can redirect t... | [
"If you are just looking for a way to redirect back to your original posting page you can use:\nself.redirect('your_url')\n\nYou could also include a GET variable in the url so that the page is aware that the CAPTCHA failed.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python",
"recaptcha"
] | stackoverflow_0005683261_google_app_engine_python_recaptcha.txt |
Q:
Regular Expressions Using Python's Re
I have the following file full of lines similar to this:
line = 'Weclome - MIsiti International,0,0,-9,0,'
I want to replace 'Weclome - MIsiti International' with the string '1'
here is my code:
exp=re.compile(r"([\./A-Za-z\s\-]+)")
print exp.sub("1",line)
Unfortunately I get... | Regular Expressions Using Python's Re | I have the following file full of lines similar to this:
line = 'Weclome - MIsiti International,0,0,-9,0,'
I want to replace 'Weclome - MIsiti International' with the string '1'
here is my code:
exp=re.compile(r"([\./A-Za-z\s\-]+)")
print exp.sub("1",line)
Unfortunately I get the following output:
1,0,0,19,0,
Which i... | [
"Why do you need a regular expression?\n>>> line = 'Weclome - MIsiti International,0,0,-9,0,'\n>>> s=line.split(\",\")\n>>> s[0]=\"1\"\n>>> ','.join(s)\n'1,0,0,-9,0,'\n\n",
"exp=re.compile(r\"([\\./A-Za-z\\s\\-]+)\"\n\nNo need to put '\\' before '-' between brackets. Put '-' at a place between brackets where it c... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005682772_python_regex.txt |
Q:
Create amount of arrays based off variable number in python?
I was wondering how you create a variable amount of arrays in python. So if the user entered "3" you would get 3 arrays create. Might be obvios but got stuck after this:
baseNumber = 0
#how many rows needed
board_height = []
print "select a ... | Create amount of arrays based off variable number in python? | I was wondering how you create a variable amount of arrays in python. So if the user entered "3" you would get 3 arrays create. Might be obvios but got stuck after this:
baseNumber = 0
#how many rows needed
board_height = []
print "select a width"
x = int(raw_input(">"))
print "select a height"
... | [
"You'd make an array of arrays, actually a list of lists:\nnumber_of_lists = ...\nempty_lists = [[] for i in xrange(number_of_lists)]\n\nIf you wanted a list of lists with something in them already, just specify the initial contents of each individual list within the inner brackets:\nnonempty_lists = [['a', 'b', 'c... | [
2
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0005683627_arrays_python.txt |
Q:
Form validation with django 1.2 GAE
How can I add form validation and preferably with i18n localization? I tried something like the following which doesn't work and needs to import Validationerror
class AForm(djangoforms.ModelForm):
def clean_name(self):
value = self.data['name']
if not value:
... | Form validation with django 1.2 GAE | How can I add form validation and preferably with i18n localization? I tried something like the following which doesn't work and needs to import Validationerror
class AForm(djangoforms.ModelForm):
def clean_name(self):
value = self.data['name']
if not value:
raise ValidationError("No name.")
... | [
"I haven't used the Google app engine, so the import paths are probably wrong, but the pattern I've used before with standard Django is:\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nclass AForm(forms.ModelForm):\n\n def clean_name(self):\n # Get the value from the ... | [
1
] | [] | [] | [
"django_forms",
"django_models",
"google_app_engine",
"localization",
"python"
] | stackoverflow_0005683624_django_forms_django_models_google_app_engine_localization_python.txt |
Q:
Refactoring nose tests with multiple setups
Assume you are given the following testing code, where the test1 and test2 methods run some tests on the grid object.
N = 10
grid = Grid(N)
def test1():
...
def test2():
...
What is the best way to add tests for when N = 11 so that the same methods test1 and ... | Refactoring nose tests with multiple setups | Assume you are given the following testing code, where the test1 and test2 methods run some tests on the grid object.
N = 10
grid = Grid(N)
def test1():
...
def test2():
...
What is the best way to add tests for when N = 11 so that the same methods test1 and test2 are run on the new object? Of course one co... | [
"Using global variables is kind of a sticky way to set up test cases. You should refactor your tests into something like the following.\ndef test1(N):\n grid = Grid(N)\n ...\n\n\ndef test2(N):\n grid = Grid(N)\n ...\n\nFrom there, it looks like you want to take a look at the test generators included in ... | [
1
] | [] | [] | [
"nose",
"python"
] | stackoverflow_0005683648_nose_python.txt |
Q:
Populate a 5 * 5 list with python
I have a list[5][5] to populate... it looks like a table with 5 columns and 5 rows.
Each cell can be either one or zero.
I want to find different 2^25 possibility that can exist. Each possiblity is a combination of either 0 or 1 in a 5*5 table/list
How can I do that? With nested l... | Populate a 5 * 5 list with python | I have a list[5][5] to populate... it looks like a table with 5 columns and 5 rows.
Each cell can be either one or zero.
I want to find different 2^25 possibility that can exist. Each possiblity is a combination of either 0 or 1 in a 5*5 table/list
How can I do that? With nested loop or something?
| [
"I suggest you start small... with a 1x1 list first and check that you can display both of the available combinations:\n[[0]]\n[[1]]\n\nNext up, try a 2x2 list. There are 16 different lists to display:\n[[0, 0], [0, 0]]\n[[0, 0], [0, 1]]\n[[0, 0], [1, 0]]\n[[0, 0], [1, 1]]\n[[0, 1], [0, 0]]\n[[0, 1], [0, 1]]\n[[0, ... | [
3,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0005683739_list_python.txt |
Q:
Python: count occurances of a given char in a string
How would I take a string in Python like "/bin/usr/proga/file.c" and count the occurrences of the '/' character?
So, for the above example, the function would return 4.
A:
"/bin/usr/proga/file.c".count("/")
Refer to the documentation for strings.
A:
>>> s="... | Python: count occurances of a given char in a string | How would I take a string in Python like "/bin/usr/proga/file.c" and count the occurrences of the '/' character?
So, for the above example, the function would return 4.
| [
"\"/bin/usr/proga/file.c\".count(\"/\")\n\nRefer to the documentation for strings.\n",
">>> s=\"/bin/usr/proga/file.c\"\n>>> s.count(\"/\")\n4\n>>> len(s.split(\"/\"))-1\n4\n\n"
] | [
7,
3
] | [] | [] | [
"count",
"python",
"string"
] | stackoverflow_0005683830_count_python_string.txt |
Q:
access calling classes atrributes
I have 2 classes defined as such
class class1():
self.stuff = 1
def blah(self):
foo = class2()
foo.start()
class class2(threading.Thread):
def run(self):
#access class1.stuff
How would I access class1.stuff from class2
A:
It could look like t... | access calling classes atrributes | I have 2 classes defined as such
class class1():
self.stuff = 1
def blah(self):
foo = class2()
foo.start()
class class2(threading.Thread):
def run(self):
#access class1.stuff
How would I access class1.stuff from class2
| [
"It could look like this:\nclass class1(object):\n stuff = 1\n def blah(self):\n foo = class2()\n foo.start()\n\nclass class2(threading.Thread):\n def run(self):\n print(class1.stuff)\n\nThere is no special syntax to \"access calling classes atrributes\". If you want access to a object ... | [
0
] | [
"You would have to pass it into the function.\nclass class1():\n self.stuff = 1\n def blah(self):\n foo = class2()\n foo.start(self)\n\nclass class2(threading.Thread):\n def run(self, obj):\n obj.stuff;\n\nThere is no way to access another object's properties without having a referenc... | [
-1
] | [
"python"
] | stackoverflow_0005683806_python.txt |
Q:
Sorting Lists of tuples based on a list of tuples - Python
I am trying to sort a list of tuples based on another list of tuples by a key in that list.
Say I have the following:
list1 = [(5, 'something'),(2,'bobby'),(9,'suzy'),(6,'crab')]
list2 = [('something','othervalues'),('suzy','stuff'),('bobby','otherthings')... | Sorting Lists of tuples based on a list of tuples - Python | I am trying to sort a list of tuples based on another list of tuples by a key in that list.
Say I have the following:
list1 = [(5, 'something'),(2,'bobby'),(9,'suzy'),(6,'crab')]
list2 = [('something','othervalues'),('suzy','stuff'),('bobby','otherthings')]
And from this I would receive the output soring on the first ... | [
"First create a dictionary from list1:\n>>> order = dict(reversed(t) for t in list1)\n\nThis creates a name -> number mapping.\nThen you can use the sorted method (don't name your variable this way) and a lambda expression as key:\n>>> sorted(list2, key=lambda x: order[x[0]], reverse=True)\n[('suzy', 'stuff'), ('so... | [
3,
3,
0
] | [] | [] | [
"python",
"sorting",
"tuples"
] | stackoverflow_0005684053_python_sorting_tuples.txt |
Q:
unit test to check if for a given path a correct context will be returned
Just like in the title. I have a model that I can test manually. I enter url in a browser and receive a result form one of the views. Thing is unittest should be doing that.
I think there should be some way to create a request, send it to th... | unit test to check if for a given path a correct context will be returned | Just like in the title. I have a model that I can test manually. I enter url in a browser and receive a result form one of the views. Thing is unittest should be doing that.
I think there should be some way to create a request, send it to the application and in return receive the context.
| [
"You can create functional tests using the WebTest package, which allows you to wrap your WSGI application in a TestApp that supports .get(), .post(), etc.\nSee http://docs.pylonsproject.org/projects/pyramid/1.0/narr/testing.html#creating-functional-tests for specifics in Pyramid, pasted here for posterity:\nimport... | [
2,
1
] | [] | [] | [
"pylons",
"pyramid",
"python",
"testing",
"unit_testing"
] | stackoverflow_0005682581_pylons_pyramid_python_testing_unit_testing.txt |
Q:
python function not repeating
I have a python tool to 'touch' (utime) a file, then move to another folder. However, if the file already exists in the destination folder, it is silently overwritten. I would like to check for a file of the same name in the destination folder and, if it exists, rename the one I am mo... | python function not repeating | I have a python tool to 'touch' (utime) a file, then move to another folder. However, if the file already exists in the destination folder, it is silently overwritten. I would like to check for a file of the same name in the destination folder and, if it exists, rename the one I am moving to its name plus '-n' at the e... | [
"Your problem is that, if the file exists, you don't return anything. I think you're intending to use recursion to check the new filename, but you don't return the result of that call. Here's a stab:\ndef checkExists(fileName, index=0):\n print \"checkExists(\" + fileName + \")\"\n\n if exists(fileName):\n ... | [
2,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0005683963_function_python.txt |
Q:
HTML parsing to obtain what I want
I'm trying to do a little bit of HTML parsing in Python which I'm horrible at to be quite honest. I've been up googling ways to do this but can't get anything to work. Here is my situation. I have a web page that has a BUNCH of links to downloads. What I want to do is specify a s... | HTML parsing to obtain what I want | I'm trying to do a little bit of HTML parsing in Python which I'm horrible at to be quite honest. I've been up googling ways to do this but can't get anything to work. Here is my situation. I have a web page that has a BUNCH of links to downloads. What I want to do is specify a search string, and if the string I am sea... | [
"Once you have the HTML data, parse it and then you can make selections of nodes within the page:\nimport lxml.html\ntree = lxml.html.fromstring(dload)\nfor node in tree.xpath('//a'):\n print node['href']\n\n"
] | [
1
] | [] | [] | [
"html",
"python"
] | stackoverflow_0005684275_html_python.txt |
Q:
Finding k-nearest neighbors for a given vector?
Given that I have the following in my knowledge-database:
1 0 6 20 0 0 6 20
1 0 3 6 0 0 3 6
1 0 15 45 0 0 15 45
1 0 17 44 0 0 17 44
1 0 2 5 0 0 2 5
I want to be able to find the nearest neighbors of the following vector:
1 0 5 16 0 0 5 ... | Finding k-nearest neighbors for a given vector? | Given that I have the following in my knowledge-database:
1 0 6 20 0 0 6 20
1 0 3 6 0 0 3 6
1 0 15 45 0 0 15 45
1 0 17 44 0 0 17 44
1 0 2 5 0 0 2 5
I want to be able to find the nearest neighbors of the following vector:
1 0 5 16 0 0 5 16
according to a distance metric. So in this case, ... | [
"In Python (from www.comp.mq.edu.au/):\ndef count_different_values(k_v1s, k_v2s):\n \"\"\"kv1s and kv2s should be dictionaries mapping keys to \n values. count_different_values() returns the number of keys in \n k_v1s and k_v2s that don't have the same value\"\"\"\n ks = set(k_v1s.iterkeys()) | set(k_v... | [
8
] | [] | [] | [
"algorithm",
"language_agnostic",
"mysql",
"python",
"search"
] | stackoverflow_0005684370_algorithm_language_agnostic_mysql_python_search.txt |
Q:
every element of list is True boolean
I know that
all(map(compare,new_subjects.values()))==True
would tell me if every element of the list is True. However, how do I tell whether every element except for one of them is True?
A:
values = map(compare, new_subjects.values())
len([x for x in values if x]) == len(v... | every element of list is True boolean | I know that
all(map(compare,new_subjects.values()))==True
would tell me if every element of the list is True. However, how do I tell whether every element except for one of them is True?
| [
"values = map(compare, new_subjects.values())\nlen([x for x in values if x]) == len(values) - 1\n\nBasically, you filter the list for true values and compare the length of that list to the original to see if it's one less.\n",
"If you mean is actually True and not evaluates to True, you can just count them?\n>>> ... | [
12,
7,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0005683875_python.txt |
Q:
Where does ActivePython install pyqt4?
I am currently using a Windows XP machine (32 bit). I am new to Scribus, and have enjoyed using it over the other expensive program for desktop publishing. In Scribus I have a prewritten script I would like to run. The beginning of the script contains:
#!/usr/bin/env python
... | Where does ActivePython install pyqt4? | I am currently using a Windows XP machine (32 bit). I am new to Scribus, and have enjoyed using it over the other expensive program for desktop publishing. In Scribus I have a prewritten script I would like to run. The beginning of the script contains:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4.QtCore i... | [
"Type this command to see where PyQt is installed:\npypm files --full-path pyqt4\n\nBy default, PyPM installs packages into your %APPDATA%\\Python directory. If you want to install globally into C:\\Python32 use the -g option (like: pypm -g install pyqt4)\n\nHow do I make sure that script is able to fing the PYQT4 ... | [
2
] | [] | [] | [
"activepython",
"pypm",
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0005683801_activepython_pypm_pyqt_pyqt4_python.txt |
Q:
python regular expression tag
I want to change this string
<p><b> hello world </b></p>. I am playing <b> python </b>
to:
<bold><bold>hello world </bold></bold>, I am playing <bold> python </bold>
I used:
import re
pattern = re.compile(r'\<p>(.*?)\</p>|\<b>(.*?)\</b>')
print re.sub(pattern, r'<bold>\1</bold>', ... | python regular expression tag | I want to change this string
<p><b> hello world </b></p>. I am playing <b> python </b>
to:
<bold><bold>hello world </bold></bold>, I am playing <bold> python </bold>
I used:
import re
pattern = re.compile(r'\<p>(.*?)\</p>|\<b>(.*?)\</b>')
print re.sub(pattern, r'<bold>\1</bold>', "<p><b>hello world</b></p>. I am pl... | [
"If you choose not to use regex, then it simple as this:\nd = {'<p>':'<bold>','</p>':'</bold>','<b>':'<bold>','</b>':'</bold>'}\ns = '<p><b> hello world </b></p>. I am playing <b> python </b>'\nfor k,v in d.items():\n s = s.replace(k,v)\n\n",
"Although I don't recommend using Regex for parsing HTML (there are ... | [
5,
3,
2
] | [] | [] | [
"expression",
"python",
"regex"
] | stackoverflow_0005684010_expression_python_regex.txt |
Q:
Hadoop Vs. Disco Vs. Condor?
I am trying to find a tool that will manage a bunch of jobs on 100 machines in a cluster (submit the jobs to the machines; make sure that jobs are run etc).
Which tool would be more simple to install / manage:
(1) Hadoop?
(2) Disco?
(3) Condor?
Ideally, I am searching for a solution th... | Hadoop Vs. Disco Vs. Condor? | I am trying to find a tool that will manage a bunch of jobs on 100 machines in a cluster (submit the jobs to the machines; make sure that jobs are run etc).
Which tool would be more simple to install / manage:
(1) Hadoop?
(2) Disco?
(3) Condor?
Ideally, I am searching for a solution that would be as simple as possible,... | [
"I'm unfamiliar with Disco and Condor, but I can answer regarding Hadoop:\nHadoop pros: \n\nRobust and proven - probably more than anything else out there. Used by many organizations (including the one I work for) to run clusters of 100s of nodes and more.\nLarge ecosystem = support + many subprojects to make life ... | [
3,
0
] | [] | [] | [
"distributed_computing",
"python"
] | stackoverflow_0005682175_distributed_computing_python.txt |
Q:
Interactive user input while using stdout
in a script I use sys.stdout.write() to output processed data to stdout, which later I use on CLI to redirect stdout to file:
python.exe script.py > file.out
I could not write to file inside python script as redirected file can't be known
My problem is that I use also raw... | Interactive user input while using stdout | in a script I use sys.stdout.write() to output processed data to stdout, which later I use on CLI to redirect stdout to file:
python.exe script.py > file.out
I could not write to file inside python script as redirected file can't be known
My problem is that I use also raw_input(), as I need user to pass certain number... | [
"See if this works for you:\n#!/usr/bin/python\nimport sys\nimport os\n# Disable buffering for stdout\nsys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)\nx = raw_input(\">\")\nprint x\n\nRun this as:\npython ./test.py | tee ./file.out\n\nNow, you will see your output on console and it will be redirected to the fi... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005684193_python.txt |
Q:
Listing Related Fields in Django ModelAdmin
I'm listing a model in Django's admin via a TabularInline. Inside this inline, I'd like to use Django's model traversal syntax to list data in other models referenced from this model via foreign keys. e.g.
class MyRelatedModel(models.Model):
name = models.CharField(m... | Listing Related Fields in Django ModelAdmin | I'm listing a model in Django's admin via a TabularInline. Inside this inline, I'd like to use Django's model traversal syntax to list data in other models referenced from this model via foreign keys. e.g.
class MyRelatedModel(models.Model):
name = models.CharField(max_length=50)
created = models.DateField(auto... | [
"As per Roseman's suggestion above, you can display related (one-to-one or many-to-one) data in a readonly manner with Inline admin models. Here's a little example, just to make sure that we are all on the same page. You can see below that there are three ways to achieve your goal (if I understand that goal correct... | [
30
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0005678968_django_django_admin_python.txt |
Q:
Facebook integration using python library
I created a simple web app using django and was wondering if there is any python library out there that could help me integrate my app with facebook.
Thanks!
A:
A simple search for "facebook" on PyPI
http://pypi.python.org/pypi?%3Aaction=search&term=facebook&submit=searc... | Facebook integration using python library | I created a simple web app using django and was wondering if there is any python library out there that could help me integrate my app with facebook.
Thanks!
| [
"A simple search for \"facebook\" on PyPI\nhttp://pypi.python.org/pypi?%3Aaction=search&term=facebook&submit=search\ngives two django related modules with the first two hits.\nhttp://pypi.python.org/pypi/django-facebook/2.0.16\nhttp://pypi.python.org/pypi/django-la-facebook/0.1.0\nApart from that there is always th... | [
2
] | [] | [] | [
"facebook",
"python"
] | stackoverflow_0005684768_facebook_python.txt |
Q:
can python (version 2.6 ) create web services on the windows(32)?
can python (version 2.6 ) create web services on the windows(32)? i hava a program that need python create a web service project.python 2.6 linked to mysql.
In China , less men develop it,so i can't find modules for web services!!
if not,Linux may b... | can python (version 2.6 ) create web services on the windows(32)? | can python (version 2.6 ) create web services on the windows(32)? i hava a program that need python create a web service project.python 2.6 linked to mysql.
In China , less men develop it,so i can't find modules for web services!!
if not,Linux may be the next step.
| [
"http://wiki.python.org/moin/WebFrameworks. There's a ton of web frameworks for Python that will work on any platform. I'm not sure exactly what you mean by \"web service\", but I promise you that you'll find something that meets your needs on that list.\n",
"You can start by taking a look at:\nBest way to create... | [
1,
1
] | [] | [] | [
"python",
"service"
] | stackoverflow_0005684814_python_service.txt |
Q:
Find tracks that match group by length
can someone please come up with a solution to this problem, in programming language of choice (preferably Python, but anything could be fine I guess):
I have various track length groups, let's say:
10:03
24:23
...
and source tracks themselves:
1:03
9:00
4:24
...
and I need ... | Find tracks that match group by length | can someone please come up with a solution to this problem, in programming language of choice (preferably Python, but anything could be fine I guess):
I have various track length groups, let's say:
10:03
24:23
...
and source tracks themselves:
1:03
9:00
4:24
...
and I need to find pragmatically which tracks belongs t... | [
"Look at the itertools module of Python:\nhttp://docs.python.org/library/itertools.html\nIt supports to calculate all possible permutations() and combinations() of the tracks.\nThe rest is up to you (not doing your real homework).\n",
"This is a hard general NP-complete problem, known as Knapsack problem. You can... | [
0,
0
] | [] | [] | [
"algorithm",
"knapsack_problem",
"python"
] | stackoverflow_0005684908_algorithm_knapsack_problem_python.txt |
Q:
Python: better file I/0 using os.fork?
My problem is quite simple: I have a 400MB file filled with 10,000,000 lines of data. I need to iterate over each line, do something, and remove the line from memory to avoid filling-up too much RAM.
Since my machine has several processor, my initial idea to optimize this pro... | Python: better file I/0 using os.fork? | My problem is quite simple: I have a 400MB file filled with 10,000,000 lines of data. I need to iterate over each line, do something, and remove the line from memory to avoid filling-up too much RAM.
Since my machine has several processor, my initial idea to optimize this process was to create two different processes. ... | [
"Your proposed for line in open('/data/workfile', 'r'): will use a generator, so the entire file will not be read into memory. I'd go with that until it actually turns out to be too slow.\n",
"You're probably limited by the speed of your disk. Python already does buffering so reading it line by line is efficient... | [
4,
2,
1,
0
] | [] | [] | [
"file_io",
"multiprocessing",
"python",
"shared_memory"
] | stackoverflow_0002388394_file_io_multiprocessing_python_shared_memory.txt |
Q:
Setting and resetting value of variable in django template
I want to set and reset flag variable inside django template. Is there any way for doing that?
{% for software in softwares %}
//here want to asign default value to flag( flag = False)
{% for mysoftware in mysoftwares %}
{% if mysoftware.... | Setting and resetting value of variable in django template | I want to set and reset flag variable inside django template. Is there any way for doing that?
{% for software in softwares %}
//here want to asign default value to flag( flag = False)
{% for mysoftware in mysoftwares %}
{% if mysoftware.name == software.name %}
//here want to set value to Tru... | [
"There isn't a way to do this to my knowledge. Perhaps precalculate a list of tuples in your view, and iterate over that instead - displaying the results. e.g.:\n{% for software, assigned in software_list %}\n {% if assigned %}\n {{ software.name }}\n {% else %}\n Software not assigned\n {% endif %}\n{% ... | [
5
] | [] | [] | [
"django_templates",
"google_app_engine",
"python"
] | stackoverflow_0005685252_django_templates_google_app_engine_python.txt |
Q:
using python properties inside __init__?
I have a class using several property()'s. Modifying a text's font, size, or string, etc.. will require a re-render of a surface to cache.
What is the recommended way to call a class's own property(), inside init ? The problem is that the variable has not been set, at the t... | using python properties inside __init__? | I have a class using several property()'s. Modifying a text's font, size, or string, etc.. will require a re-render of a surface to cache.
What is the recommended way to call a class's own property(), inside init ? The problem is that the variable has not been set, at the time I want to call @property DrawText.text
If ... | [
"It fails because the backing field self._text is not defined yet when the setter is called the first time.\nSimple initialize it on the class level:\nclass DrawText(object):\n _text = None\n # your code here\n\nAnother solution (in your case) would be simply setting both the backing field of the property and... | [
2,
2
] | [] | [] | [
"properties",
"python"
] | stackoverflow_0005685237_properties_python.txt |
Q:
Writing a CPU bound script to gauge rough CPU performance
I have wrote a script and running it on different machines. Script looks like below
def f(n):
x = None
while n:
x = simple_math(n)
n -= 1
return x
start = now()
f(BIGNUM)
print now() - start
At the end of the script it p... | Writing a CPU bound script to gauge rough CPU performance | I have wrote a script and running it on different machines. Script looks like below
def f(n):
x = None
while n:
x = simple_math(n)
n -= 1
return x
start = now()
f(BIGNUM)
print now() - start
At the end of the script it print how much time does it take to finish. Is this good enough ... | [
"What's wrong with all of the countless existing benchmarks? The more sophisticated ones are propably a bit more robust. The major problems of your naive approach I - and I'm not an expert on this topic, mind you - can spot are:\n\nModern CPUs are highly complex and employ very clever optimizations. The speed of a ... | [
5,
1,
1,
0
] | [] | [] | [
"cpu",
"performance",
"python"
] | stackoverflow_0005685336_cpu_performance_python.txt |
Q:
Python class factory problem referencing base class?
I recently came across a Python class factory implementation that fit a problem I am working on really well. The only difference is that I wanted have the base and sub classes in different packages.
When I try to do this, however, I run into a problem whenever I... | Python class factory problem referencing base class? | I recently came across a Python class factory implementation that fit a problem I am working on really well. The only difference is that I wanted have the base and sub classes in different packages.
When I try to do this, however, I run into a problem whenever I try to load the base class.
Structure:
BaseClass.py
from ... | [
"Some experimenting appears to show that the problem is import recursion. Making the import statement in BaseClass.py conditional solved the problem for my tests:\nif __name__ == '__main__':\n from subclasses import *\n\nprevents the recursion and python appears satisfied with this.\n[EDIT]\nA better solution is... | [
2,
1
] | [] | [] | [
"class",
"factory",
"import",
"importerror",
"python"
] | stackoverflow_0005686156_class_factory_import_importerror_python.txt |
Q:
Is there a non-deprecated equivalent of rfc822.AddressList?
I need something like rfc822.AddressList to parse, say, the content of the "TO" header field of an email into individual addresses. Since rfc822 is deprecated in favor of the email package, I looked for something similar there but couldn't find anything.... | Is there a non-deprecated equivalent of rfc822.AddressList? | I need something like rfc822.AddressList to parse, say, the content of the "TO" header field of an email into individual addresses. Since rfc822 is deprecated in favor of the email package, I looked for something similar there but couldn't find anything. Does anyone know what I'm supposed to use instead?
Thanks!
| [
"Oh it's email.utils.getaddresses. Just make sure to call it with a list.\n",
"If you are open to using a third party module, I ported the Python 2.x module rfc822 to Python 3.x\nhttps://github.com/MarkNenadov/rfc822py3\nIt hasn't been tested thoroughly yet. I encourage you to try it out and let me know how it w... | [
6,
0
] | [] | [] | [
"email",
"email_parsing",
"python",
"rfc822"
] | stackoverflow_0004084608_email_email_parsing_python_rfc822.txt |
Q:
Why isn't this Python import working?
I have three modules:
plugin_grt.py
fragments.py
helpers.py
Right at the top of plugin_grt.py I have
from jpa_export_helpers import SourceFile, Mysql, Conv, Columns, Column, Table, ForeignKey, Index, Catalog, Inheritance
which works, that is I can use Table.whateverMethod(...... | Why isn't this Python import working? | I have three modules:
plugin_grt.py
fragments.py
helpers.py
Right at the top of plugin_grt.py I have
from jpa_export_helpers import SourceFile, Mysql, Conv, Columns, Column, Table, ForeignKey, Index, Catalog, Inheritance
which works, that is I can use Table.whateverMethod(...) without problems. Now when I add the same... | [
"When you import into a module, you import into the module's namespace. Thus when you have \n from jpa_export_helpers import SourceFile\n\nin plugin_jrt_py you have actually created a name plugin_jrt_py.SourceFile. Following namespace resolution, within plug_in_jrt.py that name can be shortened to SourceFile but on... | [
3,
2
] | [] | [] | [
"class",
"import",
"module",
"python"
] | stackoverflow_0005686575_class_import_module_python.txt |
Q:
Transaction beginning in Django
I read the chapter in the Django docs about the transaction management. From what I understand, the transaction is started as soon as TransactionMiddleware is invoked. Then by using @commit_on_success, @commit_manually there is a possibility of controlling transaction ending.
My que... | Transaction beginning in Django | I read the chapter in the Django docs about the transaction management. From what I understand, the transaction is started as soon as TransactionMiddleware is invoked. Then by using @commit_on_success, @commit_manually there is a possibility of controlling transaction ending.
My question: is there a possibility to cont... | [
"\nTransactions are created with first DB query.\nTransactionMiddleware applies something similar to commit_on_success to all your views. There's no need to add this explicitly. commit_on_success is still useful for giving this behavior to specific functions you call from within a view.\nNested transactions are s... | [
4
] | [] | [] | [
"django",
"django_middleware",
"django_orm",
"python",
"transactions"
] | stackoverflow_0005686813_django_django_middleware_django_orm_python_transactions.txt |
Q:
Trouble using eval() with cython
I was trying to speed up some code, and then I tried compiling a class and a function using cython
and WOW! I havn't measured it yet but it looks at least 10x faster.
I first looked at cython just two days ago, I'm very impressed!
However, I can't get eval() to work.
def thefirst(... | Trouble using eval() with cython | I was trying to speed up some code, and then I tried compiling a class and a function using cython
and WOW! I havn't measured it yet but it looks at least 10x faster.
I first looked at cython just two days ago, I'm very impressed!
However, I can't get eval() to work.
def thefirst(int a):
d = eval('1+2+a')
retu... | [
"This is because eval has no way of examining the environment to find a. Use the locals function to pass it the environment.\ndef thefirst(a):\n return eval('1+2+a', locals())\n\n",
"You may get away with cython.inline:\nhttp://wiki.cython.org/enhancements/inline\nHowever, keep an eye on your Python runtime's... | [
7,
4
] | [] | [] | [
"cython",
"python"
] | stackoverflow_0002589121_cython_python.txt |
Q:
Getting 4 rather than 4.76 as answer to math / science problem (always integer not decimal)
So this is in a way connected to my problem with drawing the energy levels etc. link to the problem.
Anywho, I was using discretization to get the energy levels and wave functions for various potentials, and I'm probably a ... | Getting 4 rather than 4.76 as answer to math / science problem (always integer not decimal) | So this is in a way connected to my problem with drawing the energy levels etc. link to the problem.
Anywho, I was using discretization to get the energy levels and wave functions for various potentials, and I'm probably a tool in programming, because I have no idea how to get the numerical result for the energy eigenv... | [
"This is your issue:\n>>> '%d' % 1.2\n'1'\n\nThe format string you want is %f to show decimal\n>>> '%f' % 1.2\n'1.200000'\n\nThe clutch of the diagnosis was the fact that it was an integer rather than a float you were seeing.\nMore information can be found at http://docs.python.org/library/stdtypes.html\nFor exampl... | [
6,
1
] | [] | [] | [
"math",
"python"
] | stackoverflow_0005686416_math_python.txt |
Q:
*.pyd file fails to load, but DependancyWalker comes up clean, and ProcMon shows it loaded
I am trying to load a *.pyd with Python, but I receive the well known "Import Error: DLL load failed: the specified procedure can not be found." error.
I have already done the following:
1.) Investigated the *.pyd with Depe... | *.pyd file fails to load, but DependancyWalker comes up clean, and ProcMon shows it loaded | I am trying to load a *.pyd with Python, but I receive the well known "Import Error: DLL load failed: the specified procedure can not be found." error.
I have already done the following:
1.) Investigated the *.pyd with Dependency Walker. GPSVC.DLL and IESHIMS.DLL came up as missing, but delay loaded, IEFRAME.DLL aslo... | [
"Is the .pyd file for the same version of Python you're using? Loading a .pyd file for the wrong Python version can produce that error message.\nDependency Walker can show you which pythonNN.dll it links to.\n",
"If you have a file foo.pyd, for import foo to succeed, there must be an externally accessible functio... | [
5,
1,
1
] | [] | [] | [
"dll",
"procmon",
"pyd",
"python"
] | stackoverflow_0005667556_dll_procmon_pyd_python.txt |
Q:
Reverse Engineer Auto-Generated C?
How easy is it to reverse engineer an auto-generated C code? I am working on a Python project and as part of my work, am using Cython to compile the code for speedup purposes.
This does help in terms of speed, yet, I am concerned that where I work, some people would try to "peek"... | Reverse Engineer Auto-Generated C? | How easy is it to reverse engineer an auto-generated C code? I am working on a Python project and as part of my work, am using Cython to compile the code for speedup purposes.
This does help in terms of speed, yet, I am concerned that where I work, some people would try to "peek" into the code and figure out what it do... | [
"Okay -- to attempt to answer your question more directly: most auto-generated C code is fairly ugly, so somebody would need to be fairly motivated to reverse engineer it. At the same time, I don't believe I've never looked at what Cython generates, so I'm not sure how it looks.\nIn addition, a lot of auto-generate... | [
7,
2,
2
] | [] | [] | [
"c",
"cython",
"python",
"reverse_engineering"
] | stackoverflow_0005507531_c_cython_python_reverse_engineering.txt |
Q:
How to add keyboard navigation to a menu?
How can I add keyboard navigation (using Alt with underlines to suggest what other keys to use) to a python gtk gobject-introspection application.
This code works for showing a simple menu but does not add keyboard navigation:
mb = Gtk.MenuBar()
filemenu = Gtk.Menu()
filem... | How to add keyboard navigation to a menu? | How can I add keyboard navigation (using Alt with underlines to suggest what other keys to use) to a python gtk gobject-introspection application.
This code works for showing a simple menu but does not add keyboard navigation:
mb = Gtk.MenuBar()
filemenu = Gtk.Menu()
filem = Gtk.MenuItem()
filem.set_label("File")
filem... | [
"Set the use-underline property and prepend _ to the key you want to use as shortcut.\nclose_menu = Gtk.MenuItem()\nclose_menu.set_label(\"_Close\")\nclose_menu.set_use_underline(True)\n\nIf your version of PyGObject is recent enough, you can also use\nclose_menu = Gtk.MenuItem(\"_Close\", True)\n\n"
] | [
3
] | [] | [] | [
"gobject",
"gtk",
"menu",
"python"
] | stackoverflow_0005668695_gobject_gtk_menu_python.txt |
Q:
Parsing a file with multiple xmls in it
Is there a way to parse a file which contains multiple xmls in it?
eg., if I have a file called stocks.xml and within the stocks.xml i have more than one xml content, is there any way to parse this xml file ?.
-- stocks.xml
<?xml version="1.0" encoding="ASCII"?><PRODUCT><ID>... | Parsing a file with multiple xmls in it | Is there a way to parse a file which contains multiple xmls in it?
eg., if I have a file called stocks.xml and within the stocks.xml i have more than one xml content, is there any way to parse this xml file ?.
-- stocks.xml
<?xml version="1.0" encoding="ASCII"?><PRODUCT><ID>A001</ID>..</PRODUCT><SHOP-1><QUANTITY>nn</QU... | [
"If you can assume that each xml document begins with <?xml version=\"1.0\" ..., simply read the file line-by-line looking for a lines that match that pattern (or, read all the data and then do a search through the data).\nOnce you find a line, keep it, and append subsequent lines until the next xml document is fou... | [
3,
0,
0,
0
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0005687056_python_xml.txt |
Q:
Solving a programming-contest using Python
I found this problem, which I thought would be interesting to solve but couldn't really come up with a correct solution-
Inside a room, there is a monster with
N heads, and a human (with 1 head).
The human has two laser guns. The
first gun, A destroys C1 heads whe... | Solving a programming-contest using Python | I found this problem, which I thought would be interesting to solve but couldn't really come up with a correct solution-
Inside a room, there is a monster with
N heads, and a human (with 1 head).
The human has two laser guns. The
first gun, A destroys C1 heads when
fired and the second gun,B destroys C2
hea... | [
"Ah, I see you have found a solution in C++ already using Dijkstra's algorithm: http://hashsamrat.blogspot.com/2010/10/surviving-monster-programming-problem.html\nHowever, you seem to be thinking about 'recursion' and other methods.\nThe solution is separate than the implementation. Thus what you really want to do ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005687682_python.txt |
Q:
multi-platform gui app in C(P)ython or D
I really like D(2) language and would like to use it for multi-platform GUI application, but I see that its ecosystem is not quite developed. After moving from Linux to (Free)PC-BSD, I see there is even no 64bit compiler ready in the ports and one is not sure if any of GUI ... | multi-platform gui app in C(P)ython or D | I really like D(2) language and would like to use it for multi-platform GUI application, but I see that its ecosystem is not quite developed. After moving from Linux to (Free)PC-BSD, I see there is even no 64bit compiler ready in the ports and one is not sure if any of GUI libs (QtD, gtkD, wxD) are ready for serious pr... | [
"I'm obviously biased as a Cython core developer, but I can certainly recommend it. The combination of CPython and Cython provides an otherwise hard to reach level of developing speed, platform stability, portability, low-level coding and FFI capabilities, and execution performance, including a very easy optimisati... | [
7,
6,
2,
1
] | [] | [] | [
"cpython",
"cython",
"d",
"python",
"user_interface"
] | stackoverflow_0005685078_cpython_cython_d_python_user_interface.txt |
Q:
Accessing the HIDAPI library in python
I am trying to use python to communicate with a generic HID device.
I have read that the HIDAPI library, written in C, beats libusb1.0 for simple and stable cross-platform HID communication. However, no one has ever bothered to show how to call the HIDAPI functions from with... | Accessing the HIDAPI library in python | I am trying to use python to communicate with a generic HID device.
I have read that the HIDAPI library, written in C, beats libusb1.0 for simple and stable cross-platform HID communication. However, no one has ever bothered to show how to call the HIDAPI functions from within a python script, and that is where I am h... | [
"This is not the exact answers to your question, but may give some new pointers.\nWhen interacting with complex native libraries, you probably need to write some C code to \"bridge the gap\" and ctypes alone might not cut it. The bridge code simplifies C structures before passing them down to Python and vice versa... | [
3
] | [] | [] | [
"ctypes",
"hid",
"python",
"usb"
] | stackoverflow_0005557552_ctypes_hid_python_usb.txt |
Q:
Static media fails to load in Django
My settings.py contains the following configuration parameters.
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
'C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows',
)
My project's CSS file is located at C:/Users/ABC/Desk... | Static media fails to load in Django | My settings.py contains the following configuration parameters.
STATIC_ROOT = ''
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
'C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows',
)
My project's CSS file is located at C:/Users/ABC/Desktop/DBMS/DjangoProject/tvshows/static/defa... | [
"Things to check:\n\nDEBUG = True in settings.py\nurls \nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\n# ... the rest of your URLconf goes here ...\n\nurlpatterns += staticfiles_urlpatterns()\n\nuse context processor or load static if {{ STATIC_URL }} isn't working\n\nIf {{ STATIC_URL }} is... | [
4,
3
] | [] | [] | [
"django",
"django_settings",
"python"
] | stackoverflow_0005687136_django_django_settings_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.