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:
ipython and reference counts
It would appear that ipython may be retaining references to objects when I'm not expecting it to.
Consider the following script (grc.py):
import sys
obj = []
print sys.getrefcount(obj)
When I run it in ipython:
Python 2.7.1 |EPD 7.0-2 (64-bit)| (r271:86832, Nov 29 2010, 13:51:37)
In ... | ipython and reference counts | It would appear that ipython may be retaining references to objects when I'm not expecting it to.
Consider the following script (grc.py):
import sys
obj = []
print sys.getrefcount(obj)
When I run it in ipython:
Python 2.7.1 |EPD 7.0-2 (64-bit)| (r271:86832, Nov 29 2010, 13:51:37)
In [1]: %run grc.py
2
In [2]: print ... | [
"Yes, IPython does maintain references to objects behind the scenes. Using %run in particular leaves references in the machinery that handles modules.\nWe're working on it in the development version (which will hopefully become 0.11 soon) - see this issue for more information. The references will still be there, bu... | [
3
] | [] | [] | [
"ipython",
"memory_leaks",
"python",
"reference_counting"
] | stackoverflow_0006019835_ipython_memory_leaks_python_reference_counting.txt |
Q:
What's the best way to duplicate fork() in windows?
How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the fork() system call, using Python?
I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in t... | What's the best way to duplicate fork() in windows? | How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the fork() system call, using Python?
I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.
| [
"Use the python multiprocessing module which will work everywhere.\nHere is a IBM developerWords article that shows how to convert from os.fork() to the multiprocessing module.\n",
"fork() has in fact been duplicated in Windows, under Cygwin, but it's pretty hairy.\n\nThe fork call in Cygwin is particularly inter... | [
18,
10,
3,
3,
3,
2,
0
] | [] | [] | [
"fork",
"process",
"python",
"subprocess",
"windows"
] | stackoverflow_0000023397_fork_process_python_subprocess_windows.txt |
Q:
Django Ldap Connection Setup
I am trying to setup a LDAP connection in Django. Does anyone have any sample code? I need to know what information I need to place inside of the settings.py.
I keep getting the following error message:
AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance.
A:
Are you using a specifi... | Django Ldap Connection Setup | I am trying to setup a LDAP connection in Django. Does anyone have any sample code? I need to know what information I need to place inside of the settings.py.
I keep getting the following error message:
AUTH_LDAP_USER_SEARCH must be an LDAPSearch instance.
| [
"Are you using a specific backend? \nAssuming you are using django-auth-ldap the docs are quite detailed.\n"
] | [
0
] | [] | [] | [
"django",
"ldap",
"ldapconnection",
"python"
] | stackoverflow_0006020334_django_ldap_ldapconnection_python.txt |
Q:
How to update a model
Assume I have a model definition like this:
class Image(db.Model):
id = db.StringProperty()
url = db.URLProperty()
Now I want to add some fields to this model to make it look like this:
class Image(db.Model):
id = db.StringProperty()
url = db.URLProperty()
width = db.Inte... | How to update a model | Assume I have a model definition like this:
class Image(db.Model):
id = db.StringProperty()
url = db.URLProperty()
Now I want to add some fields to this model to make it look like this:
class Image(db.Model):
id = db.StringProperty()
url = db.URLProperty()
width = db.IntegerProperty()
height = ... | [
"This exact scenario is covered in the GAE docs (articles section):\nUpdating your model's schema.\nBasically just change the model definition as you've done, then perform some operation to supply default values for all your extant entities. There are several ways to do the second part - the article describes one. ... | [
3,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006014501_google_app_engine_python.txt |
Q:
Python: Dictionary as instance variable
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm very confused about the behavior of dictionaries as class instance variables in Python 3. The way I understand it, instance variables in Python have per-instance storage, unlike class var... | Python: Dictionary as instance variable |
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm very confused about the behavior of dictionaries as class instance variables in Python 3. The way I understand it, instance variables in Python have per-instance storage, unlike class variables which are per-class (similar to what ... | [
"This is a well known surprise in Python. The default parameters are evaluated when the function is defined, not when it is called. So your default parameter is a reference to a common dict. It has nothing to do with assigning it to class/instance variables.\nIf you want to use a default parameter, use None, and ch... | [
18,
3
] | [] | [] | [
"class",
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0006020960_class_dictionary_python_python_3.x.txt |
Q:
BeautifulSoup print multiple tag / attr
First off all, this is my first try on Python, so far it looks pretty easy to use, though I still ran into a problem..
I am trying to change an XML-file to an rss-XML
The original xml source looks like this:
<news title="Random Title" date="Date and Time" subtitle="The arti... | BeautifulSoup print multiple tag / attr | First off all, this is my first try on Python, so far it looks pretty easy to use, though I still ran into a problem..
I am trying to change an XML-file to an rss-XML
The original xml source looks like this:
<news title="Random Title" date="Date and Time" subtitle="The article txt"></news>
It shoold eventually look l... | [
"Your example doc variable only holds one <news> element.\nbut in general you would need to loop through the news elements\nsomething like\nfor news in soup.findAll('news'):\n posttitle = news['post_title']\n postdate = news['post_date']\n postcontent = news['post_content']\n print \"<item>\"\n print... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"python",
"xml",
"xml_parsing"
] | stackoverflow_0006020863_beautifulsoup_python_xml_xml_parsing.txt |
Q:
importing javax packages into python
I have (what I hope is) a very simple question.
I would like to use some javax.crypto classes from within a python script, so be able to do something like:
from javax.crypto import Cipher
cipher = Cipher.getInstance('AES/CTR/NoPadding')
But I am not familiar with how to do th... | importing javax packages into python | I have (what I hope is) a very simple question.
I would like to use some javax.crypto classes from within a python script, so be able to do something like:
from javax.crypto import Cipher
cipher = Cipher.getInstance('AES/CTR/NoPadding')
But I am not familiar with how to do this get python to be able to recognise java... | [
"It's very completely wrong. Python and Java are separate languages, and CPython, the implementation you're using, has its own VM. Use Jython if you want to bridge the two.\n",
"Under jython you use the syntax you describe. Basic types(strings, ints, floats) are converted automatically by jython when going from ... | [
2,
1
] | [] | [] | [
"java",
"linux",
"python"
] | stackoverflow_0006021047_java_linux_python.txt |
Q:
I how to intersect a range of columns between two horizontal list?
At the code I'm writing I need to intersect two horizontal list like:
listA:
('name1','chr1', 'aatt')
('name2','chr11', 'aaga')
('name2','chr11', 'aaaa')
('name3','chr7', 'gtag')
listB
('chr8', 'tagt')
('chr1', 'tttt')
('chr7', 'gtag')
('chr11','a... | I how to intersect a range of columns between two horizontal list? | At the code I'm writing I need to intersect two horizontal list like:
listA:
('name1','chr1', 'aatt')
('name2','chr11', 'aaga')
('name2','chr11', 'aaaa')
('name3','chr7', 'gtag')
listB
('chr8', 'tagt')
('chr1', 'tttt')
('chr7', 'gtag')
('chr11','aaaa')
('chr9', 'atat')
#This lists are compounded by one str per line, ... | [
"set_b = set(list_b)\nresult = [x for x in list_a if (x[1], x[2]) in set_b]\n\n"
] | [
3
] | [] | [] | [
"intersection",
"list",
"python"
] | stackoverflow_0006021378_intersection_list_python.txt |
Q:
Questions on "Python Is Not Java"
I'm a novice programmer with basic Java experience, and currently learning Python.
I've stumbled across this blog post in another question thread:
http://dirtsimple.org/2004/12/python-is-not-java.html
and I've got a couple of questions regarding the topic posted:
1) "Oh, and all ... | Questions on "Python Is Not Java" | I'm a novice programmer with basic Java experience, and currently learning Python.
I've stumbled across this blog post in another question thread:
http://dirtsimple.org/2004/12/python-is-not-java.html
and I've got a couple of questions regarding the topic posted:
1) "Oh, and all those Foo.Bar.Baz attribute chains don... | [
"\nIt rarely matters. If it does, you'd be better off writing C (or letting Cython do that for you, with static type annotations to make it really count), using PyPy (their JIT can completely remove such lookups and many more things, even memory allocations, in certain loops), etc.\n\"lambda\" is in a different cat... | [
8,
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0006021091_python.txt |
Q:
Python Numpy.ndarray.shape limit
I want to create a matrix with Numpy in Python with the following code:
import numpy
result=numpy.zeros((20,20,20,30,30,30))
numpy.save('result',result)
I get the following error:
Traceback (most recent call last):
File "numpy_memoryerror.py",
line 5, in <module>
result=nu... | Python Numpy.ndarray.shape limit | I want to create a matrix with Numpy in Python with the following code:
import numpy
result=numpy.zeros((20,20,20,30,30,30))
numpy.save('result',result)
I get the following error:
Traceback (most recent call last):
File "numpy_memoryerror.py",
line 5, in <module>
result=numpy.zeros((20,20,20,30,30,30))
MemoryE... | [
"Its not a fundamental limit of the shape tuple, its that you don't have enough memory (RAM) on your system, hence the MemoryError.\nAgain 20*20*20*30*30*30 is 216 million 64-bit (8 byte) floats or a little more than 1.6 GB of RAM. So do you have 1.6 GB of RAM free while running the script at that point? (Don't f... | [
6
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006021728_numpy_python.txt |
Q:
openssl_csr_get_public_key in Python
Can anybody suggest any python *ssl rsa library* , which has a function like in PHP (openssl_csr_get_public_key).
Because i have a certificate , with which i need to verify the data . And every time i try to use this certificate with M2Crypto public key functiton , it gives er... | openssl_csr_get_public_key in Python | Can anybody suggest any python *ssl rsa library* , which has a function like in PHP (openssl_csr_get_public_key).
Because i have a certificate , with which i need to verify the data . And every time i try to use this certificate with M2Crypto public key functiton , it gives error "no start line " , which is completely... | [
"I think what you want is M2Crypto.X509.load_cert(), and then getting the public key from the certificate object using cert.get_pubkey().\n"
] | [
0
] | [] | [] | [
"certificate",
"python",
"rsa",
"ssl"
] | stackoverflow_0006021837_certificate_python_rsa_ssl.txt |
Q:
How do I set remote server TimeZone via Fabric?
I'm trying to change my remote server's timezone via Fabric like so:
run("export TZ=\":Pacific/Auckland\"")
run("date")
This doesn't seem to work. run("date") gives me:
Tue Apr 19 00:19:58 CDT 2011 which is not the timezone I just set.
If I just log into the server... | How do I set remote server TimeZone via Fabric? | I'm trying to change my remote server's timezone via Fabric like so:
run("export TZ=\":Pacific/Auckland\"")
run("date")
This doesn't seem to work. run("date") gives me:
Tue Apr 19 00:19:58 CDT 2011 which is not the timezone I just set.
If I just log into the server and run the same bash commands, everything's just as... | [
"run(\"export TZ=\\\":Pacific/Auckland\\\"\")\nrun(\"date\")\n\nis like\n/bin/sh -c 'export TZ=\":Pacific/Auckland\"'\n/bin/sh -c 'date'\n\nYou're launching a shell, setting one of its environment variables, then exiting it. It never had a chance to pass that environment var to anyone.\nSet TZ in your script's envi... | [
4,
2,
1
] | [] | [] | [
"bash",
"fabric",
"python"
] | stackoverflow_0005712062_bash_fabric_python.txt |
Q:
Problem: How to read a minimum value in the list consisting of objects?
How can I read the minimum value of "price" parameter in the "room_options" list, with n elements of the list. Each list item is an instance of Room class:
room_options: (list)
[0] Room
[1] Room
[2] Room
[3] Room
...
[n] Room... | Problem: How to read a minimum value in the list consisting of objects? | How can I read the minimum value of "price" parameter in the "room_options" list, with n elements of the list. Each list item is an instance of Room class:
room_options: (list)
[0] Room
[1] Room
[2] Room
[3] Room
...
[n] Room
Room:
price=700
currency="PLN"
type="Twin Room"
dining=True
I'... | [
"min(room_options, key=lambda x: x.price)\n",
"min(room.price for room in rooms)\n\nEDIT: see comment\n"
] | [
3,
0
] | [] | [] | [
"iteration",
"min",
"python"
] | stackoverflow_0006022015_iteration_min_python.txt |
Q:
Convert Python2.6 to Google App Engine compatible (multiprocessing)
I've made a little script in Python which uses multiprocessing. I've thought of running it on the Google App Engine as a cron-job, but unfortunately Google App Engine doesn't support multiprocessing. Can anyone help me convert this into Google App... | Convert Python2.6 to Google App Engine compatible (multiprocessing) | I've made a little script in Python which uses multiprocessing. I've thought of running it on the Google App Engine as a cron-job, but unfortunately Google App Engine doesn't support multiprocessing. Can anyone help me convert this into Google App Engine compatible code (perhaps using Google App Engine tasks?)?
from mu... | [
"Take a look at Task Queues.\nca can insert an amount of work into a task Queue (=> Thread) and set the number of jobs in a queue which are executed simultaniously.\nTake a look here: http://code.google.com/intl/de-DE/appengine/docs/python/taskqueue/\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"multiprocessing",
"python"
] | stackoverflow_0006021670_google_app_engine_multiprocessing_python.txt |
Q:
Purging numpy.memmap
Given a numpy.memmap object created with mode='r' (i.e. read-only), is there a way to force it to purge all loaded pages out of physical RAM, without deleting the object itself?
In other words, I'd like the reference to the memmap instance to remain valid, but all physical memory that's being ... | Purging numpy.memmap | Given a numpy.memmap object created with mode='r' (i.e. read-only), is there a way to force it to purge all loaded pages out of physical RAM, without deleting the object itself?
In other words, I'd like the reference to the memmap instance to remain valid, but all physical memory that's being used to cache the on-disk ... | [
"If you run \"pmap SCRIPT-PID\", the \"real\" memory shows as \"[ anon ]\" blocks, and all memory-mapped files show up with the file name in the last column.\nPurging the pages is possible at C level, if you manage to get ahold of the pointer to the beginning of the mapping and call madvise(ptr, length, MADV_DONTNE... | [
2
] | [] | [] | [
"large_data",
"memory_mapped_files",
"mmap",
"numpy",
"python"
] | stackoverflow_0006021550_large_data_memory_mapped_files_mmap_numpy_python.txt |
Q:
Custom Templates/Forms for Django Comments
How would I make my own custom templates/forms for the built in Django Comments Framework?
A:
If you just want to override (specific) templates put them in templates/comments (a technique not only valid for contrib.comments but for all reusable apps including Django's a... | Custom Templates/Forms for Django Comments | How would I make my own custom templates/forms for the built in Django Comments Framework?
| [
"If you just want to override (specific) templates put them in templates/comments (a technique not only valid for contrib.comments but for all reusable apps including Django's admin.).\nIf you want to edit the builtin forms you have to extend contrib.comments as mentioned and explained in the docs.\n"
] | [
1
] | [] | [] | [
"comments",
"django",
"forms",
"python",
"templates"
] | stackoverflow_0006021982_comments_django_forms_python_templates.txt |
Q:
API design Python
I have found a very nice talk by Joshua Bloch:
http://www.youtube.com/watch?v=aAb7hSCtvGw
http://lcsd05.cs.tamu.edu/slides/keynote.pdf
While it is fairly general, some comments are only valid to statically typed languages. I am looking for something equivalent for Python.
(This talk looks promisi... | API design Python | I have found a very nice talk by Joshua Bloch:
http://www.youtube.com/watch?v=aAb7hSCtvGw
http://lcsd05.cs.tamu.edu/slides/keynote.pdf
While it is fairly general, some comments are only valid to statically typed languages. I am looking for something equivalent for Python.
(This talk looks promising but has not been giv... | [
"Perhaps one of these (or both).\n\nPyCon 2011: API Design: Lessons Learned by Hettinger\nPyCon 2011: API Design anti-patterns by Alex Martelli\n\n"
] | [
21
] | [] | [] | [
"api",
"python"
] | stackoverflow_0006022074_api_python.txt |
Q:
Advice: where to situate html table content: in JS or HTML
SHORT: my python code generates a webpage with a table. i'm considering rewriting it to generate a js file instead, that holds the table contents in an array ... and then let the table be generated client-side. I am not sure of the pros and cons. Anyone ... | Advice: where to situate html table content: in JS or HTML | SHORT: my python code generates a webpage with a table. i'm considering rewriting it to generate a js file instead, that holds the table contents in an array ... and then let the table be generated client-side. I am not sure of the pros and cons. Anyone care to offer their experience/insight? Are there other solutio... | [
"If your API can output a JSON document with your data, you gain significant flexibility and future-proofing. This might even be something your users will want to access directly for their own external consumption. And of course your JS code can easily generate a table from this data.\nHowever nobody here can tel... | [
4
] | [] | [] | [
"dhtml",
"html",
"javascript",
"python"
] | stackoverflow_0006022119_dhtml_html_javascript_python.txt |
Q:
Separating Axis Theorem and Python
This is what I am currently doing:
Creating 4 axis that are perpendicular to 4 edges of 2 rectangles. Since they are rectangles I do not need to generate an axis (normal) per edge.
I then loop over my 4 axes.
So for each axis:
I get the projection of every corner of a rectangl... | Separating Axis Theorem and Python | This is what I am currently doing:
Creating 4 axis that are perpendicular to 4 edges of 2 rectangles. Since they are rectangles I do not need to generate an axis (normal) per edge.
I then loop over my 4 axes.
So for each axis:
I get the projection of every corner of a rectangle on to the axis.
There are 2 lists (ar... | [
"In general it is necessary to carry out the steps outlined in the Question to determine if the rectangles \"collide\" (intersect), noting as the OP does that we can break (with a conclusion of non-intersection) as soon as a separating axis is found.\nThere are a couple of simple ways to \"optimize\" in the sense o... | [
5,
3
] | [] | [] | [
"math",
"physics",
"pygame",
"python"
] | stackoverflow_0006013333_math_physics_pygame_python.txt |
Q:
get selected text in an other application
I want to have a python script, which will "idle" until some text is selected in an other desktop app, and then store it in a var. Eg:
User goes into Safari
User selects a block of text
In the background, the python script will store that block of text in a var
Now that t... | get selected text in an other application | I want to have a python script, which will "idle" until some text is selected in an other desktop app, and then store it in a var. Eg:
User goes into Safari
User selects a block of text
In the background, the python script will store that block of text in a var
Now that the python script has it's var, it can stop "idl... | [
"You might want to consider using AppleScript rather than python and have the AppleScript pass the information along to the python if needed.\n",
"Doing what you want would be hard to do properly, assuming it's possible at all.\nFor example, without requiring the user to press a key (eg: Cmd+C, Ctrl+C, etc) how ... | [
1,
0
] | [] | [] | [
"clipboard",
"python",
"selection"
] | stackoverflow_0006021174_clipboard_python_selection.txt |
Q:
Explicit line joining in Python
I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:
file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''
for line in scanlines:
if line.startswith('>from... | Explicit line joining in Python | I am reading a file, line-by-line and doing some text processing in order to get output in a certain format
My string processing code goes as follows:
file1=open('/myfolder/testfile.txt')
scanlines=file1.readlines()
string = ''
for line in scanlines:
if line.startswith('>from'):
continue
if line.sta... | [
"there are several ways to do this. for example just using + should do the trick.\n\"abc\" + \"def\" # produces \"abcdef\"\nIf you try to concatenate multiple strings you can do this with the join method:\n', '.join(('abc', 'def', 'ghi')) # produces 'abc, def, ghi'\n\nIf you want no delimiter, use the empty string ... | [
5,
3,
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006022088_python_string.txt |
Q:
wxMessageBox with an auto-close timer in wxPython
Platforms: Windows, OS X
Python Version: Active State Python 2.7
wxPython Version: Version 2.9
Here is a sample code in which I use a wxMessageBox:
import wx,os
class Frame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, paren... | wxMessageBox with an auto-close timer in wxPython | Platforms: Windows, OS X
Python Version: Active State Python 2.7
wxPython Version: Version 2.9
Here is a sample code in which I use a wxMessageBox:
import wx,os
class Frame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(100, 100),style=wx.MINIMIZE_BOX | w... | [
"If you create your own custom dialog by subclassing wx.Dialog you can use a wx.Timer to generate a periodic event to which you can bind a handler which updates the message every time the timer event fires, then after x event fires you can destroy the dialog.\nWorking example:\nimport wx\nimport os\n\nclass Message... | [
7,
4
] | [] | [] | [
"auto_close",
"python",
"wxpython"
] | stackoverflow_0006012380_auto_close_python_wxpython.txt |
Q:
Get current working directory from Vte (GTK Terminal Widget) in Python
Hey,
How can I get the current working directory of a VTE widget in Python?
Thanks.
A:
Borrowing from Mark, a slightly more elegant approach:
import vte
import os
v = vte.Terminal()
vPid = v.fork_command()
workingDir = os.readlink('/proc/%s/c... | Get current working directory from Vte (GTK Terminal Widget) in Python | Hey,
How can I get the current working directory of a VTE widget in Python?
Thanks.
| [
"Borrowing from Mark, a slightly more elegant approach:\nimport vte\nimport os\nv = vte.Terminal()\nvPid = v.fork_command()\nworkingDir = os.readlink('/proc/%s/cwd' % vPid)\n\n",
"This is a kludge, but the best way I can think of would be:\nimport vte\nimport os\nv = vte.Terminal()\nvPid = v.fork_command()\n# mak... | [
3,
1
] | [] | [] | [
"gtk",
"pygtk",
"python",
"vte"
] | stackoverflow_0006016219_gtk_pygtk_python_vte.txt |
Q:
How to get back a signed string (e.g. md5 hash) using a public-key (x509 certificate)
I'm very new with cryptographic and stuck for 2 days with this problem, I hope you can help me with.
I try to sign a md5 digest string with the private key of a X509 certificate. As far as I can see, this works fine.
Now I try to... | How to get back a signed string (e.g. md5 hash) using a public-key (x509 certificate) | I'm very new with cryptographic and stuck for 2 days with this problem, I hope you can help me with.
I try to sign a md5 digest string with the private key of a X509 certificate. As far as I can see, this works fine.
Now I try to get back that string using the public key of that x509 certificate, but I have no idea how... | [
"Technically, you are not supposed to \"decrypt\" the signature. If you really want to decrypt it, do something like this:\ncert = X509.load_cert(\"signer.pem\")\ndecrypted = cert.get_pubkey().get_rsa().public_decrypt(StringSignature, 1)\n\nbut this will not give you what you are expecting, I guess.\nIf you want to... | [
0
] | [] | [] | [
"m2crypto",
"python"
] | stackoverflow_0006020920_m2crypto_python.txt |
Q:
TypeError: expected string when using re.findall on web page text -- why?
I'm trying to learn how to screen-scrape with BeautifulSoup.
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re
webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()
patFinderTitle = re.compile('<h4 c... | TypeError: expected string when using re.findall on web page text -- why? | I'm trying to learn how to screen-scrape with BeautifulSoup.
from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import re
webpage = urlopen('http://feeds.feedburner.com/zenhabits').read()
patFinderTitle = re.compile('<h4 class="itemtitle"><a href=(.*)</a></h4>')
findPatTitle = re.findall(patFinderTi... | [
"Use the following expression:\npatFinderTitle.findall(webpage)\n\nYou can't do the equivalent of re.findall(re.compile(<expression>), <string>) since re.findall only accepts a regular expression as a string -- and re.compile(<expression>) returns a compiled regex object. So you need to use your compiled regex obje... | [
3,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006023160_python_regex.txt |
Q:
Stream lots of screenshots from server
Let's say I have this tool that takes a screenshot of the user's desktop every 10 seconds and uploads the images to a server. Images are deleted from the server after 24 hours. I want to allow the user to view these screenshots in their browser. So let's say each image is ... | Stream lots of screenshots from server | Let's say I have this tool that takes a screenshot of the user's desktop every 10 seconds and uploads the images to a server. Images are deleted from the server after 24 hours. I want to allow the user to view these screenshots in their browser. So let's say each image is 300K and there are 5000 of them uploaded in ... | [
"The quick & easy solution is to\n\ntile up the screen along a fixed grid\nstore the tiles separately, indexed by a strong hash (to eliminate duplicates, even between users)\nstore the entire screen as a 2-d array of tile hashes\nreconstruct the original screen in the browser from the hashed tiles.\n\nGoing from on... | [
5,
1
] | [] | [] | [
"image",
"python",
"streaming",
"video"
] | stackoverflow_0006023173_image_python_streaming_video.txt |
Q:
Running CPython functions from C#
I'm working on a project where I need to be able to run a python function that depends on SciPy/NumPy. Due to this being an add-on to a project already in progress, using IronPython would not be an option.
Additional info:
Python.NET seemed to be a good fit, but I was unable to ... | Running CPython functions from C# | I'm working on a project where I need to be able to run a python function that depends on SciPy/NumPy. Due to this being an add-on to a project already in progress, using IronPython would not be an option.
Additional info:
Python.NET seemed to be a good fit, but I was unable to get the return value from RunString() (... | [
"I guess you could write a DLL that uses the CPython API to expose the function, then call it in C#?\nIt's possible to embed the Python interpreter; although I've never done this personally, I guess it would be useful: http://docs.python.org/extending/embedding.html\n",
"Does it need to be portable beyond Windows... | [
2,
1,
1,
0
] | [] | [] | [
".net",
"c#",
"python"
] | stackoverflow_0006021625_.net_c#_python.txt |
Q:
Python equivalent of PHP's @
Is there a Python equivalent of PHP's @?
@function_which_is_doomed_to_fail();
I've always used this block:
try:
foo()
except:
pass
But I know there has to be a better way.
Does anyone know how I can Pythonicify that code?
I think adding some context to that code would be appropr... | Python equivalent of PHP's @ | Is there a Python equivalent of PHP's @?
@function_which_is_doomed_to_fail();
I've always used this block:
try:
foo()
except:
pass
But I know there has to be a better way.
Does anyone know how I can Pythonicify that code?
I think adding some context to that code would be appropriate:
for line in blkid:
line = ... | [
"What you are looking for is anti-pythonic, because:\n\nThe Zen of Python, by Tim Peters\n Beautiful is better than ugly.\nExplicit is better than implicit.\n Simple is better than complex.\n Complex is better than complicated.\n Flat is better than nested.\n Sparse is better than dense.\n Readability counts.... | [
5,
2,
1,
1,
1,
0
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0006006645_exception_handling_python.txt |
Q:
How to proportionally (respecting aspect ratio) scale a rectangle?
I'm trying to simply take a given box of x by y and scale it up, either by setting x and finding y, or vice versa. How would this formula be expressed in Python (for readability's sake). I'm trying to fit this box inside of a larger box so that the... | How to proportionally (respecting aspect ratio) scale a rectangle? | I'm trying to simply take a given box of x by y and scale it up, either by setting x and finding y, or vice versa. How would this formula be expressed in Python (for readability's sake). I'm trying to fit this box inside of a larger box so that the inner box always fits within the larger box.
| [
"new_y = (float(new_x) / x) * y\nor\nnew_x = (float(new_y) / y) * x\n",
"NB: I don't really do Python, so this is pseudocode.\nWhat you need is the relative aspect ratios of the two boxes, since that determines which of the new axes must be the same size as the new box:\nr_old = old_w / old_h\nr_new = new_w / new... | [
6,
6,
0
] | [] | [] | [
"aspect_ratio",
"math",
"python"
] | stackoverflow_0006023488_aspect_ratio_math_python.txt |
Q:
how to edit model data using django forms
i'm new to django so i'm sorry for my newbie question
i have a model and i need to let user edit data inside it using django forms or any other way.
look at the image above , i want to show this form ready populated with the data and let user update it.
what is the bes... | how to edit model data using django forms | i'm new to django so i'm sorry for my newbie question
i have a model and i need to let user edit data inside it using django forms or any other way.
look at the image above , i want to show this form ready populated with the data and let user update it.
what is the best way to do this ?
EDIT : here is my views.py ... | [
"Assuming you are using a ModelForm, use the instance keyword argument, and pass the model you are updating.\nSo, if you have MyModel and MyModelForm (the latter of which must extend django.forms.ModelForm), then your code snippet might look like:\nmy_record = MyModel.objects.get(id=XXX)\nform = MyModelForm(instanc... | [
64
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006023421_django_django_forms_python.txt |
Q:
py.test use monkeypatch in custom funcargs
I use py.test and really like the funcarg approach to inject objects into test functions.
In my testing I need to work with Mock objects, as I have a lot external dependencies. I use monkeypatch to replace certain attributes with the mock objects.
The problem I have is,... | py.test use monkeypatch in custom funcargs | I use py.test and really like the funcarg approach to inject objects into test functions.
In my testing I need to work with Mock objects, as I have a lot external dependencies. I use monkeypatch to replace certain attributes with the mock objects.
The problem I have is, that I will often end up with a bunch of tests ... | [
"You can use the documented getfuncargvalue function to internally use a function argument from another function argument's factory:\ndef pytest_funcarg__api(request):\n api = myclass()\n #do some initialisation...\n mp = request.getfuncargvalue(\"monkeypatch\")\n mp.setattr(api,\"get_external_stuff\", ... | [
5,
2
] | [] | [] | [
"pytest",
"python",
"unit_testing"
] | stackoverflow_0006018040_pytest_python_unit_testing.txt |
Q:
django mutlipleChoiceField how to validate?
i have the form below :
forms.py :
class enrolForm(forms.Form):
CHOICES = [('male','male'),('female','female')]
students = forms.MultipleChoiceField(choices = CHOICES)
views.py :
form = enrolForm(request.POST)
if form.is_valid():
print "creating st... | django mutlipleChoiceField how to validate? | i have the form below :
forms.py :
class enrolForm(forms.Form):
CHOICES = [('male','male'),('female','female')]
students = forms.MultipleChoiceField(choices = CHOICES)
views.py :
form = enrolForm(request.POST)
if form.is_valid():
print "creating student"
exam = models.Exam.objects.get... | [
"What's wrong with using a standard ChoiceField?\nclass enrolForm(forms.Form):\n CHOICES = [('male','male'),('female','female')]\n students = forms.ChoiceField(choices = CHOICES)\n\nAlso doing this to view the errors and letting us know would be helpful:\nif form.is_valid():\n print \"creating student\"\n ... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0006023109_django_django_forms_python.txt |
Q:
Passing shellcode from Python as command line argument
I am currently preparing a small presentation about computer security among my fellow students. To get them at least a bit excited I wanted to demonstrate how the wrong use of the strcpy-function inc C can be exploited.
This is the code of the vulnerable progr... | Passing shellcode from Python as command line argument | I am currently preparing a small presentation about computer security among my fellow students. To get them at least a bit excited I wanted to demonstrate how the wrong use of the strcpy-function inc C can be exploited.
This is the code of the vulnerable program:
#include<string.h>
#include<stdio.h>
void function(char ... | [
"It looks like your text is undergoing UTF-8 conversion. Note that your original bytes:\n75 9a 21 1b\n ^^\n\nare replaced by\n75 c2 9a 21 1b\n ^^^^^\n\nI've highlighted the UTF-8 encoded byte. If you're using Python 3, try:\nos.system(b\"test.exe ABCDEFGHI\\x75\\x9a\\x21\\x1bNOPQRSTUVWXYZ\")\n\nThe b\"\" indica... | [
1
] | [] | [] | [
"buffer_overflow",
"python",
"utf_8"
] | stackoverflow_0006023731_buffer_overflow_python_utf_8.txt |
Q:
How to search for specific text from a website, retrieve and use it with google app engine (python)?
I'm trying to retrieve basically this block of text from www.crossfit.com.
Monday 110516
Complete as many rounds as possible in five minutes of:
275 pound Deadlift, 3 reps
115 pound Push press, 7 reps
It's basica... | How to search for specific text from a website, retrieve and use it with google app engine (python)? | I'm trying to retrieve basically this block of text from www.crossfit.com.
Monday 110516
Complete as many rounds as possible in five minutes of:
275 pound Deadlift, 3 reps
115 pound Push press, 7 reps
It's basically just the date (Monday yymmdd), and a short description of a workout. The site updates daily with a new... | [
"Instead of parsing the HTML yourself, use the already provided XML feed: http://www.crossfit.com/index.xml.\nYou can parse the XML feed in python 2.5 with xml.etree.ElementTree.\n"
] | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0006023846_google_app_engine_python.txt |
Q:
file renaming/deleting
I have a few files like this-
*.sss and *_passive.sss
If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.
I was able to locate all the ... | file renaming/deleting | I have a few files like this-
*.sss and *_passive.sss
If I have a file called blah1.sss and blah1_passive.sss, i want to get rid of blah1.sss and rename blah1_passive.sss. However, if I don't have blah1_passive.sss I want to log the filename and keep blah1.sss.
I was able to locate all the *_passive.sss files but I wo... | [
"In Unix you can use the following command in a Bourne shell (i.e. sh/bash):\nfor f in *_passive.sss; do mv -v $f `basename $f _passive.sss`.sss; done\n\n",
"This shell script shoul do the trick:\nwhile read f; do\n fp=\"`echo \"$f\" | sed -nr 's|(.*)(\\.sss)|\\1_passive\\2| p'`\"\n if [ -f \"$fp\" ]; then ... | [
5,
1,
1
] | [] | [] | [
"python",
"unix"
] | stackoverflow_0006023581_python_unix.txt |
Q:
Pipe text to Python script or prompt
I'm trying to write a very simple email script in python. It's basically a poor man's mutt. At work, we send a lot of data from servers around, and it would be much easier to send it directly from the server.
The part that I'm stuck on is dealing with the message. I want users... | Pipe text to Python script or prompt | I'm trying to write a very simple email script in python. It's basically a poor man's mutt. At work, we send a lot of data from servers around, and it would be much easier to send it directly from the server.
The part that I'm stuck on is dealing with the message. I want users to to be able to do the following:
$ cat ... | [
"You can use sys.stdin.isatty to check if the script is being run interactively. Example:\nif sys.stdin.isatty():\n message = raw_input('Enter your message ')\nelse:\n message = sys.stdin.read()\n\n"
] | [
18
] | [] | [] | [
"bash",
"python"
] | stackoverflow_0006024149_bash_python.txt |
Q:
How to print file contents with filename before each line?
I have several files, say, a,b,c, I would like to something like
> cat a b c
but with "a," in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:
#!/bin/env python
f... | How to print file contents with filename before each line? | I have several files, say, a,b,c, I would like to something like
> cat a b c
but with "a," in the beginning lines of a. "b," in the beginning of the lines of b and "c," in the beginning of the lines of c.
I can do this using python:
#!/bin/env python
files = 'a b c'
all_lines = []
for f in files.split():
lines =... | [
"perl -pe 'print \"$ARGV,\"' a b c\n\nwill do it.\n",
"grep(1) and sed(1)can do this for you: grep -H '' <files> | sed 's/:/,/':\n$ cat a ; cat b ; cat c\nhello\n\n\nworld\nfrom space\n$ grep -H '' * | sed 's/:/,/'\na,hello\nb,\nb,\nb,world\nc,from space\n\n",
"You can also use the awk(1) program :)\n$ awk 'BEG... | [
8,
5,
4
] | [] | [] | [
"bash",
"perl",
"python",
"scripting",
"sed"
] | stackoverflow_0006024116_bash_perl_python_scripting_sed.txt |
Q:
IDE for Python: test a script
Is there any IDE that allows to run a script in testing mode, allowing to replace at runtime, some values, like a folder or else?
I have a program that will have to run on a network i have no access to where I develop. Since it will use some specific folders to pick up files, I was wo... | IDE for Python: test a script | Is there any IDE that allows to run a script in testing mode, allowing to replace at runtime, some values, like a folder or else?
I have a program that will have to run on a network i have no access to where I develop. Since it will use some specific folders to pick up files, I was wondering if i.e. I could use an IDE ... | [
"In absence of some other file based config, you could just keep the variable definitions in a a file that you import in the main script (e.g, config.py), then have two different versions of that file for 'on' and 'off' network, (or ' development' and 'production', whatever) with the appropriate settings. No IDE n... | [
3
] | [] | [] | [
"ide",
"python"
] | stackoverflow_0006023377_ide_python.txt |
Q:
argv listing directory files
this very simple code is driving me nuts.
import sys,string,socket
maquina = sys.argv[1]
texto = string.join(sys.argv[2:], " ")
print '['+maquina+']'
print '['+texto+']'
mysock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
if maquina == '*':
for ip in range(18,254):
... | argv listing directory files | this very simple code is driving me nuts.
import sys,string,socket
maquina = sys.argv[1]
texto = string.join(sys.argv[2:], " ")
print '['+maquina+']'
print '['+texto+']'
mysock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
if maquina == '*':
for ip in range(18,254):
mysock.sendto( texto, ('192.... | [
"Try using '*' instead of *. Your shell feeds results of * to the program via cmdline args, just like ls *.\n",
"Another way to get file names is using the glob module:\n>>> from glob import glob\n>>> glob('*')\n['file1.txt', 'file2.py', 'file3', ... ]\n\nIt work just like the ls command.\n"
] | [
10,
1
] | [] | [] | [
"python"
] | stackoverflow_0006024233_python.txt |
Q:
RSS aggregation packages
We are looking to add a news/articles section to an existing site which will be powered by aggregating content via RSS feeds. The requirements are
Be able to aggregate lots of feeds. Initially we will start with small number of and eventually we may be aggregating few hundreds of them.
We... | RSS aggregation packages | We are looking to add a news/articles section to an existing site which will be powered by aggregating content via RSS feeds. The requirements are
Be able to aggregate lots of feeds. Initially we will start with small number of and eventually we may be aggregating few hundreds of them.
We don't want to display the who... | [
"If you have a good idea of what you want, why not just try them all? If you have pretty strict requirements, write it yourself, roll your own aggregator with feedparser.\n"
] | [
0
] | [] | [] | [
"aggregate",
"django",
"feed",
"python",
"rss"
] | stackoverflow_0006024340_aggregate_django_feed_python_rss.txt |
Q:
Cache anonymous HTTP requests (based on cookies)
I would like to add a HTTP (or WSGI) cache to my Python web application, for all requests which
are either GET or HEAD
do not have a cookie called "session_id" (known users get specialized, non-cacheable pages)
do not have a cookie called "_flash" (this cookie is u... | Cache anonymous HTTP requests (based on cookies) | I would like to add a HTTP (or WSGI) cache to my Python web application, for all requests which
are either GET or HEAD
do not have a cookie called "session_id" (known users get specialized, non-cacheable pages)
do not have a cookie called "_flash" (this cookie is used to show the user some short messages like "article... | [
"I'd recommend checking out varnish. It's going to be a lot faster than any WSGI-Middleware you write/find, and you should be able to do everything you want with it. Here's the tutorial for a taste of it's many features, options: http://www.varnish-cache.org/docs/trunk/tutorial/index.html\n"
] | [
1
] | [] | [] | [
"caching",
"http",
"mod_cache",
"python",
"squid"
] | stackoverflow_0006023278_caching_http_mod_cache_python_squid.txt |
Q:
matplotlib figures disappearing between show() and savefig()
I've kept a set of references to figures in a dictionary so that I could save them later if desired. I am troubled that the saved figures are blank if invoke a show() command and look at them first. Since the show() command blocks and I am not using a ... | matplotlib figures disappearing between show() and savefig() | I've kept a set of references to figures in a dictionary so that I could save them later if desired. I am troubled that the saved figures are blank if invoke a show() command and look at them first. Since the show() command blocks and I am not using a spyder-like interpreter, I have to close the figures before I get ... | [
"Generally speaking, in cases like this don't use the interactive matlab-ish state machine interface to matplotlib. It's meant for interactive use. \nYou're trying to make a figure \"active\", and creating a new figure instead. It doesn't matter which figure is active, if you just retain the returned figure and/or... | [
7,
2
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006019776_matplotlib_python.txt |
Q:
South ignores change in field default value in Python / Django
Why does South not recognize changes in default field values in Python models? For example, take this existing model that is migrated with south:
class MyFamily(models.Model):
family_size = models.IntegerField(verbose_name="What is your family siz... | South ignores change in field default value in Python / Django | Why does South not recognize changes in default field values in Python models? For example, take this existing model that is migrated with south:
class MyFamily(models.Model):
family_size = models.IntegerField(verbose_name="What is your family size?", default=2)
Now, I'd like to change the default value from two ... | [
"South won't update the default value for existing columns, because it matters for him only when adding a new column to a non empty table. The django orm will handle writing the new default value to new rows before hitting the database.\nIf you will work on the database from outside django orm, you have to update i... | [
11
] | [] | [] | [
"django",
"django_south",
"python"
] | stackoverflow_0006024724_django_django_south_python.txt |
Q:
Python object persistence over re-execs
Is where a way to persist objects over re-execs of a running script? If I want a running script to re execute itself to pick up any code changes, (os.exec*) is there a way to persist the objects for access after the re-execution? I could set environment variables with pick... | Python object persistence over re-execs | Is where a way to persist objects over re-execs of a running script? If I want a running script to re execute itself to pick up any code changes, (os.exec*) is there a way to persist the objects for access after the re-execution? I could set environment variables with pickled ascii data, or write that data to a pipe ... | [
"If you put your code in a module, you can use the reload() standard function to load the new version of the code. Your main module could look like this:\nimport mymodule\n\nwhile mymodule.go():\n reload(mymodule)\n\nWhenever you want to reload your module code, return True from go(). When you want to exit, retu... | [
3,
1
] | [] | [] | [
"exec",
"process",
"python"
] | stackoverflow_0006024799_exec_process_python.txt |
Q:
Deserializing C data
I'm receiving a struct over a network from a C server to my Python client. The protocol is UDP. I have no control over the server and it's protocols/data formats. It consists of this struct (yes, an IPv4 + port):
struct ip_s {
uint8_t i1;
uint8_t i2;
uint8_t i3;
uint8_t i4;
... | Deserializing C data | I'm receiving a struct over a network from a C server to my Python client. The protocol is UDP. I have no control over the server and it's protocols/data formats. It consists of this struct (yes, an IPv4 + port):
struct ip_s {
uint8_t i1;
uint8_t i2;
uint8_t i3;
uint8_t i4;
uint16_t port; // big end... | [
"Look into struct.unpack\nIt will probably look something like this:\n# socket setup\n\n(buffer, sockaddress) = mysocket.recvfrom(6)\nif len(buffer)== 6:\n i1,i2,i3,i4, port = struct.unpack('!BBBBH', buffer)\n\n",
"\nI'm receiving a struct over a network\n\nStop right there. Don't do that. This technique intro... | [
3,
0
] | [] | [] | [
"deserialization",
"networking",
"python",
"udp"
] | stackoverflow_0006023993_deserialization_networking_python_udp.txt |
Q:
Django data hierarchy question
I am new to Django and I am trying to build a data hierarchy that follows this pattern:
There will be several Communities - say Huntsville, Phoenix, and Madison.
Each of those communities will be able to have several distinct Categories. For example, Huntsville may have Hunting, fi... | Django data hierarchy question | I am new to Django and I am trying to build a data hierarchy that follows this pattern:
There will be several Communities - say Huntsville, Phoenix, and Madison.
Each of those communities will be able to have several distinct Categories. For example, Huntsville may have Hunting, fishing, and skiing - and Phoenix may ... | [
"I'm not sure I fully understand the behavior you're looking for, but I have some advice anyway.\nFirst, it looks like you're implementing a one-to-many when you really want a many-to-many.\nCheck out http://docs.djangoproject.com/en/1.3/ref/models/relations/\nPer that link, use models.ManyToManyField instead of mo... | [
5
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006024841_django_python.txt |
Q:
PyQT - modifying main window widgets from other functions
A PyQT beginner question. I'm wondering how to do something like the following - modify widgets in the main window from outside the main window class. Like so:
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(M... | PyQT - modifying main window widgets from other functions | A PyQT beginner question. I'm wondering how to do something like the following - modify widgets in the main window from outside the main window class. Like so:
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow,self).__init__(parent)
self.ui = Ui_MainWind... | [
"First, there's a much better way to connect signals to slots on PyQt:\nself.button.clicked.connect(self.method)\n\nYou can use lambda functions to pass extra arguments to methods.\ndef do_stuff(arg)\n #do stuff with arg\n\nThen you call\nself.button1.clicked.connect(lambda : do_stuff('btn one'))\nself.button2.... | [
4
] | [] | [] | [
"pyqt",
"python"
] | stackoverflow_0006024990_pyqt_python.txt |
Q:
Using Hist function to build series of 1D histograms in Python 3d plot
I am using pythons hist function to generate 1d histograms each linked to a given experiment.
Now I understand that the Hist function allows one to plot multiple histograms on the same x axis for comparison. I normally use something akin to th... | Using Hist function to build series of 1D histograms in Python 3d plot | I am using pythons hist function to generate 1d histograms each linked to a given experiment.
Now I understand that the Hist function allows one to plot multiple histograms on the same x axis for comparison. I normally use something akin to the following for this purpose and the result is a very nice plot where x1,x2 ... | [
"I believe you just want matplotlib.pyplot.bar3d.\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nx0, x1, x2 = [np.random.normal(loc=loc, size=100) for loc in [1, 2, 3]]\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nyspacing = 1\nfor i, measure... | [
5,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0006024622_matplotlib_python.txt |
Q:
Python "list order"
I have 2 troubles with my data, can anyone help me:
How can I get from this:
1.
k=[['1','7', 'U1'],
['1.5', '8', 'U1'],
['2', '5.5', 'U1']]
get this
1,7,U1
1.5,8,U1
2,5.5,U1
EDIT 2 I MAKE SOME CHANGE ON second case:, still searching solution for this one:
2. And how to get, from this
l=a... | Python "list order" | I have 2 troubles with my data, can anyone help me:
How can I get from this:
1.
k=[['1','7', 'U1'],
['1.5', '8', 'U1'],
['2', '5.5', 'U1']]
get this
1,7,U1
1.5,8,U1
2,5.5,U1
EDIT 2 I MAKE SOME CHANGE ON second case:, still searching solution for this one:
2. And how to get, from this
l=array([[[ 4.24231542], 'U... | [
"One-line functional style:\nprint '\\n'.join(','.join(x) for x in k)\n\n",
"1)\nfor x in k:\n print(','.join(x))\n\n2)\nfor x,y in l:\n print('%.8f,%s' % (x[0], y))\n\n",
"for a,b,c in k: print \"%s,%s,%s\" % (a,b,c)\n\nfor a,b in l: print \"%s,%s\" % (a[0],b)\n\n",
">>> print k\n[['1', '7', 'U1'], ['1... | [
5,
4,
1,
1,
1,
1,
1,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006022359_numpy_python.txt |
Q:
Passing function from another class to this class
I know, title is hard to understand.
So, i have this class:
class ConfigDict(dict):
def __init__(self, dic):
super(ConfigDict, self).__init__(dic)
def required(self, keys_array, function):
print 'required'
def valid(self, function = N... | Passing function from another class to this class | I know, title is hard to understand.
So, i have this class:
class ConfigDict(dict):
def __init__(self, dic):
super(ConfigDict, self).__init__(dic)
def required(self, keys_array, function):
print 'required'
def valid(self, function = None):
print 'valid'
And what i want - i create... | [
"Use a lambda function:\nConfigDict({'a' : ('b', lambda self: self.required(['test'], valid))})\n\nThis would require you to explicitly pass self as a parameter (From the __init__ method, it would look like dict['a'][1](self)).\nYou can find out if something is a tuple like this:\n>>> isinstance((1, 2, 3), tuple)\n... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006024123_python.txt |
Q:
using python in c++ basics
can anyone show me a basic program that includes python in a c++ program? i have gotten #include <Python.h> to work, but thats about it. how do you create a string, int, and include a module that is not part of the python library?
A:
Maybe the main Python doc can help here: http://docs... | using python in c++ basics | can anyone show me a basic program that includes python in a c++ program? i have gotten #include <Python.h> to work, but thats about it. how do you create a string, int, and include a module that is not part of the python library?
| [
"Maybe the main Python doc can help here: http://docs.python.org/extending/\nHere's a simple module written in C: http://docs.python.org/extending/extending.html#a-simple-example\n",
"I suggest Boost Python, since you're using C++ rather than C. The documentation is decent, but note that you can skip much of the... | [
3,
2,
1
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0006025386_c++_python.txt |
Q:
Python -- Speed Up Imports?
I have 10000s custom (compiled to '.so') modules that I'd like to use in python. The usage of the modules will be consequential (modules are used one after the other; not at the same time).
Normally, the code would look something like this:
# list with all the paths to all modules
li... | Python -- Speed Up Imports? | I have 10000s custom (compiled to '.so') modules that I'd like to use in python. The usage of the modules will be consequential (modules are used one after the other; not at the same time).
Normally, the code would look something like this:
# list with all the paths to all modules
listPathsToModules = [.....]
# loop... | [
"I would first question whether import is really the technique you want to be using to access thousands of code fragments - the full import process is quite expensive, and loading (non-shared) dynamic modules at all isn't particularly cheap, either.\nSecond, the code as you have written it clearly isn't what you're... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006025635_python.txt |
Q:
TypeError when assigning a random value from a list to a variable?
I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.
import random
cards = { '2'... | TypeError when assigning a random value from a list to a variable? | I have a list and I want to assign a random element from that list to a new variable five times in order to generate a hand of cards. I've searched, and I can't seem to understand why my random.choice is causing errors.
import random
cards = { '2' '3' '4' '5' '6' '7' '8' '9' 'J' 'Q' 'K' 'A' }
for newCard in range(5):... | [
"You used { and } rather than [ and ] to define cards. Therefore, it is a set. sets are not ordered, and therefore it makes no sense to try to index into it. random.choice needs to index into a collection to pull an item out of it. Anyway, a quick fix is to replace this:\nrandom.choice(cards)\n\nWith this:\nrandom.... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006025683_python.txt |
Q:
What's the pythonic way to set class variables?
perhaps I'm asking the wrong question. I have code like this:
class ExpressionGrammar(Grammar):
def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
self.nonterminals = nonterminals
self.terminals = terminals
... | What's the pythonic way to set class variables? | perhaps I'm asking the wrong question. I have code like this:
class ExpressionGrammar(Grammar):
def __init__(self, nonterminals, terminals, macros, rules, precedence, nonterminal_name = '_expr'):
self.nonterminals = nonterminals
self.terminals = terminals
self.rules = rules
self.macros = macros
s... | [
"You can avoid doing that with something like:\nclass C(object):\n def __init__(self, x, y, z, etc):\n self.__dict__.update(locals())\n\nthen all these arguments become members (including the self argument). So you may remove it with: self.__dict__.pop('self')\nI don't know how pythonic this approach is, ... | [
9,
1
] | [] | [] | [
"python"
] | stackoverflow_0006025758_python.txt |
Q:
add two lists then sort = None(?)
Second list squared each item on list, xs. Running the code below, python gives me 'None'
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')
Same list but different code--
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b... | add two lists then sort = None(?) | Second list squared each item on list, xs. Running the code below, python gives me 'None'
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')
Same list but different code--
xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = a + xs
c.sort()
print(c, en... | [
"Generally speaking, anything that operates on something in-place will return None, by convention. (This convention is not necessarily always followed, however.) somelist.sort() will sort the list in-place. \nIf you'd rather have a sorted copy, you can just call c = sorted(a + xs). sorted operates on a copy of th... | [
12,
4
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006025475_python_python_3.x.txt |
Q:
why this regular does not Match the html using python
the html is :
<div style="background-color:#A7A7A7;text-align:center;">
<span style="color:#FFFFFF;">{{rk_user.name}}のステータス</span>
</div>
my Regular is :
a = r'''
<div style="background-color:#([a-z0-9]+);text-align:center;">
\s*<span style="color:#(.+?);">(.+... | why this regular does not Match the html using python | the html is :
<div style="background-color:#A7A7A7;text-align:center;">
<span style="color:#FFFFFF;">{{rk_user.name}}のステータス</span>
</div>
my Regular is :
a = r'''
<div style="background-color:#([a-z0-9]+);text-align:center;">
\s*<span style="color:#(.+?);">(.+)</span>
</div>
'''
but this Regular does not Match the ht... | [
"Do not use regular expressions to parse HTML. Please!\nUse an HTML parser!\n\nWhy not use regex, you ask?\n\nRegular expression to match closing HTML tags\nCan you provide some examples of why it is hard to parse XML and HTML with a regex?\nUsing regular expressions to parse HTML: why not?\nCan regular expressions... | [
2,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006026104_python_regex.txt |
Q:
Run a Python script from PackageMaker in OSX
I'm having a difficult time finding any decent documentation for packaging on OSX. My package needs to run a Python script that will do some launchd magic right after the app is installed. I tried using -s scripts with packagemaker and put my script in the directory scr... | Run a Python script from PackageMaker in OSX | I'm having a difficult time finding any decent documentation for packaging on OSX. My package needs to run a Python script that will do some launchd magic right after the app is installed. I tried using -s scripts with packagemaker and put my script in the directory scripts, but I had no luck. Is there something I'm mi... | [
"I've resolved this issue.\n\nThe script needs to be named postflight and have a proper shebang line.\nThe script needs to exit with specific status codes (0 for success, which is the default, I believe).\n\n"
] | [
0
] | [] | [] | [
"macos",
"packagemaker",
"python"
] | stackoverflow_0005902058_macos_packagemaker_python.txt |
Q:
PHP SHA-512 to Python+C SHA-512
I am working on a website for a game. The accounts are created via the php based website, and the game login server is being prototyped in Python, and will be finalized in C. The problem I am having is that when I hash something in PHP, I am unable to reproduce the same result with ... | PHP SHA-512 to Python+C SHA-512 | I am working on a website for a game. The accounts are created via the php based website, and the game login server is being prototyped in Python, and will be finalized in C. The problem I am having is that when I hash something in PHP, I am unable to reproduce the same result with the same starting data and salt in Py... | [
"Here is some simpler Python code for you.\nimport crypt\ndef hashPassword(salt, password, rounds=5000):\n return crypt.crypt(password, '$6$rounds={:d}${}$'.format(rounds, salt))\n\n",
"String in python doesn't include a null byte at the end.\nAnd range(2,5000) will only loop 4998 times.\n"
] | [
1,
0
] | [] | [] | [
"php",
"python",
"sha512"
] | stackoverflow_0006026226_php_python_sha512.txt |
Q:
Ending external programs with Python
I'm writing a program that needs to be able to kill certain processes. The two lines I'm currently using work; however, the second line os.system(task) launches command prompt for a split second whilst it's ending a process. Are there any equivalent lines which do not launch co... | Ending external programs with Python | I'm writing a program that needs to be able to kill certain processes. The two lines I'm currently using work; however, the second line os.system(task) launches command prompt for a split second whilst it's ending a process. Are there any equivalent lines which do not launch command prompt?
Snippet :
task = 'taskkill ... | [
"Try using subprocess.check_call instead of os.system. This won't launch the process in a console window.\nimport subprocess\ntaskname = '...'\ntask = 'taskkill /im ' + taskname + ' /f'\nsubprocess.check_call(task, shell=True)\n\n"
] | [
3
] | [] | [] | [
"abort",
"kill",
"process",
"python"
] | stackoverflow_0006026791_abort_kill_process_python.txt |
Q:
How can I get sqlite working on a shared hosting server?
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.
anyhow, when I run the script belo... | How can I get sqlite working on a shared hosting server? | I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.
anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm ... | [
"In general, the first thing to do is to ask your host. I seems a bit odd that SQLite is not installed (or installed properly). So they'll likely fix it quite fast if you ask them.\n",
"For python 2.4, you need sqlite and bindings, pysqlite 2 or aspw\n",
"None of the files listed in the sqlite folder is the _sq... | [
0,
0,
0,
0
] | [] | [] | [
"linux",
"python",
"sqlite",
"unix"
] | stackoverflow_0006026485_linux_python_sqlite_unix.txt |
Q:
Translation of this Python Line
I am relatively new to Python and having problem translating the following one line:
diffList = [key for key in set(dict1n.keys() + dict2.keys()) if dict1.get(key) != dict2t.get(key)]
Can someone please rewrite it for me - break it down into multiple lines in a "normal" nice format... | Translation of this Python Line | I am relatively new to Python and having problem translating the following one line:
diffList = [key for key in set(dict1n.keys() + dict2.keys()) if dict1.get(key) != dict2t.get(key)]
Can someone please rewrite it for me - break it down into multiple lines in a "normal" nice format?
I think - and I am not sure - what ... | [
"That translates to:\ndiffList = []\nfor key in set(dict1.keys() + dict2.keys()):\n if dict1.get(key) != dict2.get(key):\n diffList.append(key)\n\nWhat this basically does is it generates a new list, with the unique values from both dicts. Not that those values are unique per key, and not necessarily uniq... | [
3,
2,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006027225_dictionary_python.txt |
Q:
Problem when querying the database
When I do:
channel = session.query(Channel).options(eagerload("items")).filter(Channel.title == title)
I get this error:
TypeError: 'bool' object is not callable
If I rid of options(eagerload("items")), it's working properly.
Any idea??
Thanks in advance!
A:
SQLAlchemy filte... | Problem when querying the database | When I do:
channel = session.query(Channel).options(eagerload("items")).filter(Channel.title == title)
I get this error:
TypeError: 'bool' object is not callable
If I rid of options(eagerload("items")), it's working properly.
Any idea??
Thanks in advance!
| [
"SQLAlchemy filtering works with operator overloading on column objects. You are, however, not referencing the column object, but the value property of the table. So instead of\nChannel.title == title\n\nwhich is a 'bool' object, you need\nChannel.c.title == title\n\nwhich yields a SLQAlchemy specific object.\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0004188628_python_sqlalchemy.txt |
Q:
SqlAlchemy: Get instances of certain type in a relationship that can contain objects of several types
I have an application with a "BaseVisibilizer" class that is base
class for two other classes:
class BaseVisibilizer(declarativeBase):
__tablename__ = "base_visibilizers"
_polymorphicIdentity = Colu... | SqlAlchemy: Get instances of certain type in a relationship that can contain objects of several types | I have an application with a "BaseVisibilizer" class that is base
class for two other classes:
class BaseVisibilizer(declarativeBase):
__tablename__ = "base_visibilizers"
_polymorphicIdentity = Column("polymorphic_identity", String(20), key="polymorphicIdentity")
__mapper_args__ = {
... | [
"One solution would be to create another relationship on Whatever which would include the filter to the specific table UserGroup, which should do the trick.\nSee Multiple Relationships against the Same Parent/Child documentation for more information. In your case adding additional join condition on UserGroup table ... | [
0
] | [] | [] | [
"class",
"oop",
"python",
"relationship",
"sqlalchemy"
] | stackoverflow_0006011289_class_oop_python_relationship_sqlalchemy.txt |
Q:
Retrieving string from html on non-unique table
Here is the html I am trying to parse.
<TD>Serial Number</TD><TD>AB12345678</TD>
I am attempting to use regex to parse the data. I heard about BeautifulSoup but there are around 50 items like this on the page all using the same table parameters and none of them have... | Retrieving string from html on non-unique table | Here is the html I am trying to parse.
<TD>Serial Number</TD><TD>AB12345678</TD>
I am attempting to use regex to parse the data. I heard about BeautifulSoup but there are around 50 items like this on the page all using the same table parameters and none of them have ID numbers. The closest they have to unique identifi... | [
"Pyparsing can give you a little more robust extractor for your data:\nfrom pyparsing import makeHTMLTags, Word, alphanums\n\nhtmlfrag = \"\"\"<blah></blah><TD>Serial Number</TD><TD>\n AB12345678\n </TD><stuff></stuff>\"\"\"\n\ntd,tdEnd = makeHTMLTags(\"td\")\n\nsernoFormat = (td + \"Serial Nu... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python",
"regex",
"urllib"
] | stackoverflow_0006022278_beautifulsoup_html_parsing_python_regex_urllib.txt |
Q:
What's the preferred method in the community for having python 2.x and 3.x in the same codebase?
I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.
I don't mind about devotin... | What's the preferred method in the community for having python 2.x and 3.x in the same codebase? | I am starting a project in Python 3.x, (I'm quite new to Python) and there exists the possibility that I will need to use say Thrift or any other library that is not yet ported to Python 3.x.
I don't mind about devoting some (substantial) amount of time to convert an external library to Python 3.x if with that others c... | [
"I suggest supporting Python 2.x and Python 3.x simultaneously from the same code base, using tox. Check out the Supporting All Versions of Python All The Time With Tox talk from Pycon 2011.\n",
"The approach I've been using is to maintain the code in version 2 format, use the 2to3 converter, and test the output... | [
2,
2,
2,
2,
1
] | [] | [] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0006024212_python_python_2.7_python_3.x.txt |
Q:
having two or more worker queues in python
So I have 2 main worker processes one is supposed to fetch content of a URL and the other
will insert each of the anchor links into a postgre table. Now I am running
12 instances of the first process all of which taking their URL from a single URL queue, and then placin... | having two or more worker queues in python | So I have 2 main worker processes one is supposed to fetch content of a URL and the other
will insert each of the anchor links into a postgre table. Now I am running
12 instances of the first process all of which taking their URL from a single URL queue, and then placing the anchors in a second queue but how do I hav... | [
"you need two queues the URLFetchers will pop URLs from one queue and push into a second one, then the AnchorInserters should pop from this second queue to process the data. This organisation should give you a good sync mechanism for your problem.\nEdit: to avoid worker exiting\nYou need to block till one element i... | [
1
] | [] | [] | [
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0006028493_multiprocessing_multithreading_python.txt |
Q:
How to add dtd validation to `xml.etree.cElementTree.iterparse`
I know, that this way of dtd validation before parsing a xml file works:
from lxml import etree
context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
But how do I get this to work for the xml.etree.cElementTree.... | How to add dtd validation to `xml.etree.cElementTree.iterparse` | I know, that this way of dtd validation before parsing a xml file works:
from lxml import etree
context = etree.iterparse(PATH_TO_XML, dtd_validation=True, events=("start", "end"))
But how do I get this to work for the xml.etree.cElementTree.iterparse?
from xml.etree.cElementTree import iterparse
conte... | [
"cElementTree is not part of lxml.\nAccording to the cElementTree website, DTD Validation is not available to cElementTree.\n"
] | [
2
] | [] | [] | [
"dtd",
"lxml",
"python",
"xml"
] | stackoverflow_0006028386_dtd_lxml_python_xml.txt |
Q:
Python SMTP import
Has anyone had this before? It's working with all the other scripts I've written.
import smtplib
File "/usr/lib64/python2.4/smtplib.py", line 49, in ?
from email.base64MIME import encode as encode_base64
ImportError: No module named base64MIME
And it's not called email.py!
A:
Do python -... | Python SMTP import | Has anyone had this before? It's working with all the other scripts I've written.
import smtplib
File "/usr/lib64/python2.4/smtplib.py", line 49, in ?
from email.base64MIME import encode as encode_base64
ImportError: No module named base64MIME
And it's not called email.py!
| [
"Do python -v then import smtplib at the python command-line.\nThat should show you where it is getting email from.\nEDIT:\nPlease could you post your output from the import email line.\nMine is:\nimport email # directory /usr/lib/python2.4/email\n# /usr/lib/python2.4/email/__init__.pyc matches /usr/lib/python2.4/e... | [
3
] | [] | [] | [
"import",
"python",
"smtp"
] | stackoverflow_0006028957_import_python_smtp.txt |
Q:
Python Datastructure Suggestion
i am building a small search engine to search a collection of pdfs. From each pdf i extract a set of tokens and store it in database. I do not want to store duplicate tokens in database, instead i want to store count of each token in the database. Does python has any special datastr... | Python Datastructure Suggestion | i am building a small search engine to search a collection of pdfs. From each pdf i extract a set of tokens and store it in database. I do not want to store duplicate tokens in database, instead i want to store count of each token in the database. Does python has any special datastructure that do not store duplicates b... | [
"Python >=2.7 has the Counter.\n",
"I'd suggest to use a simple dictionary to store the count like\nstorage = {} # initialize\n# ...\nif !storage.has_key(token):\n storage[token] = 1\nelse:\n storage[token] += 1\n\nEDIT\nThat said, if you're using Python 3 I'd follow Space_C0wb0y's suggestion to use the Counter... | [
5,
3,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0006028968_python.txt |
Q:
Write a list of Complex Numbers as Binary Data
I'm trying to output some data from a python script to a binary file.
If I have a list of floats I've been using this
out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()
This seems t... | Write a list of Complex Numbers as Binary Data | I'm trying to output some data from a python script to a binary file.
If I have a list of floats I've been using this
out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()
This seems to work fine, at least it's resulting in a file with ... | [
"Don't invent your own serialization methods when Python offers so many good ones out of the box! I suggest you use pickle - it works with complex numbers as well (*):\n>>> import pickle\n>>> s = pickle.dumps([1+2j, 5-1j])\n>>> pickle.loads(s)\n[(1+2j), (5-1j)]\n\nI'm using dumps for demonstration here, you can als... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006029057_python.txt |
Q:
How to check user agent inside Django template?
I want to check the useragent using Django inside my template. I know this is possible using JavaScript, but I wanted a server side solution.
I know I can use HttpRequest.META in some middleware class, which I am not currently looking for. I want to determine this us... | How to check user agent inside Django template? | I want to check the useragent using Django inside my template. I know this is possible using JavaScript, but I wanted a server side solution.
I know I can use HttpRequest.META in some middleware class, which I am not currently looking for. I want to determine this using some code in the template itself, without any dep... | [
"You need to use context processors, more specifically django.core.context_processors.request.\nThis SO answer covers it quiet well:\nHow can I pass data to any template from any view in Django?\nEspecially this blog post, that is referenced in the SO answer:\nhttp://www.b-list.org/weblog/2006/jun/14/django-tips-te... | [
3
] | [] | [] | [
"django",
"python",
"user_agent"
] | stackoverflow_0006029732_django_python_user_agent.txt |
Q:
python mechanize to access Sharepoint website
I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:
import mechanize
url = "http://sharepoint:8080/foo/bar/foobar.aspx"
br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_passwor... | python mechanize to access Sharepoint website | I'm trying to access Sharepoint using mechanize but i got a 401 error. Here's the code i'm using:
import mechanize
url = "http://sharepoint:8080/foo/bar/foobar.aspx"
br.addheaders = [('User-agent', 'Mozilla/4.0(compatible; MSIE 7.0b; Windows NT 6.0)')]
br.add_password(url, 'domain\\user', 'myPassword')
r = br.open(ur... | [
"Did you happen to try Python Ntlm for accessing SharePoint? \nExamples in the Ntlm doc will explain how to use it with Urllib2. Pasted below the code for using NTLM authentication using mechanize.\nimport mechanize\nfrom ntlm import HTTPNtlmAuthHandler\npass_manager = mechanize.HTTPPasswordMgrWithDefaultRealm()\np... | [
1,
0,
0
] | [] | [] | [
"mechanize",
"python"
] | stackoverflow_0006026152_mechanize_python.txt |
Q:
Why can't I execute system("xxx.Py -yyy -zzz...") on Ruby?
My OS is Win7
I have a python file(xxx.py), and I need execute it on ruby
my ruby code:
system("xxx.py -yyy -zzz");
and run it no result, but it can run on cmd(xxx.py -yyy -zzz)
and ruby can run system("java -h"); or system("python -h"); success.
What's p... | Why can't I execute system("xxx.Py -yyy -zzz...") on Ruby? | My OS is Win7
I have a python file(xxx.py), and I need execute it on ruby
my ruby code:
system("xxx.py -yyy -zzz");
and run it no result, but it can run on cmd(xxx.py -yyy -zzz)
and ruby can run system("java -h"); or system("python -h"); success.
What's problem with me???
| [
"Just to fill out Dogberts answer in full\nUsing system(\"python xxx.py -yyy -zzz\") should prrovide you with what you want. This is because your python script is probably not +777 or is missing its shebang line. \n"
] | [
4
] | [] | [] | [
"python",
"ruby"
] | stackoverflow_0006029764_python_ruby.txt |
Q:
What are the RTP Libraries in Python with good RTCP Support?
I am looking for a RTP/RTCP Library that is open source.
I plan to use Python.
A:
GStreamer. Open source multimedia framework
This is a good framework for doing RTP in. It is widely used on a number of platforms and has bindings in many different lang... | What are the RTP Libraries in Python with good RTCP Support? | I am looking for a RTP/RTCP Library that is open source.
I plan to use Python.
| [
"GStreamer. Open source multimedia framework \nThis is a good framework for doing RTP in. It is widely used on a number of platforms and has bindings in many different languages.\nHere is a link to the python bindings of GStreamer\nAdvantages to using GStreamer:\n\nCross Platform\nCross Language\nComprehensive and ... | [
4
] | [] | [] | [
"open_source",
"python",
"rtp"
] | stackoverflow_0006029778_open_source_python_rtp.txt |
Q:
Boxplotting Masked Arrays
How can i boxplot only the non-masked values of a MaskedArray ? I tought this would happen automatically by boxplot(ma) but this seems to boxplot the non-masked array.
A:
I think you are right -- plt.boxplot ignores the mask if sent a masked array.
So it looks like you'll have to give b... | Boxplotting Masked Arrays | How can i boxplot only the non-masked values of a MaskedArray ? I tought this would happen automatically by boxplot(ma) but this seems to boxplot the non-masked array.
| [
"I think you are right -- plt.boxplot ignores the mask if sent a masked array.\nSo it looks like you'll have to give boxplot some extra help by sending it only the values which are not masked. Since each row of the array may have a different number of unmasked values, you won't be able to use a numpy array. You'll ... | [
9
] | [] | [] | [
"boxplot",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0006029912_boxplot_matplotlib_numpy_python.txt |
Q:
SQLAlchemy: add a relationship using id instead of object?
Is it possible to add to a SQLAlchemy relationship using ids rather than objects?
For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:
class Review(Base):
artist_id = Column(Integer, ForeignKey(... | SQLAlchemy: add a relationship using id instead of object? | Is it possible to add to a SQLAlchemy relationship using ids rather than objects?
For example, consider two declarative SQLAlchemy classes, Review and Artist, with a relationship between them:
class Review(Base):
artist_id = Column(Integer, ForeignKey('artist.id'))
artist = relationship(Artist, backref=backref(... | [
"Your best bet is probably to compose an update expression against the backing tables. Otherwise, you can't really modify a Review without actually querying for it (and that's what your doing; you aren't actually modifying the Artist at all).\nAssuming Review.id is the primary key, That would roughly be:\nconn = s... | [
9,
8,
3
] | [] | [] | [
"orm",
"python",
"relationship",
"sqlalchemy"
] | stackoverflow_0006024462_orm_python_relationship_sqlalchemy.txt |
Q:
Python - Generate a multiple row update query
My goal is dynamically generate in Python a SQL query similar to,
UPDATE SURV_SCF_ID_STATUS
SET AGE_STATUS = CASE NAME
WHEN 'entityXp1' THEN '1'
WHEN 'entityXp3' THEN '0'
WHEN 'entityXpto1' THEN '1'
WHEN 'entityXpto3' THEN '1'
EN... | Python - Generate a multiple row update query | My goal is dynamically generate in Python a SQL query similar to,
UPDATE SURV_SCF_ID_STATUS
SET AGE_STATUS = CASE NAME
WHEN 'entityXp1' THEN '1'
WHEN 'entityXp3' THEN '0'
WHEN 'entityXpto1' THEN '1'
WHEN 'entityXpto3' THEN '1'
END
WHERE NAME IN ('entityXp1', 'entityXp3', 'entityX... | [
"You can build the condition_string via\nconditions_string = ' '.join([\"\\t\\tWHEN %s THEN %s\\n\" % (x, y) for x, y in logs_age_list])\n\nand the where_string as\nwhere_string = ', '.join([duo[0] for duo inlogs_age_list])\n\nthen do something like\nsql = '''\nUPDATE SURV_SCF_ID_STATUS\nSET AGE_STATUS = CASE NAME\... | [
1
] | [] | [] | [
"python",
"sql",
"sql_update"
] | stackoverflow_0006030136_python_sql_sql_update.txt |
Q:
Why would a websocket created with pywebsocket be closed automatically?
I want to test websocket with pywebsocket, after some configurations following some instructions I found on the Internet, I finally got it run.
Then I want to try the echo example: http://code.google.com/p/pywebsocket/source/browse/trunk/src/e... | Why would a websocket created with pywebsocket be closed automatically? | I want to test websocket with pywebsocket, after some configurations following some instructions I found on the Internet, I finally got it run.
Then I want to try the echo example: http://code.google.com/p/pywebsocket/source/browse/trunk/src/example/console.html
the websocket is connected successfully, and I can do tho... | [
"I've found the solution by myself, modify /etc/apache2/mods-enabled/reqtimeout.conf to change the timeout time to 60 seconds. \n"
] | [
7
] | [] | [] | [
"apache",
"mod_pywebsocket",
"python",
"websocket"
] | stackoverflow_0006030436_apache_mod_pywebsocket_python_websocket.txt |
Q:
Parsing of a huge xml file with `pythons etree.iterparse()` does not work right. Is there a logic error in the code?
I want to parse a huge file xml-file. The records in this huge file do look for example like this. And in general the file looks like this
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp ... | Parsing of a huge xml file with `pythons etree.iterparse()` does not work right. Is there a logic error in the code? | I want to parse a huge file xml-file. The records in this huge file do look for example like this. And in general the file looks like this
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE dblp SYSTEM "dblp.dtd">
<dblp>
record_1
...
record_n
</dblp>
I wrote some code, that shall get me a selection of r... | [
"Add print statements in the blocks of code where you detect start and stop of a tag in elements, to make sure you are detecting these properly. I suspect that for some reason you aren't getting to the code that clears the authors list.\nTry commenting out this code (or at least, move it into the \"end\" handling ... | [
3,
3
] | [] | [] | [
"elementtree",
"iterparse",
"lxml",
"python",
"xml"
] | stackoverflow_0006028595_elementtree_iterparse_lxml_python_xml.txt |
Q:
Using 1:n relations in django admin
I want to build a questionary in Django and use django's admin-interface to enter the data.
The site-admin should be able to set-up new questionaries with questions. Define models which questions have always a querstionary in relation is no problem:
class Questionary(models.Mode... | Using 1:n relations in django admin | I want to build a questionary in Django and use django's admin-interface to enter the data.
The site-admin should be able to set-up new questionaries with questions. Define models which questions have always a querstionary in relation is no problem:
class Questionary(models.Model):
title = models.CharField(max_leng... | [
"Yes you can, take a look at InlineModelAdmin\n"
] | [
2
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python",
"relation"
] | stackoverflow_0006030838_django_django_admin_django_models_python_relation.txt |
Q:
Merging a list of numpy arrays into one array (fast)
what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?
I tried two approaches:
merged_array = array(list_of_arrays) from Pythonic way to create a nu... | Merging a list of numpy arrays into one array (fast) | what would be the fastest way to merge a list of numpy arrays into one array if one knows the length of the list and the size of the arrays, which is the same for all?
I tried two approaches:
merged_array = array(list_of_arrays) from Pythonic way to create a numpy array from a list of numpy arrays and
vstack
A you ca... | [
"You have 80 arrays 320x320? So you probably want to use dstack:\nfirst3 = numpy.dstack(firstmatrices)\n\nThis returns one 80x320x320 array just like numpy.array(firstmatrices) does:\ntimeit numpy.dstack(firstmatrices)\n10 loops, best of 3: 47.1 ms per loop\n\n\ntimeit numpy.array(firstmatrices)\n1 loops, best of 3... | [
22
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0006030906_arrays_numpy_python.txt |
Q:
Handling an interactive script from another script , using python
I have a shell script and this one is interactive and I am creating some automation to provide inputs to this shell scripts. The automation is done using Python. example,
the shell script waits for an input like, "what is the domain name?"
now the p... | Handling an interactive script from another script , using python | I have a shell script and this one is interactive and I am creating some automation to provide inputs to this shell scripts. The automation is done using Python. example,
the shell script waits for an input like, "what is the domain name?"
now the python should be able to provide the input and press ENTER.
Please prov... | [
"pexpect: http://pypi.python.org/pypi/pexpect/\nit comes with a bunch of examples. e.g. this one for ftp:\nimport pexpect\nimport sys\n\nchild = pexpect.spawn('ftp ftp.openbsd.org')\nchild.expect('(?i)name .*: ')\nchild.sendline('anonymous')\nchild.expect('(?i)password')\nchild.sendline('pexpect@sourceforge.net')\... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006031007_python.txt |
Q:
Python or Java for text processing (text mining, information retrieval, natural language processing)
I'm soon to start on a new project where I am going to do lots of text processing tasks like searching, categorization/classifying, clustering, and so on.
There's going to be a huge amount of documents that need t... | Python or Java for text processing (text mining, information retrieval, natural language processing) | I'm soon to start on a new project where I am going to do lots of text processing tasks like searching, categorization/classifying, clustering, and so on.
There's going to be a huge amount of documents that need to be processed; probably millions of documents. After the initial processing, it also has to be able to be... | [
"Both are good. Java has a lot of steam going into text processing. Stanford's text processing system, OpenNLP, UIMA, and GATE seem to be the big players (I know I am missing some). You can literally run the StanfordNLP module on a large corpus after a few minutes of playing with it. But, it has major memory requir... | [
18,
9,
3,
2
] | [] | [] | [
"information_retrieval",
"java",
"nlp",
"python",
"text_mining"
] | stackoverflow_0006030291_information_retrieval_java_nlp_python_text_mining.txt |
Q:
Where can I download a sample Django template?
I just started working at a place as a front end developer where I need to build Django templates. I never worked with these before, does anyone know where I can download a sample template so I can look through the code structure?
I won't be doing any application deve... | Where can I download a sample Django template? | I just started working at a place as a front end developer where I need to build Django templates. I never worked with these before, does anyone know where I can download a sample template so I can look through the code structure?
I won't be doing any application development using the Django framework, only taking the ... | [
"There are lots of Open Source django apps that you could look at for inspiration. One example is Zinnia which is a blogging application - there are dozens of templates in this project, see this directory. There are many other open source django projects on http://github.com and http://bitbucket.org\nYou should als... | [
6,
4
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0006031349_django_python_templates.txt |
Q:
using numpy.memmap to map a device file
Is there a reason that opening a device file (rather than a regular file) using numpy's memmap shouldn't work?
self.surface = np.memmap('/dev/fb1', dtype=np.uint16, mode='r+', shape=(320,240))
I'm working with a custom kernel module that adds a framebuffer device, which wor... | using numpy.memmap to map a device file | Is there a reason that opening a device file (rather than a regular file) using numpy's memmap shouldn't work?
self.surface = np.memmap('/dev/fb1', dtype=np.uint16, mode='r+', shape=(320,240))
I'm working with a custom kernel module that adds a framebuffer device, which works fine with python's regular mmap module. Bu... | [
"If your code works fine with the python mmap module, you can use it directly instead of numpy.memmap:\n>>> fd = os.open(\"a\", os.O_RDWR)\n>>> buffer = mmap.mmap(fd, 0)\n>>> surface = np.ndarray((320,240), np.uint16, buffer)\n\nThis has the other advantage that you have more control over the memory mapping used.\... | [
2
] | [] | [] | [
"device_driver",
"linux",
"mmap",
"numpy",
"python"
] | stackoverflow_0004988465_device_driver_linux_mmap_numpy_python.txt |
Q:
Django-Secretballot does not work?
I am using Django-secretballot app which allows anonymous voting. First we register a model for secret voting and then there is a function add_vote() which takes 2 arguments. 'Token' and vote value(+1 or -1).
from docs:
add_vote:
function that takes a token and a vote (+1 or -1)... | Django-Secretballot does not work? | I am using Django-secretballot app which allows anonymous voting. First we register a model for secret voting and then there is a function add_vote() which takes 2 arguments. 'Token' and vote value(+1 or -1).
from docs:
add_vote:
function that takes a token and a vote (+1 or -1) and adds or updates the vote for said ... | [
"I'm the author and although I haven't actively developed it recently I hope you find it useful.\ntoken can be any unique string you require, generally speaking what you have should work but there's a chance you're behind a proxy or there's another issue with REMOTE_ADDR in your server config (which is beyond what ... | [
2
] | [] | [] | [
"django",
"django_models",
"django_sessions",
"django_views",
"python"
] | stackoverflow_0006029559_django_django_models_django_sessions_django_views_python.txt |
Q:
setting color range in matplotlib patchcollection
I am plotting a PatchCollection in matplotlib with coords and patch color values read in from a file.
The problem is that matplotlib seems to automatically scale the color range to the min/max of the data values. How can I manually set the color range? E.g. if my ... | setting color range in matplotlib patchcollection | I am plotting a PatchCollection in matplotlib with coords and patch color values read in from a file.
The problem is that matplotlib seems to automatically scale the color range to the min/max of the data values. How can I manually set the color range? E.g. if my data range is 10-30, but I want to scale this to a colo... | [
"Use p.set_clim([5, 50]) to set the color scaling minimums and maximums in the case of your example. Anything in matplotlib that has a colormap has the get_clim and set_clim methods.\nAs a full example:\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import PatchCollection\nfrom mat... | [
38
] | [] | [] | [
"matplotlib",
"patch",
"python"
] | stackoverflow_0006028675_matplotlib_patch_python.txt |
Q:
inverted reindent.py (spaces to tabs)
afaik reindent.py (available in the standard python examples) has a tokenizer allowing it to do smart reindenting based on the indentation level rather than on the number of spaces osed per level (which can vary in bad code)
unfortunately it enforces 4-space indentation, but i... | inverted reindent.py (spaces to tabs) | afaik reindent.py (available in the standard python examples) has a tokenizer allowing it to do smart reindenting based on the indentation level rather than on the number of spaces osed per level (which can vary in bad code)
unfortunately it enforces 4-space indentation, but i want tabs, because 1 tab == 1 indentation ... | [
"Using sed in unix you could get it with one line:\nsed -r ':f; s|^(\\t*)\\s{4}|\\1\\t|g; t f' file\n\nedit: this will work for spaces at beginning of the line only.\n"
] | [
3
] | [] | [] | [
"indentation",
"python"
] | stackoverflow_0006031954_indentation_python.txt |
Q:
Limit number of executions of a python program
Hello
I made a program in python2.6 and converted to exe with py2exe.
I wish that could limit the number of times the
user can use, then this is blocked with a counter or maybe a library.
Any ideas?
A:
Either store the count in the registry or write it to a file alo... | Limit number of executions of a python program | Hello
I made a program in python2.6 and converted to exe with py2exe.
I wish that could limit the number of times the
user can use, then this is blocked with a counter or maybe a library.
Any ideas?
| [
"Either store the count in the registry or write it to a file along with the program. Either way is easy for the end user to modify though, unless you manage to encrypt the count file.\nSince it's an .exe from py2exe, there would be at least a low barrier if you used something like AES encryption with a string key... | [
4,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006032106_python.txt |
Q:
A neat and clean algorithm for the image resize
I need a better and clean algorithm for resizing and Image. My Images are mostly large and I want to resize it smaller size without much degradation of quality. I am using python image library PIL. Here I found An algorithm for resizing . when My Original image wi... | A neat and clean algorithm for the image resize | I need a better and clean algorithm for resizing and Image. My Images are mostly large and I want to resize it smaller size without much degradation of quality. I am using python image library PIL. Here I found An algorithm for resizing . when My Original image width is greater than the length then it seems to works ... | [
"I've used this before and it works for image with length > width and for any common image format.\nimg = Image.open(filename)\nimg.thumbnail((100,100))\n\nEven in the case that the algo is broken for length > width but works when length < width. You can rotate the image by 90 degree first, resize it and rotate it ... | [
0
] | [] | [] | [
"algorithm",
"image",
"python"
] | stackoverflow_0005918567_algorithm_image_python.txt |
Q:
Python encoding issue
i m working with some python script, got a raw string with UTF8 encoding. first of all i decoded it to utf8 then some processing is done and at the end i encode it back to utf8 and inserted to DB(mysql) but chars in DB are not presented in real format.
str = '<term>Beiträge</term>'
str = str... | Python encoding issue | i m working with some python script, got a raw string with UTF8 encoding. first of all i decoded it to utf8 then some processing is done and at the end i encode it back to utf8 and inserted to DB(mysql) but chars in DB are not presented in real format.
str = '<term>Beiträge</term>'
str = str.decode('utf8')
...
...
...... | [
"Assuming you are using the MySQLdb library, you need to create connections using the keyword arguments:\n\nuse_unicode\n If True, text-like columns are returned as unicode objects using the\n connection's character set. Otherwise,\n text-like columns are returned as\n strings. columns are returned as\n no... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006031219_python.txt |
Q:
Setting up Python in Netbeans
I remember successfully doing this countless times before with a bit of trial and error, but after a new reinstall of Snow Leopard, I would like to just ask the Stackoverflow community this for once and for all...
I installed Netbeans 7 (for C++). For some reason, I didn't see any way... | Setting up Python in Netbeans | I remember successfully doing this countless times before with a bit of trial and error, but after a new reinstall of Snow Leopard, I would like to just ask the Stackoverflow community this for once and for all...
I installed Netbeans 7 (for C++). For some reason, I didn't see any way to install Python plugins here, so... | [
"Unfortunately Netbeans seem to have dropped support for Python in version 7. I find it pretty annoying as it seems to work ok in 6.9.1 (although I resort to Eclipse for serious Python programming as PyDev has better code completion).\nSo, your options are \n\nDownload 6.9.1, and get the python plugin via tools--> ... | [
11,
1
] | [
"Your python 3.1 binary. I'm not familiar with OSX but usually it would be something like /usr/bin/python3.1\n"
] | [
-1
] | [
"netbeans",
"python",
"python_3.x"
] | stackoverflow_0005769000_netbeans_python_python_3.x.txt |
Q:
How can I name my objects in Python?
I know this is a very simple question, but unfortunately I don't know enough to search effectively for an answer. Any answers or links to things I should already know would be greatly appreciated.
What I am trying to do is make an environment in Python where I have a bunch of t... | How can I name my objects in Python? | I know this is a very simple question, but unfortunately I don't know enough to search effectively for an answer. Any answers or links to things I should already know would be greatly appreciated.
What I am trying to do is make an environment in Python where I have a bunch of turtles running around doing various things... | [
"You should add the turtles to the list directly while executing the loop, for example\nmy_turtles = []\nfor i in range(num_turtles):\n x = ...\n y = ...\n h = ...\n my_turtles.append(Turtle(x, y, h))\n\nIt's often also possible to write this as a \"list comprehension\":\nmy_turtles = [Turtle(..., ..., ... | [
6,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006032720_python.txt |
Q:
Nginx + fastcgi truncation problem
I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)
Details:
I'm usin... | Nginx + fastcgi truncation problem | I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)
Details:
I'm using flup, and spawning the fastcgi server ... | [
"I had the same exact problem running Nagios on nginx. I stumbled upon your question while googling for an answer, and reading \"permission denied\" related answers it struck me (and perhaps it will help you) : \n\nNginx error.log was reporting :\n2011/03/07 11:36:02 [crit] 30977#0: *225952 open() \"/var/lib/nginx/... | [
8,
6,
3,
2,
2,
0
] | [] | [] | [
"django",
"fastcgi",
"nginx",
"python"
] | stackoverflow_0000159541_django_fastcgi_nginx_python.txt |
Q:
Two sets of users (teacher and student) in Django authentication
I'm building a web application where I have 2 sets of users (students and teachers). Teachers should be able to create their account, create a page of their content. Students should be able to create an account to sign up for this content. I am curre... | Two sets of users (teacher and student) in Django authentication | I'm building a web application where I have 2 sets of users (students and teachers). Teachers should be able to create their account, create a page of their content. Students should be able to create an account to sign up for this content. I am currently using django-registration to handle registration but I am wonderi... | [
"You could use permissions. When they sign up if they're a Teacher give them content creation permissions. If they're a student they don't get the permissions.\nIn the user profile I would just have a field that says which type they are. Unless a lot of the data is different I wouldn't have two user profiles.\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006033067_django_python.txt |
Q:
Python logging: Why is __init__ called twice?
I am trying to use python logging with a config file and an own handler. This works to some degree. What really puzzle me is __init__ being called twice and __del__ being called once. When I remove the whole config file stuff and create the handler directly within the ... | Python logging: Why is __init__ called twice? | I am trying to use python logging with a config file and an own handler. This works to some degree. What really puzzle me is __init__ being called twice and __del__ being called once. When I remove the whole config file stuff and create the handler directly within the code __init__ is called once and __del__ is never c... | [
"\n\nWhy is init called twice?\n\n\nIf you follow the code of the logging module, you'll see that when you're loading the logging configuration file, it instantiates all the handlers (First instantiation).\nIn your code, you declare your handler like test1.Test1TimedRotatingFileHandler, so when it try to import you... | [
14,
5
] | [] | [] | [
"config",
"handler",
"init",
"logging",
"python"
] | stackoverflow_0006032053_config_handler_init_logging_python.txt |
Q:
Python, step through folders (to run scripts)
Since Im unfamiliar with Python I thought i'd come here.
Anyways I have several Folders (lets say 20 folders)
Within each folder is more folders (lets say 5 per)
and within EACH one of these folders is another folder, and within THAT is a script I need to run.
The scri... | Python, step through folders (to run scripts) | Since Im unfamiliar with Python I thought i'd come here.
Anyways I have several Folders (lets say 20 folders)
Within each folder is more folders (lets say 5 per)
and within EACH one of these folders is another folder, and within THAT is a script I need to run.
The script is ran the same way 'ie':sh script.sh
Basically... | [
"import glob,subprocess\nfor script in glob.glob('*/*/*/*.sh'):\n s = subprocess.Popen([script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n stdoutdata,stderrdata = s.communicate()\n returncode = s.returncode\n # Do something with stdoutdata, returncode etc. here\n\n",
"A bit overkill, but it should... | [
2,
1
] | [] | [] | [
"python",
"python_2.6"
] | stackoverflow_0006033441_python_python_2.6.txt |
Q:
DirectoryIndex ignored by Django Webapplication
Hey there,
i'm using an Q+A script that is build with python and django. My problem is that i want to serve some static files i placed in a certain directory. That works basically. My problem is if someone calls http://domains.com/static/sub1/ the content of this dir... | DirectoryIndex ignored by Django Webapplication | Hey there,
i'm using an Q+A script that is build with python and django. My problem is that i want to serve some static files i placed in a certain directory. That works basically. My problem is if someone calls http://domains.com/static/sub1/ the content of this directory is shown as a list. I want that if you type th... | [
" urlpatterns += patterns('',\n url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {\n 'document_root': settings.MEDIA_ROOT,\n 'show_indexs': True,\n }),\n )\n\n"
] | [
0
] | [] | [] | [
"django",
"python",
"static_files"
] | stackoverflow_0006030088_django_python_static_files.txt |
Q:
How to avoid Python fileinput buffering
Possible Duplicate:
Setting smaller buffer size for sys.stdin?
I have a Python (2.4/2.7) script using fileinput to read from standard input or from files. It's easy to use, and works well except for one case:
tail -f log | filter.py
The problem is that my script buffers ... | How to avoid Python fileinput buffering |
Possible Duplicate:
Setting smaller buffer size for sys.stdin?
I have a Python (2.4/2.7) script using fileinput to read from standard input or from files. It's easy to use, and works well except for one case:
tail -f log | filter.py
The problem is that my script buffers its input, whereas (at least in this case) I... | [
"Try running python -u; man says that it will \"force stdin, stdout and stderr to be totally unbuffered\".\nYou can just alter the hashbang path at the first line of filter.py.\n",
"Have you tried:\ndef hook_nobuf(filename, mode):\n return open(filename, mode, 0)\n\nfi = fileinput.FileInput(openhook=hook_nobu... | [
3,
0
] | [] | [] | [
"buffering",
"file_io",
"python",
"readline"
] | stackoverflow_0006033781_buffering_file_io_python_readline.txt |
Q:
Python: Get user input by letting user edit default value
I've got a script that pulls text from a Web server. I want to give the user (me) an opportunity to edit that text so they can select which part to keep. Ideally, it would be something like this:
editedText= raw_input(defaultText)
So, defaultText is printe... | Python: Get user input by letting user edit default value | I've got a script that pulls text from a Web server. I want to give the user (me) an opportunity to edit that text so they can select which part to keep. Ideally, it would be something like this:
editedText= raw_input(defaultText)
So, defaultText is printed, the user edits it and presses enter, and the text as they've... | [
"Yes, there is a way. Use readline\nimport readline\n\ndefaultText = 'I am the default value'\nreadline.set_startup_hook(lambda: readline.insert_text(defaultText))\nres = raw_input('Edit this:')\nprint res\n\nNote that this is not a terribly portable solution, and I've only tested it on Linux :)\n"
] | [
4
] | [] | [] | [
"command_line",
"defaults",
"macos",
"python",
"user_input"
] | stackoverflow_0006033903_command_line_defaults_macos_python_user_input.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.