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:
Help: Shifting to ubuntu and opensource from Microsoft stack
I love SO and have been using it for the last 2 years. I've never posted any questions on it (because I found most answers though SO's search).
I have high hopes for this question.
I have been a .NET developer for the last 7-8 years (ASP.NET, ASP.NET MVC... | Help: Shifting to ubuntu and opensource from Microsoft stack | I love SO and have been using it for the last 2 years. I've never posted any questions on it (because I found most answers though SO's search).
I have high hopes for this question.
I have been a .NET developer for the last 7-8 years (ASP.NET, ASP.NET MVC etc) and now i want to learn something new, especially outside Wi... | [
"It's pretty brief, but this is what I'd do:\n\nInstall Ubuntu on my desktop machines, netbooks and laptops and play for a day.\nRead about the philosophy of open-source, what it's all about (it's not just free).\nDo a Python tutorial.\nChoose a webserver technology, the most popular one is probably Apache.\nTurn s... | [
3,
2,
1,
1,
0
] | [] | [] | [
".net",
"open_source",
"python",
"ruby",
"ubuntu"
] | stackoverflow_0003899285_.net_open_source_python_ruby_ubuntu.txt |
Q:
Django's Model fields are defined on the class level?
Maybe my question is little childish. A django model is typically defined like this:
class DummyModel(models.Model):
field1 = models.CharField()
field2 = models.CharField()
As per my understanding, field1 and field2 are defined on the class level inste... | Django's Model fields are defined on the class level? | Maybe my question is little childish. A django model is typically defined like this:
class DummyModel(models.Model):
field1 = models.CharField()
field2 = models.CharField()
As per my understanding, field1 and field2 are defined on the class level instead of instance level. So different instances will share the... | [
"You are correct that normally attributes declared at the class level will be shared between instances. However, Django uses some clever code involving metaclasses to allow each instance to have different values. If you're interested in how this is possible, Marty Alchin's book Pro Django has a good explanation - o... | [
2,
0
] | [] | [] | [
"django",
"field",
"model",
"python"
] | stackoverflow_0003897033_django_field_model_python.txt |
Q:
How do I dump the TCP client's buffer in order to accept more data?
I've got a simple TCP server and client. The client receives data:
received = sock.recv(1024)
It seems trivial, but I can't figure out how to recieve data larger than the buffer. I tried chunking my data and sending it multiple times from the ser... | How do I dump the TCP client's buffer in order to accept more data? | I've got a simple TCP server and client. The client receives data:
received = sock.recv(1024)
It seems trivial, but I can't figure out how to recieve data larger than the buffer. I tried chunking my data and sending it multiple times from the server (worked for UDP), but it just told me that my pipe was broken.
Sugges... | [
"If you have no idea how much data is going to pour over the socket, and you simply want to read everything until the socket closes, then you need to put socket.recv() in a loop:\n# Assumes a blocking socket.\nwhile True:\n data = sock.recv(4096)\n if not data:\n break\n # Do something with `data` h... | [
1,
1,
0
] | [] | [] | [
"python",
"tcp"
] | stackoverflow_0003902757_python_tcp.txt |
Q:
web access by python
i'am looking up for way to enter web site "Login"
i tried this
login_form_seq = [
('user', 'Lick'),
('pass', 'Shot'),
('submit', 'login')]
A=urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
try:
site = opener.open('http://www.SMS-Example.com/user.php', A).re... | web access by python | i'am looking up for way to enter web site "Login"
i tried this
login_form_seq = [
('user', 'Lick'),
('pass', 'Shot'),
('submit', 'login')]
A=urllib.urlencode(login_form_seq)
opener = urllib2.build_opener()
try:
site = opener.open('http://www.SMS-Example.com/user.php', A).read()
site2 = urllib.urlop... | [
"It will depend from site to site and on many site you won't even need a submit value, user/pass should be sufficient and then in many other sites they may have some hidden fields in the login form, so best way is to see the fields in the form you are submitting either directly in html or using some tool like fireb... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003905817_python.txt |
Q:
Why can't I call read() twice on an open file?
For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?
Here's the code
f = f.open()
# get the year
match = re.search(... | Why can't I call read() twice on an open file? | For an exercise I'm doing, I'm trying to read the contents of a given file twice using the read() method. Strangely, when I call it the second time, it doesn't seem to return the file content as a string?
Here's the code
f = f.open()
# get the year
match = re.search(r'Popularity in (\d+)', f.read())
if match:
print... | [
"Calling read() reads through the entire file and leaves the read cursor at the end of the file (with nothing more to read). If you are looking to read a certain number of lines at a time you could use readline(), readlines() or iterate through lines with for line in handle:.\nTo answer your question directly, onc... | [
186,
43,
22,
15,
3,
1
] | [
"I always find the read method something of a walk down a dark alley. You go down a bit and stop but if you are not counting your steps you are not sure how far along you are. Seek gives the solution by repositioning, the other option is Tell which returns the position along the file. May be the Python file api can... | [
-1
] | [
"io",
"python"
] | stackoverflow_0003906137_io_python.txt |
Q:
How to control a frame from another frame?
I'm writing a small app which has 2 separate frames.
The first frame is like a video player controller. It has Play/Stop/Pause buttons etc. It's named controller.py.
The second frame contains OpenGL rendering and many things inside it, but everything is wrapped inside a F... | How to control a frame from another frame? | I'm writing a small app which has 2 separate frames.
The first frame is like a video player controller. It has Play/Stop/Pause buttons etc. It's named controller.py.
The second frame contains OpenGL rendering and many things inside it, but everything is wrapped inside a Frame() class as the above. It's named model.py.
... | [
"Theres not much too it, you create an instance of your model class in your controller and call its methods. So for example when you click the models stop button its handler calls the appropriate method of your model class to stop playback.\nIf you would like your frames to be decoupled somewhat, you could use pub... | [
4,
1
] | [] | [] | [
"frame",
"python",
"send",
"wxpython"
] | stackoverflow_0003898988_frame_python_send_wxpython.txt |
Q:
blender not responding to my accelerometer motion
m using arduino to interact the accelerometer MMA7361L with blender2.49.using python 2.62.
my arduino code is :
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(analogRead(0)/4, BYTE); //x-axis
Serial.print(analogRead(1)/4, BYTE); //y-ax... | blender not responding to my accelerometer motion | m using arduino to interact the accelerometer MMA7361L with blender2.49.using python 2.62.
my arduino code is :
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(analogRead(0)/4, BYTE); //x-axis
Serial.print(analogRead(1)/4, BYTE); //y-axis
Serial.print(analogRead(2)/4, BYTE); //z-axis
... | [
"In your python code, you only read the sensor values coming over a serial port 100 times, which is 4 seconds worth of sensor data at 40 ms per update (according to your processing code). You need to constantly read the sensor values and update scene orientation, so use a while loop like this:\nread_sensors = True\... | [
1,
1
] | [] | [] | [
"arduino",
"blender",
"python"
] | stackoverflow_0003884425_arduino_blender_python.txt |
Q:
Python "strange" output
class Foo(object):
def __init__(self,x):
self.x = x
self.is_bar = False
def __repr__(self): return str(self.x)
class Bar(object):
def __init__(self,l = []):
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
... | Python "strange" output | class Foo(object):
def __init__(self,x):
self.x = x
self.is_bar = False
def __repr__(self): return str(self.x)
class Bar(object):
def __init__(self,l = []):
self.l = l
def add(self,o):
self.l += [o]
def __repr__(self): return str(self.l)
def foo_plus_foo(f1,f2):
... | [
"Never. Do. This.\ndef __init__(self,l = []):\n\nNever.\nOne list object is reused. And it's Mutable, so that each time it's reused, the one and only [] created in your method definition is updated.\nAlways. Do. This.\ndef __init__( self, l= None ):\n if l is None: l = []\n\nThat creates a fresh, new, unique ... | [
5,
4,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003905448_python.txt |
Q:
Disable browser caching in pylons
I'm have an action /json that returns json from the server.
Unfortunately in IE, the browser likes to cache this json.
How can I make it so that this action doesn't cache?
A:
Make sure your response headers have:
Cache-Control: no-cache
Pragma: no-cache
Expires=-1
A:
Make sure... | Disable browser caching in pylons | I'm have an action /json that returns json from the server.
Unfortunately in IE, the browser likes to cache this json.
How can I make it so that this action doesn't cache?
| [
"Make sure your response headers have:\nCache-Control: no-cache\nPragma: no-cache\nExpires=-1\n\n",
"Make sure your responses are not telling the browser that the content expires in the future. There are two HTTP headers the control this.\n\nExpires\nCache-Control - There are many possible values for this header,... | [
3,
2,
1,
1
] | [] | [] | [
"caching",
"internet_explorer",
"pylons",
"python"
] | stackoverflow_0002439987_caching_internet_explorer_pylons_python.txt |
Q:
How to set up global connection to database?
I have problem with setting up database connection. I want to set connection, where I can see this connection in all my controllers.
Now I use something like this in my controller:
db = create_engine('mysql://root:password@localhost/python')
metadata = MetaData(db)
ema... | How to set up global connection to database? | I have problem with setting up database connection. I want to set connection, where I can see this connection in all my controllers.
Now I use something like this in my controller:
db = create_engine('mysql://root:password@localhost/python')
metadata = MetaData(db)
email_list = Table('email',metadata,autoload=True)
I... | [
"I hope you got pylons working; for anyone else that may later read question I'll present some pointers in the right direction.\nFirst of all, you are only creating a engine and a metadata object. While you can use the engine to create connections directly you would almost always use a Session to manage querying an... | [
3,
2,
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002603093_pylons_python_sqlalchemy.txt |
Q:
Simplest way to calculate the width and height of a jpeg image in Python
How can I calculate the width and height of an image in Python?
I'm using the "Image" library already if that makes it easier.
Thanks.
A:
im=Image.open(pic)
print im.size
| Simplest way to calculate the width and height of a jpeg image in Python | How can I calculate the width and height of an image in Python?
I'm using the "Image" library already if that makes it easier.
Thanks.
| [
"im=Image.open(pic) \nprint im.size \n\n"
] | [
5
] | [] | [] | [
"image",
"image_processing",
"python"
] | stackoverflow_0003907360_image_image_processing_python.txt |
Q:
How can I implement a color table with VTK / TK in python
I'm developing an application in VTK / TK and I was wondering what's the best way to provide the user with a table which lists items and allow the user to pick the color for each item:
item1 | color
item2 | color
item3 | color
thanks
A:
I would create a ... | How can I implement a color table with VTK / TK in python | I'm developing an application in VTK / TK and I was wondering what's the best way to provide the user with a table which lists items and allow the user to pick the color for each item:
item1 | color
item2 | color
item3 | color
thanks
| [
"I would create a frame, then write a loop that creates a label widget and a button for each item. The background of the button would be the current color. There needs not be any text on the button, just make it square. The button would call a method that calls tk_chooseColor to get a color from the user. \n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003907123_python_tkinter.txt |
Q:
Python - PIL - Missing images
Trying to use pil for creating grid-like layout from images. But that code only draws first column. Can anyone help me?
def draw(self):
image=Image.new("RGB",((IMAGE_SIZE[0]+40)*5+40,(IMAGE_SIZE[1]+20)*CHILD_COUNT+20),(255,255,255))
paste_x=(-1)*IMAGE_SIZE[0]
paste_y=(-1)*... | Python - PIL - Missing images | Trying to use pil for creating grid-like layout from images. But that code only draws first column. Can anyone help me?
def draw(self):
image=Image.new("RGB",((IMAGE_SIZE[0]+40)*5+40,(IMAGE_SIZE[1]+20)*CHILD_COUNT+20),(255,255,255))
paste_x=(-1)*IMAGE_SIZE[0]
paste_y=(-1)*IMAGE_SIZE[1]
i=0
for a ran... | [
"Use itertools.product to iterate over the rows and columns:\nimport tempfile\nimport Image\nimport itertools\n\nCOLUMNS=5\nROWS=5\nVSEP=20\nHSEP=40\nIMAGE_SIZE=(100,100)\n\ndef draw():\n image=Image.new(\"RGB\",\n ((IMAGE_SIZE[0]+HSEP)*COLUMNS+HSEP,\n (IMAGE_SIZE[1]+VSEP)*... | [
3
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0003907443_python_python_imaging_library.txt |
Q:
Error "AttributeError: 'unicode' object has no attribute 'read'" on file upload
I'm using Pylons to upload an image and store it to disk:
<form method="post">
<input type="file" name="picture" enctype="multipart/form-data" />
</form>
Then in my controller:
if 'picture' in request.POST:
i = ImageHandler(... | Error "AttributeError: 'unicode' object has no attribute 'read'" on file upload | I'm using Pylons to upload an image and store it to disk:
<form method="post">
<input type="file" name="picture" enctype="multipart/form-data" />
</form>
Then in my controller:
if 'picture' in request.POST:
i = ImageHandler()
#Returns full path of image file
picture_file = i.makePath()
shuti... | [
"Both arguments to copyfileobj are now strings, while that functions takes files (or \"file-like objects\") as arguments. Do something like\n picture_file = open(i.makePath(), 'w')\n\n(or just picture_file = i, not sure what your ImageHandler class is like), then\n shutil.copyfileobj(request.POST['picture'].file, p... | [
3
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003907832_pylons_python.txt |
Q:
How to upload a file on FTPS server using m2crypto
I am trying to use ftps to upload file to our FTP server. Login is trivial and works:
from M2Crypto import ftpslib
ftp = ftpslib.FTP_TLS()
ftp.connect(host)
ftp.login(username, password)
as well as descending into directory
for dir in directory:
ftp.cwd(dir)
... | How to upload a file on FTPS server using m2crypto | I am trying to use ftps to upload file to our FTP server. Login is trivial and works:
from M2Crypto import ftpslib
ftp = ftpslib.FTP_TLS()
ftp.connect(host)
ftp.login(username, password)
as well as descending into directory
for dir in directory:
ftp.cwd(dir)
However, when trying to retrieve directory content:
if ... | [
"Solution is to explicitly call for protected transfer after login():\nftp.prot_p()\n\n"
] | [
4
] | [] | [] | [
"ftp",
"m2crypto",
"python",
"ssl"
] | stackoverflow_0003907826_ftp_m2crypto_python_ssl.txt |
Q:
URL rewriting question
I have a CGI script (pwyky) that I called index.cgi, put in directory wiki/, and setup Apache to call localhost/wiki/index.cgi when I access localhost/wiki.
I'm getting errors when I'm trying to use this application -- it creates a page with links like "http://localhost/wiki/@edit/index", bu... | URL rewriting question | I have a CGI script (pwyky) that I called index.cgi, put in directory wiki/, and setup Apache to call localhost/wiki/index.cgi when I access localhost/wiki.
I'm getting errors when I'm trying to use this application -- it creates a page with links like "http://localhost/wiki/@edit/index", but when I click that link, Ap... | [
"You'd need to show your apache configuration to say for certain, but it seems that Apache isn't actually using mod_cgi to serve the index.cgi script. In your configuration there should be something like 'LoadModule mod_cgi'. It should be uncommented (i.e., it shouldn't have a '#' at the beginning of the line). \nI... | [
0,
0
] | [] | [] | [
"apache",
"python"
] | stackoverflow_0003897140_apache_python.txt |
Q:
Can I use IronPython to develop GUIs for Google App Engine?
I'm developing a simple Python program with a (dynamic) form interface, but it needs to run on Google App Engine. I understand that IronPython lets one use Visual Studio's drag-and-drop interface builder and classes while programming with Python, but will... | Can I use IronPython to develop GUIs for Google App Engine? | I'm developing a simple Python program with a (dynamic) form interface, but it needs to run on Google App Engine. I understand that IronPython lets one use Visual Studio's drag-and-drop interface builder and classes while programming with Python, but will this be compatible with Google App Engine?
| [
"Google's Google App Engine can only run pure python code, and not even all Python is supported. No, you can't do things like IronPython.\nIf you want to use Python, I'd learn Django. If you want something closer to .NET, I'd go with Java.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"ironpython",
"python",
"user_interface"
] | stackoverflow_0003908062_google_app_engine_ironpython_python_user_interface.txt |
Q:
In Python + Pylons, simple way to copy uploaded file to disk
How can I copy a posted file to disk?
Can I do something like:
file = '/uploaded_files/test.txt'
shutil.copy2(request.POST['file'],file)
Thanks.
A:
You do something like this:
tempfile = request.POST['file']
file_path = 'uploaded_files/' + tempfile.fi... | In Python + Pylons, simple way to copy uploaded file to disk | How can I copy a posted file to disk?
Can I do something like:
file = '/uploaded_files/test.txt'
shutil.copy2(request.POST['file'],file)
Thanks.
| [
"You do something like this:\ntempfile = request.POST['file']\nfile_path = 'uploaded_files/' + tempfile.filename # for the original filename\npermanent_file = open( file_path, 'wb')\nshutil.copyfileobj(tempfile.file, permanent_file)\n\n"
] | [
1
] | [] | [] | [
"pylons",
"python"
] | stackoverflow_0003907611_pylons_python.txt |
Q:
Non-binary(hex) characters in string received over TCP with Python
maybe this is a noob question, but I'm receiving some data over TCP and when I look at the string I get the following:
\x00\r\xeb\x00\x00\x00\x00\x01t\x00
What is that \r character, and what does the t in \x01t mean?
I've tried Googling, but I'm no... | Non-binary(hex) characters in string received over TCP with Python | maybe this is a noob question, but I'm receiving some data over TCP and when I look at the string I get the following:
\x00\r\xeb\x00\x00\x00\x00\x01t\x00
What is that \r character, and what does the t in \x01t mean?
I've tried Googling, but I'm not sure what to Google for...
thanks.
| [
"\\r is a carriage return (0x0d), the t is a t.\n",
"Viewing binary data in strings can sometimes be confusing, especially if they're long, but you can always convert it to some easier-to-read hex.\n>>> data = '\\x00\\r\\xeb\\x00\\x00\\x00\\x00\\x01t\\x00'\n>>> ' '.join([\"%02X\" % ord(char) for char in data])\n'... | [
9,
4,
2
] | [] | [] | [
"bit",
"character",
"networking",
"python"
] | stackoverflow_0003906903_bit_character_networking_python.txt |
Q:
error message when populating cell in 2d numpy array
I am trying to populate data from some csv files into a numpy array with the following code:
PreExArray=zeros([len(TestIDs),numColumns],float)
for row in reader:
if row[1] =='PreEx10SecondsBEFORE':
PreExArray[(j-1),0]=[row[2]]
However, the last lin... | error message when populating cell in 2d numpy array | I am trying to populate data from some csv files into a numpy array with the following code:
PreExArray=zeros([len(TestIDs),numColumns],float)
for row in reader:
if row[1] =='PreEx10SecondsBEFORE':
PreExArray[(j-1),0]=[row[2]]
However, the last line of code above throws the following error:
ValueError: se... | [
"You should just have:\nPreExArray[(j-1),0]=row[2]\n\nThat is, the right hand side should NOT be put into a length-1 list.\n",
"It looks like your row variables are from a spreadsheet, and the first index values are row labels (strings). As has been pointed out, you cannot store this data in a numpy array of data... | [
1,
0
] | [] | [] | [
"2d",
"arrays",
"numpy",
"python"
] | stackoverflow_0003902977_2d_arrays_numpy_python.txt |
Q:
Django Monthly/quartarly grouping of DateField() data
I've got a django model which contains, among other things, a DateField() attribute:
class Table():
date = models.DateField()
value = models.FloatField()
I'm writing a view that groups this data by week, month Quarter and year.
I've hardcoded a calcula... | Django Monthly/quartarly grouping of DateField() data | I've got a django model which contains, among other things, a DateField() attribute:
class Table():
date = models.DateField()
value = models.FloatField()
I'm writing a view that groups this data by week, month Quarter and year.
I've hardcoded a calculation that gets my monthly value simply enough - by adding u... | [
"You can do this using the model's query capabilities.\nHere's an example for the monthly query:\nfrom django.db.models import Avg\nTable.objects.extra(select={'month':\"strftime('%m',date)\"}).values('month').annotate(Avg('value'))\n\nWhere you may want to change strftime('%m',date) with month(date) or any other c... | [
3
] | [] | [] | [
"datefield",
"django",
"django_models",
"python"
] | stackoverflow_0003907240_datefield_django_django_models_python.txt |
Q:
Sending data to django server from a non-django server
I am making a bookmarklet where I need people to login first. My question is how do I send login credentials to the django server from a different domain?
I was thinking there were a couple ways, since I can't use send data via request.
Generate the sha1 algo... | Sending data to django server from a non-django server | I am making a bookmarklet where I need people to login first. My question is how do I send login credentials to the django server from a different domain?
I was thinking there were a couple ways, since I can't use send data via request.
Generate the sha1 algo on the client-side...but then how do I know what Django is ... | [
"You can send the POST data (via SSL of course) to your Django site. Your view will handle the request. If you post to that view, you can authenticate using django.contrib.auth methods. The following was taken from http://docs.djangoproject.com/en/dev/topics/auth/\nif request.method == 'POST':\n username = re... | [
1
] | [] | [] | [
"bookmarklet",
"django",
"javascript",
"python"
] | stackoverflow_0003908523_bookmarklet_django_javascript_python.txt |
Q:
Python: Google Checkout Signature Function
I am attempting to integrate Google Checkout into my website. I have created the following function for generating the hmac-sha-1 signature requred:
def make_signature(cart_xml):
import hmac
import hashlib
import base64
# The number is a psuedo-merchantID... | Python: Google Checkout Signature Function | I am attempting to integrate Google Checkout into my website. I have created the following function for generating the hmac-sha-1 signature requred:
def make_signature(cart_xml):
import hmac
import hashlib
import base64
# The number is a psuedo-merchantID, cart_xml contains a string with the
# shop... | [
"Figured it out. I was using the Merchant ID instead of the Merchant Key.\n"
] | [
0
] | [] | [] | [
"google_checkout",
"payment_gateway",
"python"
] | stackoverflow_0003902667_google_checkout_payment_gateway_python.txt |
Q:
Check if Session Key is set
I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving... | Check if Session Key is set | I am attempting to create a relatively simple shopping cart in Django. I am storing the cart in request.session['cart']. Therefore, I'll need to access the data in this session when anything is added to it. However, if the session is not already set, I cannot access it without receiving an error. Is there any way to ch... | [
"I assume that you want to check if a key is set in session, not if a session is set (don't know what the latter means). If so:\nYou can do:\nif key not in request.session:\n # Set it.\n\nIn your case:\nif 'cart' not in request.session:\n # Set it.\n\nEDIT: changed the code snippet to use key not in rather th... | [
53,
19
] | [] | [] | [
"django",
"django_sessions",
"python"
] | stackoverflow_0003908761_django_django_sessions_python.txt |
Q:
Why are CherryPy object attributes persistent between requests?
I was writing debugging methods for my CherryPy application. The code in question was (very) basically equivalent to this:
import cherrypy
class Page:
def index(self):
try:
self.body += 'okay'
except AttributeError:
... | Why are CherryPy object attributes persistent between requests? | I was writing debugging methods for my CherryPy application. The code in question was (very) basically equivalent to this:
import cherrypy
class Page:
def index(self):
try:
self.body += 'okay'
except AttributeError:
self.body = 'okay'
return self.body
index.expos... | [
"You hit the nail on the head with the observation that you're getting the same data from self.body because it's the same in memory of the Python process running CherryPy.\nself.debug maintains 'state' for this reason, it's an attribute of the running server.\nTo set data for the current session, use cherrypy.sessi... | [
5,
5
] | [] | [] | [
"cherrypy",
"persistent",
"python",
"request"
] | stackoverflow_0003898482_cherrypy_persistent_python_request.txt |
Q:
python regex question
What is the correct regex statement using re.search() to find and return a file extension in a string.
Such as:
(.+).(avi|rar|zip|txt)
I need it to search a string and if it contains any of those avi, rar, etc) return just that extension.
Thanks!
EDIT: should add that is needs to be case inse... | python regex question | What is the correct regex statement using re.search() to find and return a file extension in a string.
Such as:
(.+).(avi|rar|zip|txt)
I need it to search a string and if it contains any of those avi, rar, etc) return just that extension.
Thanks!
EDIT: should add that is needs to be case insensitive
| [
"the standard library is better ;) \n>>> os.path.splitext('hello.py')\n('hello', '.py')\n\n",
"You need:\n(.)\\.(avi|rar|zip|txt)$\n\nNote the backslash to escape the dot. This will make it look for a literal dot rather than any character.\nTo make it case insensitive, use the RE.I flag in your search call.\nre.s... | [
8,
6,
1,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003908727_python_regex.txt |
Q:
combination of coverage and profiler?
I really like the python coverage module:
http://nedbatchelder.com/code/coverage/
and the HTML pages it generates. Is there a combination of this and profiling so that one could see a unified HTML report of coverage+profiling.
Thanks in advance.
A:
Thanks, reckoner, glad th... | combination of coverage and profiler? | I really like the python coverage module:
http://nedbatchelder.com/code/coverage/
and the HTML pages it generates. Is there a combination of this and profiling so that one could see a unified HTML report of coverage+profiling.
Thanks in advance.
| [
"Thanks, reckoner, glad that you like the HTML output from coverage. I've never done anything to combine it with a profiler, and haven't heard of anyone else doing it either.\nWhen I created the HTML output, I had in the back of my mind the idea of having it be a generalized source-code-with-tool-annotations facil... | [
4
] | [] | [] | [
"code_coverage",
"profiling",
"python"
] | stackoverflow_0003907923_code_coverage_profiling_python.txt |
Q:
Handling graceful degradation within a Django form
I have a form that looks similar to the following (simplified for brevity):
PRICING_PATTERN = r'(?:^\$?(?P<flat_price>\d+|\d?\.\d\d)$)|(?:^(?P<percent_off>\d+)\s*\%\s*off$)'
class ItemForm(forms.Form):
pricing = forms.RegexField(
label='Pricing',
... | Handling graceful degradation within a Django form | I have a form that looks similar to the following (simplified for brevity):
PRICING_PATTERN = r'(?:^\$?(?P<flat_price>\d+|\d?\.\d\d)$)|(?:^(?P<percent_off>\d+)\s*\%\s*off$)'
class ItemForm(forms.Form):
pricing = forms.RegexField(
label='Pricing',
regex=PRICING_PATTERN
)
pricing_type = forms... | [
"Define a custom widget for the type selection and include the JavaScript code as a separate .js file.\n"
] | [
1
] | [] | [] | [
"django_forms",
"graceful_degradation",
"python"
] | stackoverflow_0003909564_django_forms_graceful_degradation_python.txt |
Q:
Jython test coverage
I'm trying to use Jython instead of Python for a project (want jdbc driver for a sort of rare database).
Everything is working OK so far, but I can't find any good tools for code coverage. Does anyone have a solution to this?
The googling I've done seems to indicate that jython is missing some... | Jython test coverage | I'm trying to use Jython instead of Python for a project (want jdbc driver for a sort of rare database).
Everything is working OK so far, but I can't find any good tools for code coverage. Does anyone have a solution to this?
The googling I've done seems to indicate that jython is missing some things that code coverage... | [
"How do others solve this?\nYour question is fundamentally, \"how can I get tools for languages that don't have built-in tool support?\" The hypermodern solution for programming langauges is to try to build in all the necessary support into the particular langauge implementations (reflection, profiling, metaprog... | [
1,
1
] | [] | [] | [
"code_coverage",
"jython",
"python"
] | stackoverflow_0003902350_code_coverage_jython_python.txt |
Q:
MEDIA_URL tuple
I would like to write a context_processor, something like this:
settings.py:
MEDIA_URLS = ('cname2.example.com/media', 'cname3.example.com/media',)
TEMPLATE_CONTEXT_PROCESSORS = (
"util.context_processors.media",
)
util/context_processors.py
from random import choice
from django.conf import se... | MEDIA_URL tuple | I would like to write a context_processor, something like this:
settings.py:
MEDIA_URLS = ('cname2.example.com/media', 'cname3.example.com/media',)
TEMPLATE_CONTEXT_PROCESSORS = (
"util.context_processors.media",
)
util/context_processors.py
from random import choice
from django.conf import settings
def media(req... | [
"Like so, although the exact routine to select the next element is up to you.\n"
] | [
1
] | [] | [] | [
"django",
"optimization",
"python"
] | stackoverflow_0003909644_django_optimization_python.txt |
Q:
VoIP in Python then http
Hello there
i wanted to know if it was possible to make a voip script in python and then if it works integrate it online on my web site
thanks a bunch
A:
you are very vague if you ask me.
I guess it is possible because there are SIP libraries in python.
| VoIP in Python then http | Hello there
i wanted to know if it was possible to make a voip script in python and then if it works integrate it online on my web site
thanks a bunch
| [
"you are very vague if you ask me.\nI guess it is possible because there are SIP libraries in python.\n"
] | [
2
] | [] | [] | [
"php",
"python",
"voice",
"voip"
] | stackoverflow_0003907721_php_python_voice_voip.txt |
Q:
Calculating sliding averages
I'm not even sure what sliding average is, but someone told me it would help with something I'm working on.
I have a table of random values -- table[n] = random(100) / 100
I need to populate table2 with their sliding averages.
I think this is the terminology. Let me know if it doesn't... | Calculating sliding averages | I'm not even sure what sliding average is, but someone told me it would help with something I'm working on.
I have a table of random values -- table[n] = random(100) / 100
I need to populate table2 with their sliding averages.
I think this is the terminology. Let me know if it doesn't make sense.
| [
"The Moving average entry on Wikipedia might be a good start.\n",
"\"Sliding Average\" is another term for \"Moving Average\" AKA \"Boxcar Average\". \nAll are a form of Smoothing the data. \n"
] | [
7,
2
] | [] | [] | [
"c",
"javascript",
"python",
"sliding"
] | stackoverflow_0003909487_c_javascript_python_sliding.txt |
Q:
What's the easiest way to add commas to an integer?
Possible Duplicate:
How to print number with commas as thousands separators?
For example:
>> print numberFormat(1234)
>> 1,234
Or is there a built-in function in Python that does this?
A:
No one so far has mentioned the new ',' option which was added in vers... | What's the easiest way to add commas to an integer? |
Possible Duplicate:
How to print number with commas as thousands separators?
For example:
>> print numberFormat(1234)
>> 1,234
Or is there a built-in function in Python that does this?
| [
"No one so far has mentioned the new ',' option which was added in version 2.7 to the Format Specification Mini-Language -- see PEP 378: Format Specifier for Thousands Separator in the What's New in Python 2.7 document. It's easy to use because you don't have to mess around with locale (but is limited for internati... | [
102,
13,
12,
5
] | [] | [] | [
"number_formatting",
"python"
] | stackoverflow_0003909457_number_formatting_python.txt |
Q:
Django - Form widget with a checkbox to choose between unlimited or a textbox for a number
I am making a form in Django. The field to display is a numeric field representing some limit. It's possible for there to be no limit. Rather than force the user to enter some strange number to mean unlimited (e.g. -1), I'd ... | Django - Form widget with a checkbox to choose between unlimited or a textbox for a number | I am making a form in Django. The field to display is a numeric field representing some limit. It's possible for there to be no limit. Rather than force the user to enter some strange number to mean unlimited (e.g. -1), I'd like there to be a radio button, with 2 options: "Unlimited" and the second option being a text ... | [
"You can either make the form have an additional form field for the checkbox. And override it's save method to fill the model fields accordingly. Or you can make a custom form field widget that would hold both HTML input fields and produce the appropriate python value from the inputs and vice versa. The first optio... | [
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003904809_django_django_forms_python.txt |
Q:
OCSP command-line test tool?
Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program
A:
Looking a bit more, I think I've found some answers:
a) OpenSSL at the rescue:
openssl ocsp -whatever
F... | OCSP command-line test tool? | Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program
| [
"Looking a bit more, I think I've found some answers:\na) OpenSSL at the rescue:\nopenssl ocsp -whatever\n\nFor more info, http://www.openssl.org/docs/apps/ocsp.html\nb) http://www.openvalidation.org/ is another way of testing a cert. And via its links, I got to:\n\nhttp://security.polito.it/tools/ocsp/\nAscertia O... | [
4,
1,
1,
1,
0
] | [] | [] | [
"command_line",
"java",
"ocsp",
"python"
] | stackoverflow_0000071468_command_line_java_ocsp_python.txt |
Q:
How to generate a predictable shuffling of a sequence without generating the whole sequence in advance?
The following python code describes exactly what I want to achieve for a sequence of arbitrary size (population):
import random
fixed_seed = 1 #generate the same sequence every time with a fixed seed
population ... | How to generate a predictable shuffling of a sequence without generating the whole sequence in advance? | The following python code describes exactly what I want to achieve for a sequence of arbitrary size (population):
import random
fixed_seed = 1 #generate the same sequence every time with a fixed seed
population = 1000
sample_count = 5 #demonstration number
num_retries = 3 #just enough to show the repeatable behaviour
... | [
"I've actually written about this before: Secure Permutations with Block Ciphers. In a nutshell:\n\nYes, you can use an LFSR to generate permutations with a length that's a power of 2. You can also use any block cipher. With a block cipher, you can also find the element at index n, or the index for element n.\nTo g... | [
4,
1
] | [] | [] | [
"algorithm",
"lcg",
"python",
"random"
] | stackoverflow_0003910101_algorithm_lcg_python_random.txt |
Q:
sandbox to execute possibly unfriendly python code
Let's say there is a server on the internet that one can send a piece of code to for evaluation. At some point server takes all code that has been submitted, and starts running and evaluating it. However, at some point it will definitely bump into "os.system('rm -... | sandbox to execute possibly unfriendly python code | Let's say there is a server on the internet that one can send a piece of code to for evaluation. At some point server takes all code that has been submitted, and starts running and evaluating it. However, at some point it will definitely bump into "os.system('rm -rf *')" sent by some evil programmer. Apart from "rm -rf... | [
"If you are not specific to CPython implementation, you should consider looking at PyPy[wiki] for these purposes — this Python dialect allows transparent code sandboxing.\nOtherwise, you can provide fake __builtin__ and __builtins__ in the corresponding globals/locals arguments to exec or eval.\nMoreover, you can p... | [
6,
2,
2,
2,
1,
0,
0
] | [] | [] | [
"python",
"trusted_vs_untrusted"
] | stackoverflow_0003910223_python_trusted_vs_untrusted.txt |
Q:
m2crypto: python 2.7 compatibility and which version of OpenSSL to use?
We've been using M2crypto with Python 2.6 for Windows (32-bit) for some time with great success. We used one of the user contributed setups to install M2crypto in our development environments. We would like to move to Python 2.7, but noticed t... | m2crypto: python 2.7 compatibility and which version of OpenSSL to use? | We've been using M2crypto with Python 2.6 for Windows (32-bit) for some time with great success. We used one of the user contributed setups to install M2crypto in our development environments. We would like to move to Python 2.7, but noticed there are no pre-built Python 2.7 setups for m2crypto.
Questions:
Is M2crypto... | [
"Yes, it's compatible with Python 2.7, so you can freely upgrade if you have not already.\nYes, here you have bdist_wininst, bdist_egg and bdist for M2Crypto 20.2 built for Python 2.7 with MSVS2008 by me, hope it will fit your needs.\nNo, you will get import error, as .pyd file (which is actually DLL) has python26.... | [
3
] | [] | [] | [
"m2crypto",
"openssl",
"python",
"python_2.7"
] | stackoverflow_0003857450_m2crypto_openssl_python_python_2.7.txt |
Q:
Pass data between objects in python
I'm new to python and I'm not sure how to pass data between objects. Below is a tabbed program using python and wxwidgets. How would I be able to access the maintxt instance from the GetText method since their in different classes?
Thanks.
........
#!/usr/bin/env python
import w... | Pass data between objects in python | I'm new to python and I'm not sure how to pass data between objects. Below is a tabbed program using python and wxwidgets. How would I be able to access the maintxt instance from the GetText method since their in different classes?
Thanks.
........
#!/usr/bin/env python
import wx
class PageText(wx.Panel):
def __i... | [
"It sounds like you might be mixing logic with presentation. You should perhaps have a network of model classes that describe the behaviors of your domain (pages?) and then pass instances of those classes to the initializers of your presentation classes, so they know which models they are representing.\nMore about... | [
4
] | [] | [] | [
"class",
"pass_by_reference",
"python"
] | stackoverflow_0003911259_class_pass_by_reference_python.txt |
Q:
Python, format this list
I've got a list like
[(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
I want to make it looks like
[('1',' ', '2', '8'), ('2', ' ', '3', '7', '8', '9'), ('3', " ", '2', '5', '6', '7', '7', '9')]
How can I code this loop? Really tried ... | Python, format this list | I've got a list like
[(1, 2), (1, 8), (2, 3), (2, 7), (2, 8), (2, 9), (3, 1), (3, 2), (3, 5), (3, 6), (3, 7), (3, 7), (3, 9)]
I want to make it looks like
[('1',' ', '2', '8'), ('2', ' ', '3', '7', '8', '9'), ('3', " ", '2', '5', '6', '7', '7', '9')]
How can I code this loop? Really tried times, and nothing came up. Pl... | [
"Step 1. Convert the list to a dictionary. Each element is a list of values with a common key. (Hint: The key is the first value of each pair)\nStep 2. Now format each dictionary as key, space, value list.\n",
"Not exactly what you asked for, but maybe easier to work with?\n>>> from itertools import groupby\n... | [
2,
2,
2,
0
] | [] | [] | [
"formatting",
"list",
"python"
] | stackoverflow_0003911319_formatting_list_python.txt |
Q:
Looping over a Python / IronPython Object Methods
What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
A:
You can use the inspect module to get class (or ins... | Looping over a Python / IronPython Object Methods | What is the proper way to loop over a Python object's methods and call them?
Given the object:
class SomeTest():
def something1(self):
print "something 1"
def something2(self):
print "something 2"
| [
"You can use the inspect module to get class (or instance) members:\n>>> class C(object):\n... a = 'blah'\n... def b(self):\n... pass\n... \n...\n>>> c = C()\n>>> inspect.getmembers(c, inspect.ismethod)\n[('b', <bound method C.b of <__main__.C object at 0x100498250>>)]\n\ngetmembers() returns a ... | [
10,
4,
0
] | [
"Edit\nDaniel, you are wrong.\nhttp://docs.python.org/reference/datamodel.html\n\nUser-defined methods\nA user-defined method object combines a class, a class instance (or\nNone) and any callable object (normally a user-defined function).\n\nTherefore, anything that defines __call__ and is attached to an object is ... | [
-1
] | [
"introspection",
"ironpython",
"python",
"python_datamodel",
"reflection"
] | stackoverflow_0000928990_introspection_ironpython_python_python_datamodel_reflection.txt |
Q:
How does CherryPy caching work?
I recently discovered that page object attributes in CherryPy are persistent between requests (and between clients). So I'm wondering, would it make sense to store page output in such an attribute? Like this:
class Page:
def default(self, pagenumber):
if pagenumber not i... | How does CherryPy caching work? | I recently discovered that page object attributes in CherryPy are persistent between requests (and between clients). So I'm wondering, would it make sense to store page output in such an attribute? Like this:
class Page:
def default(self, pagenumber):
if pagenumber not in self.validpages:
return... | [
"CherryPy does not cache GET requests by default; you have to explicitly turn on the caching tool as described in that documentation.\nTo answer your first question, yes, it's perfectly valid to store things like \"pageoutput\" that do not change between calls. However, there are a couple of caveats:\n\nHTTP cachin... | [
4
] | [] | [] | [
"caching",
"cherrypy",
"get",
"python"
] | stackoverflow_0003908577_caching_cherrypy_get_python.txt |
Q:
What have i done wrong? (python help)
The question i'm working on asks me to "write an expression whose value is the concatenation of the three str values associated with name1 , name2 , and name3" , separated by commas."
"So if name1 , name2 , and name3 , were (respectively) "Neville", "Dean", and "Seamus"... | What have i done wrong? (python help) | The question i'm working on asks me to "write an expression whose value is the concatenation of the three str values associated with name1 , name2 , and name3" , separated by commas."
"So if name1 , name2 , and name3 , were (respectively) "Neville", "Dean", and "Seamus", your expression's value would be "Neville... | [
"Homework? Did you submit the result of the expression, or the expression itself?\n\",\".join([name1, name2, name3])\nOr whatever you used?\nEdit: You mention that you submitted (\"name1\", \"name2\", \"name3\") - which would not return the concatenated names - but rather those stings. If you wanted to do it like ... | [
3
] | [] | [] | [
"python",
"string_concatenation"
] | stackoverflow_0003911519_python_string_concatenation.txt |
Q:
Python: What is the recommended way to set configuration settings for a module when you import it?
I've seen people use monkey-patching to set options on a module, for example:
import mymodule
mymodule.default_img = "/my/file.png"
mymodule.view_default_img()
And Django, for example, has settings.py for the ... | Python: What is the recommended way to set configuration settings for a module when you import it? | I've seen people use monkey-patching to set options on a module, for example:
import mymodule
mymodule.default_img = "/my/file.png"
mymodule.view_default_img()
And Django, for example, has settings.py for the entire Django app, and it always grates on me a little.
What are the other ways to manage configuration ... | [
"One option is the ConfigParser module. You could have the settings in a non-python config file and have each module read its settings out of that. Another option is to have a config method in each module that the client code can pass it's arguments too.\n# foo.py\nsetting1 = 0\nsetting2 = 'foo'\n\ndef configure(co... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003911539_python.txt |
Q:
Can someone please explain to me
.. the difference between the = and the == signs in Python? i.e provide examples when each is used so there's no confusion between the two?
A:
= is used to assign variables ie number = 30 - the "number" variable now holds the number 30.
== is used as a boolean operator to check w... | Can someone please explain to me | .. the difference between the = and the == signs in Python? i.e provide examples when each is used so there's no confusion between the two?
| [
"= is used to assign variables ie number = 30 - the \"number\" variable now holds the number 30.\n== is used as a boolean operator to check whether variables are equal to each other ie 1 == 1 would give true and 1 == 2 would return false\n",
"= is assignment, == is equality.\na = 5 # assigns the variable a to 5\... | [
3,
1,
0,
0
] | [] | [] | [
"operators",
"python"
] | stackoverflow_0003911726_operators_python.txt |
Q:
python - nested try/except question
try:
for i in list:
try:
#python code...
except Exception,e:
#error handler
except Exception, e:
#error handler
If in the nested try/except it errors out, does the loop continue running?
A:
Yes, it does, since you caught the exc... | python - nested try/except question | try:
for i in list:
try:
#python code...
except Exception,e:
#error handler
except Exception, e:
#error handler
If in the nested try/except it errors out, does the loop continue running?
| [
"Yes, it does, since you caught the exception. Although if you just have a comment there and not a real line of code, I think Python may complain. (I haven't written Python code in a while.)\n",
"Aside from the typo for \"cexcept\" in the inner except, the loop should continue. Actually, the parent try/except can... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003911823_python.txt |
Q:
How to return the maximum element of a slice of a list
I am trying to simplify this function at his maximum, how can I do?
def eleMax(items, start=0, end=None):
if end is None:
end = len(items)
return max(items[start:end])
I thought of
def eleMax(items, start=0, end=-1):
return max(items[star... | How to return the maximum element of a slice of a list | I am trying to simplify this function at his maximum, how can I do?
def eleMax(items, start=0, end=None):
if end is None:
end = len(items)
return max(items[start:end])
I thought of
def eleMax(items, start=0, end=-1):
return max(items[start:end])
But the last element is deleted from the list.
| [
"You can just remove these two lines:\nif end is None:\n end = len(items)\n\nThe function will work exactly the same:\n>>> a=[5,4,3,2,1]\n>>> def eleMax(items, start=0, end=None):\n... return max(items[start:end])\n...\n>>> eleMax(a,2) # a[2:] == [3,2,1]\n3\n\n",
"Just use max(items).\nPython ranges are ... | [
4,
2,
2,
1
] | [] | [] | [
"max",
"python",
"slice"
] | stackoverflow_0003892957_max_python_slice.txt |
Q:
Set cellrenderertext foreground color when a row is highlighted
When I have a gtk.CellRendererText, I can associate its foreground color with one of the tree store's columns, and set the foreground-set attribute to True, to change the color of the text in that column. However, when the row with the colored column ... | Set cellrenderertext foreground color when a row is highlighted | When I have a gtk.CellRendererText, I can associate its foreground color with one of the tree store's columns, and set the foreground-set attribute to True, to change the color of the text in that column. However, when the row with the colored column is selected, its color disappears, and is the same as any selected ce... | [
"I've had the same problem and, after trying different alternatives, using the markup property instead of the text property solved the problem. Please find below and example that works in Ubuntu Maverick:\n#!/usr/bin/python \nimport gtk\n\n\nclass Application(object):\n def __init__... | [
7
] | [] | [] | [
"cellrenderer",
"gtk",
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003629386_cellrenderer_gtk_gtktreeview_pygtk_python.txt |
Q:
Issue happens when installing Django on Windows 7
I've got an issue when installing Django.
The official guide says open cmd with administrator privileges and run "setup.py install"
I did this but then the system default python editor came out, I don't know how to do anymore, please help me~
A:
It is very like... | Issue happens when installing Django on Windows 7 | I've got an issue when installing Django.
The official guide says open cmd with administrator privileges and run "setup.py install"
I did this but then the system default python editor came out, I don't know how to do anymore, please help me~
| [
"It is very likely that the py extension is linked with the editor rather than the Python interpreter.\nRight-click on a py file and click \"Open with\" then select the default program and choose 'C:...\\Python2x\\python.exe'\nThat should fix the pb\n"
] | [
2
] | [] | [] | [
"django",
"installation",
"python"
] | stackoverflow_0003912579_django_installation_python.txt |
Q:
Apache Can't Access Django Applications
so here's the setting:
The whole site is working fine if I remove the application (whose name
is myapp) in the INSTALLED_APPS section in the settings file I added WSGIPythonHome in apache2.conf
I can successfully access the apps via the the interactive python shell in Dj... | Apache Can't Access Django Applications | so here's the setting:
The whole site is working fine if I remove the application (whose name
is myapp) in the INSTALLED_APPS section in the settings file I added WSGIPythonHome in apache2.conf
I can successfully access the apps via the the interactive python shell in Django (python manage.py shell). I can create, ... | [
"Append /home/ygamretuta/dev/site1 to sys.path.\n"
] | [
6
] | [] | [] | [
"django",
"mod_wsgi",
"python",
"virtualenv"
] | stackoverflow_0003912670_django_mod_wsgi_python_virtualenv.txt |
Q:
Python Pyrad dictionary error
I setup some RADIUS backend to allow AD authentication via the 'admin' of django. Alltough i got a problem with some dictionaries, i really don't know what i'm doing wrong. This is the error i got:
IOError at /admin/
Errno 2] No such file or directory: '/home/pl/dictionary.compat'
I i... | Python Pyrad dictionary error | I setup some RADIUS backend to allow AD authentication via the 'admin' of django. Alltough i got a problem with some dictionaries, i really don't know what i'm doing wrong. This is the error i got:
IOError at /admin/
Errno 2] No such file or directory: '/home/pl/dictionary.compat'
I installed pyrad, so it should be the... | [
"The $INCLUDE directive in the configuration files is intended to add definitions from another dictionary file. Unless the extra dictionary files are found, the dictionary object cannot be created.\nMy advice is:\n- if you don't have the extra dictionary files: comment out/remove the $INCLUDE lines \n- if you have ... | [
0
] | [] | [] | [
"python",
"radius"
] | stackoverflow_0003912740_python_radius.txt |
Q:
Get filename when using urllib.urlopen
I'm using urllib.urlopen to read a file from a URL. What is the best way to get the filename? Do servers always return the Content-Disposition header?
Thanks.
A:
It's an optional header, so no. See if it exists, and if not then fall back to checking the URL.
| Get filename when using urllib.urlopen | I'm using urllib.urlopen to read a file from a URL. What is the best way to get the filename? Do servers always return the Content-Disposition header?
Thanks.
| [
"It's an optional header, so no. See if it exists, and if not then fall back to checking the URL.\n"
] | [
1
] | [] | [] | [
"python",
"urllib",
"urlopen"
] | stackoverflow_0003912910_python_urllib_urlopen.txt |
Q:
Function local name binding from an outer scope
I need a way to "inject" names into a function from an outer code block, so they are accessible locally and they don't need to be specifically handled by the function's code (defined as function parameters, loaded from *args etc.)
The simplified scenario: providing a... | Function local name binding from an outer scope | I need a way to "inject" names into a function from an outer code block, so they are accessible locally and they don't need to be specifically handled by the function's code (defined as function parameters, loaded from *args etc.)
The simplified scenario: providing a framework within which the users are able to define ... | [
"The more I mess around with the stack, the more I wish I hadn't. Don't hack globals to do what you want. Hack bytecode instead. There's two ways that I can think of to do this. \n1) Add cells wrapping the references that you want into f.func_closure. You have to reassemble the bytecode of the function to use LOAD... | [
11,
4,
3,
1
] | [] | [] | [
"decorator",
"python",
"scope"
] | stackoverflow_0003908335_decorator_python_scope.txt |
Q:
WSGI request and response wrappers for Python 3
Are there WSGI request and response wrappers for Python 3?
WebOb looks nice (although there is some critique), but it seems to be written in Python <3. Werkzeug seems also to be written in Python <3.
Should I write my own request and response wrappers for Python 3?... | WSGI request and response wrappers for Python 3 | Are there WSGI request and response wrappers for Python 3?
WebOb looks nice (although there is some critique), but it seems to be written in Python <3. Werkzeug seems also to be written in Python <3.
Should I write my own request and response wrappers for Python 3? Maybe this would be impossible, since WSGI seems to ... | [
"My recommendation: right now, Python 2.x should be used for production quality stuff. I know, Python 3 is technically very interesting, but right now sticking with Python 2 is MUCH easier and MUCH more productive.\n",
"No, there are not WSGI for Python3. It occurs because of new string types.\n"
] | [
2,
0
] | [] | [] | [
"python",
"python_3.x",
"request",
"response",
"wsgi"
] | stackoverflow_0003725903_python_python_3.x_request_response_wsgi.txt |
Q:
How to load .bmp file into BitmapImage class Tkinter python
I'm unable to find any way to load .bmp file into Tkinter() so that I can use it in a canvas widget!Plz help me!
from Tkinter import *
from PIL import Image
import ImageTk
import tkFileDialog
import tkMessageBox
root=Tk()
class lapp:
def __init__(self,... | How to load .bmp file into BitmapImage class Tkinter python | I'm unable to find any way to load .bmp file into Tkinter() so that I can use it in a canvas widget!Plz help me!
from Tkinter import *
from PIL import Image
import ImageTk
import tkFileDialog
import tkMessageBox
root=Tk()
class lapp:
def __init__(self,master):
w=Canvas(root,width=300,height=300)
w.pack()... | [
"This works for me. \nThe image doesn't show when I use the Tk PhotoImage class. But it works ok when using PIL.\nMy image size is 50*250, so I've put coordinates that center it (25, 125)\nfrom Tkinter import *\nfrom PIL import Image, ImageTk\n\nroot=Tk()\n\nroot.title(\"My Image\")\n\nw = Canvas(root, width=50, he... | [
1
] | [] | [] | [
"bitmap",
"bmp",
"python",
"python_imaging_library",
"tkinter"
] | stackoverflow_0003913037_bitmap_bmp_python_python_imaging_library_tkinter.txt |
Q:
Python: read user-input directly from the prompt
I have to validate user-input from stdin that is not going to be entered by hitting the Enter-key.
So readline() and other Enter-dependent functions are of no use to me.
Practically the promt will be filled, and each keystroke has to be handled as an event. How do ... | Python: read user-input directly from the prompt | I have to validate user-input from stdin that is not going to be entered by hitting the Enter-key.
So readline() and other Enter-dependent functions are of no use to me.
Practically the promt will be filled, and each keystroke has to be handled as an event. How do I get access to the promt buffer's contents?
| [
"See if it helps\nhttp://code.activestate.com/recipes/134892/\n",
"I'm unclear what you mean by \"prompt\", but it sounds like you need to respond to individual key-presses, rather than textual input.\nThis is covered in the Python FAQ under \"How do I get a single keypress at a time?\"\n"
] | [
2,
2
] | [] | [] | [
"events",
"interactive",
"prompt",
"python"
] | stackoverflow_0003913663_events_interactive_prompt_python.txt |
Q:
Can anyone explain the difference between XMLRPC, SOAP and also the C# Web Service?
Are they just the same protocol or something different?
I am just confused about it.
Actually, I want to call a web service written in C# with ASP.NET by Python. I have tried XMLRPC but it seems just did not work.
So what is the ac... | Can anyone explain the difference between XMLRPC, SOAP and also the C# Web Service? | Are they just the same protocol or something different?
I am just confused about it.
Actually, I want to call a web service written in C# with ASP.NET by Python. I have tried XMLRPC but it seems just did not work.
So what is the actually difference among them?
Thanks.
| [
"All of them use the same transport protocol (HTTP).\nXMLRPC formats a traditional RPC call with XML for remote execution.\nSOAP wraps the call in a SOAP envelope (still XML, different formatting, oriented towards message based services rather than RPC style calls).\nIf you're using C#, your best bet is probably SO... | [
5,
4,
3,
1
] | [] | [] | [
"c#",
"python",
"web_services",
"xml_rpc"
] | stackoverflow_0001847534_c#_python_web_services_xml_rpc.txt |
Q:
How does this Python Lambda recursion expression work?
rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
I am new to Python and trying to understand how lambda expressions work. Can somebody explain how this recursion is working? I am able to understand that 10==11 will be 'false' and that's how rec_fn will be called ... | How does this Python Lambda recursion expression work? | rec_fn = lambda: 10==11 or rec_fn()
rec_fn()
I am new to Python and trying to understand how lambda expressions work. Can somebody explain how this recursion is working? I am able to understand that 10==11 will be 'false' and that's how rec_fn will be called again and again recursively.
But what I am not able to get i... | [
"It may help to think of a function call as an operator. Because that's what it is. When you do rec_fn() you are doing two things. First, you're getting a reference to the object named rec_fn. This happens to be a function, but that doesn't matter (in Python, objects besides functions are callable). Then there is (... | [
4,
0,
0,
0,
0
] | [] | [] | [
"lambda",
"python",
"recursion"
] | stackoverflow_0003911705_lambda_python_recursion.txt |
Q:
Django - ManyToManyField in a model, setting it to null?
I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set blank=null and null=True on the ManyToManyField. I have created an object from th... | Django - ManyToManyField in a model, setting it to null? | I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set blank=null and null=True on the ManyToManyField. I have created an object from this model, and set types to some values. All is good.
I want to... | [
"That's what clear() is for.\nhttp://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear\nPerhaps you're looking for remove()?\nhttp://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove\n",
"I don't think i... | [
14,
1
] | [] | [] | [
"django",
"django_models",
"manytomanyfield",
"python"
] | stackoverflow_0003913499_django_django_models_manytomanyfield_python.txt |
Q:
about textarea \r\n or \n in python
i have tested code in firefox under ubuntu:
the frontend is a textarea,in textarea press the key ENTER,then submit to the server,
on the backend you'll get find \r\n string
r=request.POST.get("t")
r.find("\r\n")>-1:
print "has \r\n"
my question is when we will get \r\n ,whe... | about textarea \r\n or \n in python | i have tested code in firefox under ubuntu:
the frontend is a textarea,in textarea press the key ENTER,then submit to the server,
on the backend you'll get find \r\n string
r=request.POST.get("t")
r.find("\r\n")>-1:
print "has \r\n"
my question is when we will get \r\n ,when we'll get \n?is this platform independe... | [
"Yes, you are correct, you are dealing with a platform-specific ways to encode a newline:\n\nIn Windows platforms, a newline is typically encoded as \\r\\n\nIn Linux/Unix/OS X, a newline is typically encoded as \\n\n\nSimilarly, web browsers tend to favor these conventions: IE uses \\r\\n newlining, whereas Safari ... | [
5
] | [] | [] | [
"python",
"textarea"
] | stackoverflow_0003913830_python_textarea.txt |
Q:
"Pythonic" multithreaded (Concurrent) language
I now primarily write in python, however I am looking for a language that is more thread friendly (not JAVA,C#,C or C++).
Python's threads are good when they are IO bound but it's coming up short when I am doing something CPU intensive.
Any ideas?
Thanks,
James
A:
C... | "Pythonic" multithreaded (Concurrent) language | I now primarily write in python, however I am looking for a language that is more thread friendly (not JAVA,C#,C or C++).
Python's threads are good when they are IO bound but it's coming up short when I am doing something CPU intensive.
Any ideas?
Thanks,
James
| [
"Clojure is pretty fun, if you're into that sort of thing. It's a lisp that runs on the JVM. Apparently it's as fast as Java for a lot of things, despite being dynamically typed *. Java interop is about as convenient as I could imagine possible, though the native clojure libraries are already decent enough that ... | [
7,
4,
3,
2,
1,
1,
1,
1
] | [] | [] | [
"concurrency",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0003911897_concurrency_multiprocessing_multithreading_python.txt |
Q:
Question about python string
i have been asked to write a function which should be called in this way
foo("Hello")
This function also has to return values in this way:
[Hello( user = 'me', answer = 'no', condition = 'good'),
Hello( user = 'you', answer = 'yes', condition = 'bad'),
]
the task has clearly asked t... | Question about python string | i have been asked to write a function which should be called in this way
foo("Hello")
This function also has to return values in this way:
[Hello( user = 'me', answer = 'no', condition = 'good'),
Hello( user = 'you', answer = 'yes', condition = 'bad'),
]
the task has clearly asked to return string values. can anyone... | [
"Functions\nLists\nClasses\nCreate a class that has the desired attributes, then return a list of instances from the function.\n",
"It could be something like this:\nclass Hello:\n def __init__(self, user, answer, condition):\n self.user = user\n self.answer = answer\n self.condition = con... | [
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003912617_python_string.txt |
Q:
Query refresh issue after using MySQL to load file
I use SqlAlchemy as my ORM. I do a mysqlimport cmd through subprocess. Then before and after the execution, I query the db records with the statistics_db method.
But the records count results after import from CSV didn't increase. I think this is an SqlAlchemy pro... | Query refresh issue after using MySQL to load file | I use SqlAlchemy as my ORM. I do a mysqlimport cmd through subprocess. Then before and after the execution, I query the db records with the statistics_db method.
But the records count results after import from CSV didn't increase. I think this is an SqlAlchemy problem.
def statistics_db(f):
@wraps(f)
def wrappe... | [
"You have to either call commit()/rollback() to end transaction after calling count() or change isolation level. Otherwise you won't see changes made from other connections.\n"
] | [
0
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003906262_python_sqlalchemy.txt |
Q:
Simple graphics API with transparency, polygons, reading image pixels?
I need a simple graphics library that supports the following functionality:
Ability to draw polygons (not just rectangles!) with RGBA colors (i.e., partially transparent),
Ability to load bitmap images,
Ability to read current color of pixel i... | Simple graphics API with transparency, polygons, reading image pixels? | I need a simple graphics library that supports the following functionality:
Ability to draw polygons (not just rectangles!) with RGBA colors (i.e., partially transparent),
Ability to load bitmap images,
Ability to read current color of pixel in a given coordinate.
Ideally using JavaScript or Python.
Seems like HTML 5... | [
"PyGame can do all of those things. OTOH, I don't think it embeds into a GUI too well.\n",
"I ended up going with Canvas. The \"secret\" of polygons is using paths. Thanks, \"tur1ng\"!\n",
"GameJs does that and more - it's similar to the mentioned PyGame.\nhttp://gamejs.org\nAbility to draw polygons (not just r... | [
3,
2,
1,
0
] | [
"maybe Raphael - http://raphaeljs.com/reference.html\n"
] | [
-1
] | [
"canvas",
"graphics",
"javascript",
"python",
"svg"
] | stackoverflow_0003021514_canvas_graphics_javascript_python_svg.txt |
Q:
Possible to do ordered dictionary in python 2.5 (due to GAE)?
I'm new to Python, and using Google App Engine, which is currently running only Python 2.5. Are there any built-in ways of doing an ordered dictionary, or do I have to implement something custom?
A:
Django provides a SortedDict class, which has the s... | Possible to do ordered dictionary in python 2.5 (due to GAE)? | I'm new to Python, and using Google App Engine, which is currently running only Python 2.5. Are there any built-in ways of doing an ordered dictionary, or do I have to implement something custom?
| [
"Django provides a SortedDict class, which has the same functionality. If you are using django, you can just use from django.utils.datastructures import SortedDict.\nEven if you're not using django, you can still take advantage of that implementation. Just get the datastructures.py file from the django source and s... | [
4,
0,
0
] | [] | [] | [
"dictionary",
"google_app_engine",
"python",
"python_2.5"
] | stackoverflow_0003911494_dictionary_google_app_engine_python_python_2.5.txt |
Q:
Deploy a sub package with distutils and pip
I am wanting to create a suite of interrelated packages in Python. I would like them all to be under the same package but installable as separate components.
So, for example, installing the base package would provide the mypackage but there would be nothing in mypackage.... | Deploy a sub package with distutils and pip | I am wanting to create a suite of interrelated packages in Python. I would like them all to be under the same package but installable as separate components.
So, for example, installing the base package would provide the mypackage but there would be nothing in mypackage.subpackage until I install it separately.
Is this... | [
"What you are looking for is called \"namespace packages\", see this SO question\n"
] | [
5
] | [] | [] | [
"distutils",
"pip",
"python"
] | stackoverflow_0003914253_distutils_pip_python.txt |
Q:
Python relative import causes syntaxerror: invalid syntax
I'm trying to install this great python module Python-Chrono to my python environment, but it fails at least with python 2.4.3 and 2.6.6 with the following error message:
Traceback (most recent call last):
File "setup.py", line 30, in ?
import chrono... | Python relative import causes syntaxerror: invalid syntax | I'm trying to install this great python module Python-Chrono to my python environment, but it fails at least with python 2.4.3 and 2.6.6 with the following error message:
Traceback (most recent call last):
File "setup.py", line 30, in ?
import chrono
File "/home/janne/python-chrono-0.3.0/chrono/__init__.py", l... | [
"Python 2.4 doesn't support that syntax - it was introduced in Python 2.5.\n(Are you 100% sure that it's failing with that message in 2.6?)\n"
] | [
6
] | [] | [] | [
"python",
"python_import",
"relative_path"
] | stackoverflow_0003914245_python_python_import_relative_path.txt |
Q:
Python Servers fighting each others with sockets
I try to make two servers in a file, but they are fighting each other visibly
have anyone an idea to make them peace ?
here is my code :
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
impo... | Python Servers fighting each others with sockets | I try to make two servers in a file, but they are fighting each other visibly
have anyone an idea to make them peace ?
here is my code :
# -*- coding: utf-8 -*-
import socket
import sys
import re
import base64
import binascii
import time
import zlib
import sys
import StringIO
import contextlib
import smtplib
from thre... | [
"it was better to use : SocketServer.BaseRequestHandler with handler\nand one for each server :\nas seen here :\n# MetaProject v 0.21\n# -*- coding: utf-8 -*-\nimport socket\nimport sys\nimport re\nimport base64\nimport binascii\nimport time\nimport zlib\nimport sys\nimport StringIO\nimport contextlib\nimport smtpl... | [
0
] | [] | [] | [
"asynchronous",
"port",
"python",
"sockets"
] | stackoverflow_0003909964_asynchronous_port_python_sockets.txt |
Q:
How can fractional number expressions be parsed using pyparsing?
We've just started to kick the tires pyparsing and like it so far, but we've been unable to get it to help us parse fractional number strings to turn them into numeric data types.
For example, if a column value in a database table contained the strin... | How can fractional number expressions be parsed using pyparsing? | We've just started to kick the tires pyparsing and like it so far, but we've been unable to get it to help us parse fractional number strings to turn them into numeric data types.
For example, if a column value in a database table contained the string:
1 1/2
We'd like some way to convert it into the numeric python equi... | [
"Since you cite some tests, it sounds like you've at least taken a stab at the problem. I assume you've already defined a single number, which can be integer or real - doesn't matter, you are converting everything to float anyway - and a fraction of two numbers, probably something like this:\nfrom pyparsing import... | [
8,
3,
2,
1
] | [] | [] | [
"dsl",
"fractions",
"parsing",
"pyparsing",
"python"
] | stackoverflow_0003911824_dsl_fractions_parsing_pyparsing_python.txt |
Q:
How to decode string to use with Google Language Detection API?
I want to use Google Language Detection API in my app to detect language of url parameter. For example user requests url
http://myapp.com/q?Это тест
and gets message "Russian". I do it this way:
def get(self): ... | How to decode string to use with Google Language Detection API? | I want to use Google Language Detection API in my app to detect language of url parameter. For example user requests url
http://myapp.com/q?Это тест
and gets message "Russian". I do it this way:
def get(self):
url = "http://ajax.googleapis.com/ajax/services/languag... | [
"Maybe urllib.unquote is what you are looking for:\n>>> from urllib import unquote\n>>> unquote(\"%DD%F2%EE%20%F2%E5%F1%F2\")\n\nThis gives you a string in which the characters are in whatever encoding that you've used in the URL. If you want to recode it to a different encoding (say, UTF-8), you have to create a u... | [
3
] | [] | [] | [
"google_app_engine",
"python",
"urldecode"
] | stackoverflow_0003914803_google_app_engine_python_urldecode.txt |
Q:
Length of arguments of Python function?
Possible Duplicate:
How to find out the arity of a method in Python
For example I have declared a function:
def sum(a,b,c):
return a + b + c
I want to get length of arguments of "sum" function.
somethig like this: some_function(sum) to returned 3
How can it be done ... | Length of arguments of Python function? |
Possible Duplicate:
How to find out the arity of a method in Python
For example I have declared a function:
def sum(a,b,c):
return a + b + c
I want to get length of arguments of "sum" function.
somethig like this: some_function(sum) to returned 3
How can it be done in Python?
Update:
I asked this question bec... | [
"The inspect module is your friend; specifically inspect.getargspec which gives you information about a function's arguments:\n>>> def sum(a,b,c):\n... return a + b + c\n...\n>>> import inspect\n>>> argspec = inspect.getargspec(sum)\n>>> print len(argspec.args)\n3\n\nargspec also contains details of optional ar... | [
16,
5,
3
] | [] | [] | [
"arguments",
"function",
"parameters",
"python"
] | stackoverflow_0003913963_arguments_function_parameters_python.txt |
Q:
Dynamically creating classes - Python
I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.
By "dynamically" I intend to create a class based on configuration provided by a user.
e.g.
I want a class named CommentForm which should subclass the ... | Dynamically creating classes - Python | I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form class.
By "dynamically" I intend to create a class based on configuration provided by a user.
e.g.
I want a class named CommentForm which should subclass the Form class.
The class should have a list of... | [
"You can create classes on the fly by calling the type built-in, passing appropriate arguments along, like:\nCommentForm = type(\"CommentForm\", (Form,), { \n 'name': forms.CharField(),\n ...\n})\n\nIt works with new-style classes. I am not sure, whether this would also work with old-style classes.\n",
"Cla... | [
35,
14
] | [] | [] | [
"class",
"django",
"dynamic",
"forms",
"python"
] | stackoverflow_0003915024_class_django_dynamic_forms_python.txt |
Q:
Twisted HTTP Proxy Channel set to None on LostConnection but loseConnection hasn't been called yet
Ok I have been writing a proxy to take http GET requests and translate them into HTTP POST requests (because a lot of media players for python only support GET). So I know am working on caching those results that way... | Twisted HTTP Proxy Channel set to None on LostConnection but loseConnection hasn't been called yet | Ok I have been writing a proxy to take http GET requests and translate them into HTTP POST requests (because a lot of media players for python only support GET). So I know am working on caching those results that way I only download a url once, I moved a lot of code from the super class to the sub class and changed it ... | [
"Connections may be lost without the internet going out. All it takes is for one side of the connection to call shutdown() or close(). Have you ruled that out? And even if you have, for the code to be correct, it needs to handle that possibility anyway, because it might happen at some other time. See Request.no... | [
1
] | [] | [] | [
"python",
"twisted",
"twisted.web"
] | stackoverflow_0003911202_python_twisted_twisted.web.txt |
Q:
Advice on which language to use
I'm trying to create a web application which will get input from system.
What this application should do is to listen what happens when some shell scripts are executing and reporting the status trough web.
An example :
I'm copying thousands of records with shell script, and while t... | Advice on which language to use | I'm trying to create a web application which will get input from system.
What this application should do is to listen what happens when some shell scripts are executing and reporting the status trough web.
An example :
I'm copying thousands of records with shell script, and while this is still executing I'd like pass ... | [
"I'd use a named pipe (FIFO) instead. You simply write your output to the pipe and let the application read it. I'm not sure if there is any other way to get a more live system than this.\nI'd recommend Perl as the back-end.\nEDIT: \nnamed pipes are a special type of files on UNIX. The abbreviation FIFO stands for ... | [
5,
2,
0,
0,
0
] | [] | [] | [
"java",
"perl",
"python",
"shell",
"system"
] | stackoverflow_0003914615_java_perl_python_shell_system.txt |
Q:
Developing and using the same Python on the same computer
I'm developing a Python utility module to help with file downloads, archives, etc. I have a project set up in a virtual environment along with my unit tests. When I want to use this module on the same computer (essentially as "Production"), I move the files... | Developing and using the same Python on the same computer | I'm developing a Python utility module to help with file downloads, archives, etc. I have a project set up in a virtual environment along with my unit tests. When I want to use this module on the same computer (essentially as "Production"), I move the files to the mymodule directory in the ~/dev/modules/mymodule
I keep... | [
"I'm guessing by virtual environment you mean the virtualenv package?\nhttp://pypi.python.org/pypi/virtualenv\nWhat I'd try (and apologies if I've not understood the question right) is:\n\nKeep the source somewhere that isn't referenced by PYTHONPATH (e.g. ~/projects/myproject)\nWrite a simple setuptools or distuti... | [
1,
1,
0
] | [] | [] | [
"module",
"packaging",
"python",
"pythonpath"
] | stackoverflow_0003914289_module_packaging_python_pythonpath.txt |
Q:
How to copy a variable number of elements in a list to a uniform list and store in MySQL using Python the most efficient way?
This is a sample list (each line has variable elements) :
['1', 'Tech', 'Code']
['2', 'Edu']
['3', 'Money', 'Sum', '176']
I have to insert this into a MySQL table which has 4 columns (max ... | How to copy a variable number of elements in a list to a uniform list and store in MySQL using Python the most efficient way? | This is a sample list (each line has variable elements) :
['1', 'Tech', 'Code']
['2', 'Edu']
['3', 'Money', 'Sum', '176']
I have to insert this into a MySQL table which has 4 columns (max num. of elements in a value in a list).
How to do this efficiently? I have a feeling my solution is the least efficient!
Here is m... | [
"How about this?\nfor line in mylistings:\n out = line + [None] * (4 - len(line)) # pad the list with None to 4 elements\n cursor.execute(\"INSERT INTO LoadData VALUES (%s, %s, %s, %s)\", out)\n\n",
"You should use executemany to speed things up on the database side. Also, you can cache the padding list so ... | [
2,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003915222_mysql_python.txt |
Q:
TKinter: I cannot see my left frame with a button inside
I cannot see my left frame with a button inside (I'm using TKinter).. This is my code:
#create window & frames
root = Tk()
root.title( "Medical Visualization" )
rootFrame = Frame(root)
rootFrame.pack( fill=BOTH, expand=1, side=TOP )
leftframe = Frame(root,... | TKinter: I cannot see my left frame with a button inside | I cannot see my left frame with a button inside (I'm using TKinter).. This is my code:
#create window & frames
root = Tk()
root.title( "Medical Visualization" )
rootFrame = Frame(root)
rootFrame.pack( fill=BOTH, expand=1, side=TOP )
leftframe = Frame(root, width=100, bg="blue")
leftframe.pack(fill=X, expand=True)
bu... | [
"I see it, and looking at the code I see nothing that would prevent it from being seen. Are you remembering to call root.mainloop? Your code snippet doesn't show you calling that method. \n"
] | [
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003915582_python_tkinter.txt |
Q:
Parsing PDF file using Regular expressions in Python
I am trying to parse some object elements from a PDF file using re module of Python. My goal is to parse each PDF object using a regular expression.
A PDF object example is the following:
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/T... | Parsing PDF file using Regular expressions in Python | I am trying to parse some object elements from a PDF file using re module of Python. My goal is to parse each PDF object using a regular expression.
A PDF object example is the following:
1 0 obj
<<
/Type /Catalog
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [ 3 0 R ]
/Count 1
>>
endobj
...
... | [
"If you are using only regex, it is easy to construct a PDF file that your program will not be able to handle. PDF dictionaries and lists can contain other objects. Regex can't handle recursive structures, at least not Python re module.\nA pdf file is a tree of objects and streams:\n\nDictionaries: << (name value)*... | [
8,
2,
2,
2
] | [] | [] | [
"parsing",
"pdf",
"python",
"regex"
] | stackoverflow_0003915131_parsing_pdf_python_regex.txt |
Q:
Extending python Queue.PriorityQueue (worker priority, work package types)
I would like to extend the Queue.PriorityQueue described here: http://docs.python.org/library/queue.html#Queue.PriorityQueue
The queue will hold work packages with a priority. Workers will get work packages and process them. I want to make ... | Extending python Queue.PriorityQueue (worker priority, work package types) | I would like to extend the Queue.PriorityQueue described here: http://docs.python.org/library/queue.html#Queue.PriorityQueue
The queue will hold work packages with a priority. Workers will get work packages and process them. I want to make the following additions:
Workers have a priority too. When multiple workers are... | [
"I think you are describing a situation where you have two \"priority queues\" - one for the jobs and one for the workers. The naive approach is to take the top priority job and the top priority worker and try to pair them. But of course this fails when the worker is unable to execute the job.\nTo fix this I'd sugg... | [
1,
0
] | [] | [] | [
"parallel_processing",
"python",
"queue"
] | stackoverflow_0003849157_parallel_processing_python_queue.txt |
Q:
What is location of django Built-in tags and filters?
What is location of django Built-in tags and filters? I cant find anywhere... I need it to format datetime so then i can send right formt in JSON by AJAX response.. Or maybe you can suggest me another way to do that...
What i want to do it's import function whi... | What is location of django Built-in tags and filters? | What is location of django Built-in tags and filters? I cant find anywhere... I need it to format datetime so then i can send right formt in JSON by AJAX response.. Or maybe you can suggest me another way to do that...
What i want to do it's import function which determinate filter... and use it to format my datetime i... | [
"What do you mean location? Do you mean where in Django's code does it live? If so, the default filters live in django.template.defaultfilters.\nIf you're wanting to do date formatting in a view, then use dateformat.\nYou can see an example of how to use dateformat in the code for the time filter, visible here.\n"
... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003916332_django_python.txt |
Q:
Scipy optimize.curve_fit sometimes won't converge
I'm trying to use numpy.optimize.curve_fit to estimate the frequency and phase of an on/off sequence.
This is the code I'm using:
from numpy import *
from scipy import optimize
row = array([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,... | Scipy optimize.curve_fit sometimes won't converge | I'm trying to use numpy.optimize.curve_fit to estimate the frequency and phase of an on/off sequence.
This is the code I'm using:
from numpy import *
from scipy import optimize
row = array([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,... | [
"I tried both rows of data that you provided and both worked for me just fine. I'm using Scipy 0.8.0rc3. What version are you using? Another thing that might help is to set c and d to fixed values since they really should be the same every time. I set c to 0.6311786 and d to .5. You could also use an fft with zero ... | [
2
] | [] | [] | [
"curve_fitting",
"numerical_methods",
"numpy",
"python",
"scipy"
] | stackoverflow_0003915480_curve_fitting_numerical_methods_numpy_python_scipy.txt |
Q:
gtk minimum size
Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of a TreeView, but is it available for general widgets?
A:
For C/C++: gtk_widget_set_size_request()
Sets the minimum size of a widget; that is, the widget's size request will be wid... | gtk minimum size | Is there an easy way to request that a GTK widget have a minimum width/height? I know you can do it on the column of a TreeView, but is it available for general widgets?
| [
"For C/C++: gtk_widget_set_size_request()\n\nSets the minimum size of a widget; that is, the widget's size request will be width by height. \n\nPyGTK: def set_size_request(width, height)\n"
] | [
10
] | [] | [] | [
"c",
"c++",
"gtk",
"pygtk",
"python"
] | stackoverflow_0003916762_c_c++_gtk_pygtk_python.txt |
Q:
SMTP ERROR: (552, '5.6.0 Submission denied Sender does not match originator )
I've writted a Python script to send emails via a relay server. I've tested that the appropriate email address's etc are permissioned etc by sending an email using Telnet. My Python script also work when set up to send via my old relay s... | SMTP ERROR: (552, '5.6.0 Submission denied Sender does not match originator ) | I've writted a Python script to send emails via a relay server. I've tested that the appropriate email address's etc are permissioned etc by sending an email using Telnet. My Python script also work when set up to send via my old relay server.
Therefore i am confused as to why i am getting the following error message:
... | [
"I can't guarantee that either of these is the actual cause of the error, but:\n\nI think the message you're getting might be saying that the From: header in your message doesn't match the e-mail address you are using for the sender in the sendmail() call. Make sure that the message you are reading from the file a)... | [
0
] | [] | [] | [
"email",
"html_email",
"python",
"smtp",
"smtplib"
] | stackoverflow_0003915151_email_html_email_python_smtp_smtplib.txt |
Q:
Implementing a text-based fallback for pygtk applications
I have a pygtk application and would like to provide a text-based fallback mode for it. When mporting gtk without a X display available I see only a GtkWarning on stderr but no exception I could take advantage of and checking for DISPLAY seems like an ugly ... | Implementing a text-based fallback for pygtk applications | I have a pygtk application and would like to provide a text-based fallback mode for it. When mporting gtk without a X display available I see only a GtkWarning on stderr but no exception I could take advantage of and checking for DISPLAY seems like an ugly hack. How can I implement this?
| [
"Checking gtk.gdk.screen_get_default() does it, however there seems no way to suppress the GTK warnings.\n"
] | [
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003914370_pygtk_python.txt |
Q:
Python Threading Concept Question
I'm currently in the process of writing a client server app as an exercise and I've gotten pretty much everything to work so far, but there is a mental hurdle that I haven't been able to successfully google myself over.
In the server application am I correct in my thinking that t... | Python Threading Concept Question | I'm currently in the process of writing a client server app as an exercise and I've gotten pretty much everything to work so far, but there is a mental hurdle that I haven't been able to successfully google myself over.
In the server application am I correct in my thinking that threading the packet handler and databas... | [
"This is what queues are for. Replace stack with queue and no, you won't have to use any other synchronization methods. Incidentally, multiprocessing is better than threading, since it can take advantage of multicore/hyperthreaded processors. The interfaces are pretty similar, so it's worth looking into switching.\... | [
4
] | [] | [] | [
"arrays",
"multithreading",
"python",
"thread_safety"
] | stackoverflow_0003917036_arrays_multithreading_python_thread_safety.txt |
Q:
Split up python packets?
Is there a way python can distinguish between packets being sent ? e.g.
python receives data
it process data
clients sends first packet
client sends second packet
python receives data, can i receive the first packet rather then all info in the buffer
I know i can set it up up so it sends d... | Split up python packets? | Is there a way python can distinguish between packets being sent ? e.g.
python receives data
it process data
clients sends first packet
client sends second packet
python receives data, can i receive the first packet rather then all info in the buffer
I know i can set it up up so it sends data i confirm and the client w... | [
"There are basically two approaches:\n\nAt the start of each packet, send an integer specifying how long that packet will be. When you receive data, read the integer first, then read that many more bytes as the first packet.\nSend some sort special marker between packets. This only works if you can guarantee that... | [
1,
0,
0
] | [] | [] | [
"packets",
"python",
"sockets"
] | stackoverflow_0003914542_packets_python_sockets.txt |
Q:
Python tarfile module overwrites existing files during extraction - how to disable it?
Is there a way prevent tarfile.extractall (API) from overwriting existing files? By "prevent" I mean ideally raising an exception when an overwrite is about to happen. The current behavior is to silently overwrite the files.
A:... | Python tarfile module overwrites existing files during extraction - how to disable it? | Is there a way prevent tarfile.extractall (API) from overwriting existing files? By "prevent" I mean ideally raising an exception when an overwrite is about to happen. The current behavior is to silently overwrite the files.
| [
"You could check result of tarfile.getnames against the existing files and raise your error.\n",
"Have you tried setting tarfile.errorlevel to 2? That will cause non-fatal errors to be raised. I'm assuming an overwrite falls in that category.\n"
] | [
3,
0
] | [] | [] | [
"exception",
"python",
"tarfile"
] | stackoverflow_0003917491_exception_python_tarfile.txt |
Q:
Twisted client for a send only protocol that is tolerant of disconnects
I've decided to dip my toe into the world of asynchronous python with the help of twisted. I've implemented some of the examples from the documentation, but I'm having a difficult time finding an example of the, very simple, client I'm trying ... | Twisted client for a send only protocol that is tolerant of disconnects | I've decided to dip my toe into the world of asynchronous python with the help of twisted. I've implemented some of the examples from the documentation, but I'm having a difficult time finding an example of the, very simple, client I'm trying to write.
In short I'd like a client which establishes a tcp connection with ... | [
"What I have done is not used a Queue but I am illustrating the code that sends a line, once a connection is made. There are bunch of print stuff that will help you understand on what is going on.\nUsual import stuff:\nfrom twisted.web import proxy\nfrom twisted.internet import reactor\nfrom twisted.internet import... | [
1
] | [] | [] | [
"asynchronous",
"client",
"networking",
"python",
"twisted"
] | stackoverflow_0003917382_asynchronous_client_networking_python_twisted.txt |
Q:
Post Binary Sting to Django app using HTML 5
I read in a file via HTML5 FileReader and jQuery like so:
holder.ondrop = function(e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onloadend = function(event) {
$.ajax({
... | Post Binary Sting to Django app using HTML 5 | I read in a file via HTML5 FileReader and jQuery like so:
holder.ondrop = function(e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onloadend = function(event) {
$.ajax({
url:"/path/to/upload",
type: "POST... | [
"this post was really helpful for me, maybe it will be helpful for you too\nhttp://hacks.mozilla.org/2010/06/html5-adoption-stories-box-net-and-html5-drag-and-drop/\nI ended up changing my javascript to be:\nholder.ondrop = function(e) {\n e.preventDefault();\n\n var file = e.dataTransfer.files[0];\n ... | [
2
] | [] | [] | [
"django",
"file_upload",
"html",
"jquery",
"python"
] | stackoverflow_0003916989_django_file_upload_html_jquery_python.txt |
Q:
Get parameters of object in metaclass of this object
My problem is a python/django mix. I have a form model that will display some fields. Basing on some parameter of this model, the data sent to metaclass creating this object should differ. But how can I reach this parameter when inside the body of Meta ? Should ... | Get parameters of object in metaclass of this object | My problem is a python/django mix. I have a form model that will display some fields. Basing on some parameter of this model, the data sent to metaclass creating this object should differ. But how can I reach this parameter when inside the body of Meta ? Should I use some global var instead of object parameter (as it i... | [
"You can't do anything dynamic within Meta. That's not what it's for.\nWhy can't you do it all within __init__? You can modify self.fields from there.\n",
"Just as Daniel proposed, I moved the whole thing to __init__ :\n type = None\n try:\n type = self.instance.template_id\n except:\n pass... | [
2,
1
] | [] | [] | [
"django",
"metaclass",
"python",
"scope"
] | stackoverflow_0003916570_django_metaclass_python_scope.txt |
Q:
Iron Python vs Razor
I have a little bit of experience with the new Razor syntax, but none with Iron Python. I was wondering do both meet the same needs? Is one favored by Microsoft over the other (or will be)? Appreciate your thoughts, as I'm toying with the idea of learning Iron Python, but if Razor can meet t... | Iron Python vs Razor | I have a little bit of experience with the new Razor syntax, but none with Iron Python. I was wondering do both meet the same needs? Is one favored by Microsoft over the other (or will be)? Appreciate your thoughts, as I'm toying with the idea of learning Iron Python, but if Razor can meet the same need, I probably w... | [
"To expand on the answer given by PaulStack:\nRazor is a templating engine (with a slant towards templating XML-style documents, e.g. HTML web pages) that is available as a View Engine in MVC 3 as well as the default page syntax in ASP.NET Web Pages (which is part of the WebMatrix stack). The Razor parser uses assu... | [
7,
5,
1
] | [] | [] | [
"ironpython",
"python",
"razor"
] | stackoverflow_0003916787_ironpython_python_razor.txt |
Q:
Python Threads (or their equivalent) on Google Application Engine Workaround?
I want to make a Google App Engine app that does the following:
Client makes an asynchronous http request
Server starts processing that request
Client makes ajax http requests to get progress
The problem is that the server processing ... | Python Threads (or their equivalent) on Google Application Engine Workaround? | I want to make a Google App Engine app that does the following:
Client makes an asynchronous http request
Server starts processing that request
Client makes ajax http requests to get progress
The problem is that the server processing (step #2) may take more than 30 seconds.
I know that you can't have threads on Goog... | [
"You'll want to use the Task Queue API, probably via deferred tasks. The deferred API makes working with Task Queues dramatically simpler.\nEssentially, you'll want to spawn a task to start the processing. That task should catch DeadlineExceeded exceptions and reschedule itself (again via the deferred API) to con... | [
4
] | [] | [] | [
"django",
"google_app_engine",
"multithreading",
"python",
"python_multithreading"
] | stackoverflow_0003917432_django_google_app_engine_multithreading_python_python_multithreading.txt |
Q:
Why is 3<<1 == 6 in python?
Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?
anyone can explain me that operator << or >>
A:
The << and >> operators are bitshift operators. x << 1 shifts all the bits in x up to the next most significant bit, effectively multiplying by 2. More generally, x << n sh... | Why is 3<<1 == 6 in python? |
Possible Duplicate:
Absolute Beginner's Guide to Bit Shifting?
anyone can explain me that operator << or >>
| [
"The << and >> operators are bitshift operators. x << 1 shifts all the bits in x up to the next most significant bit, effectively multiplying by 2. More generally, x << n shifts the bits up n positions. To understand how this operation works it is easiest to look at the binary representation:\n3 0000011 = ... | [
34,
15,
4,
4
] | [] | [] | [
"bit_manipulation",
"operators",
"python"
] | stackoverflow_0003917948_bit_manipulation_operators_python.txt |
Q:
python statistical analysis
Given 15 players - 2 Goalkeepers, 5 defenders, 5 midfielders and 3 strikers, and the fact that each has a value and a score, I want to calculate the highest scoring team for the money I have. Each team must consist of 1 GK then a formation e.g. 4:4:2, 4:3:3 etc. I started with sample da... | python statistical analysis | Given 15 players - 2 Goalkeepers, 5 defenders, 5 midfielders and 3 strikers, and the fact that each has a value and a score, I want to calculate the highest scoring team for the money I have. Each team must consist of 1 GK then a formation e.g. 4:4:2, 4:3:3 etc. I started with sample data such as this
player role poi... | [
"You might be able to solve this problem with recursion. The following shows the basic outline, but ignores details like a team being composed of a certain number of certain types of players. \nplayers=[{'name':'A','score':5,'cost':10},\n {'name':'B','score':10,'cost':3},\n {'name':'C','score':6,'co... | [
5,
0
] | [] | [] | [
"python",
"statistics"
] | stackoverflow_0003917967_python_statistics.txt |
Q:
Problem with running a program on Pydev in Eclipse
I need your help,
I'm using Eclipse and Pydev plugin as python IDE.
I have configured and set environment variables, libraries etc etc
I created a project, and a module.
When I write these lines and run the program, it gives an error:
`a = 3
b = 4.6
print "%d is t... | Problem with running a program on Pydev in Eclipse | I need your help,
I'm using Eclipse and Pydev plugin as python IDE.
I have configured and set environment variables, libraries etc etc
I created a project, and a module.
When I write these lines and run the program, it gives an error:
`a = 3
b = 4.6
print "%d is the value of a, %.2f is the value of b" %(a, b)`
and the... | [
"Well, the error message pretty much sums it up: There is a non-ascii character in your file. Python 2 source files are expected to be ASCII only, or contain an # -*- coding: <encoding name> -*- (there are other valid forms, see the PEP the error refers to) comment at the top. For Python 3, UTF-8 is allowed too.\nI... | [
0
] | [] | [] | [
"eclipse",
"pydev",
"python"
] | stackoverflow_0003918241_eclipse_pydev_python.txt |
Q:
Generic metaclass to keep track of subclasses?
I'm trying to write a generic metaclass to track subclasses
Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like:
def make_subtracker(ro... | Generic metaclass to keep track of subclasses? | I'm trying to write a generic metaclass to track subclasses
Since I want this to be generic, I didn't want to hardcode any class name within this metaclass, therefore I came up with a function that generates the proper metaclass, something like:
def make_subtracker(root):
class SubclassTracker(type):
def __... | [
"I think you want something like this (untested):\nclass SubclassTracker(type):\n def __init__(cls, name, bases, dct):\n if not hasattr(cls, '_registry'):\n cls._registry = []\n print('registering %s' % (name,))\n cls._registry.append(cls)\n super(SubclassTracker, cls).__in... | [
11,
11,
2
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0003915315_metaclass_python.txt |
Q:
Having issues with flock() function
I have a question about how flock() works, particularly in python. I have a module that opens a serial connection (via os.open()). I need to make this thread safe. It's easy enough making it thread safe when working in the same module using threading.Lock(), but if the module ge... | Having issues with flock() function | I have a question about how flock() works, particularly in python. I have a module that opens a serial connection (via os.open()). I need to make this thread safe. It's easy enough making it thread safe when working in the same module using threading.Lock(), but if the module gets imported from different places, it bre... | [
"When a process dies the OS should clean up any open file resources (with some caveats, I'm sure). This is because the advisory lock is released when the file is closed, an operation which occurs as part of the OS cleanup when the python process exits.\nRemember, flock(2) is merely advisory: \n\nAdvisory locks allo... | [
2
] | [] | [] | [
"fcntl",
"flock",
"locking",
"python"
] | stackoverflow_0003918385_fcntl_flock_locking_python.txt |
Q:
How to make cStringIO transparent to another function that expects a real local file
I came up with the following problem: CODE A works right now.. I am saving a png file called chart.png locally, and then I am loading it into the proprietary function (which I do not have access).
However, in CODE B, am trying to... | How to make cStringIO transparent to another function that expects a real local file | I came up with the following problem: CODE A works right now.. I am saving a png file called chart.png locally, and then I am loading it into the proprietary function (which I do not have access).
However, in CODE B, am trying to use cStringIO.StringIO() so that I do not have to write the file "chart.png" to the disk.... | [
"Probably not, but there's always tempfile if you need a \"clean\" workaround...\n"
] | [
3
] | [] | [] | [
"matplotlib",
"python",
"stringio"
] | stackoverflow_0003917902_matplotlib_python_stringio.txt |
Q:
DNS resolver libraries with support for DNSSEC and/or experimental new RR types
What's the state of the art in DNS resolver libraries? I am particularly interested in full (not stub) resolvers that support any or all of: making multiple queries in one request packet, complete DNSSEC validation, returning detailed... | DNS resolver libraries with support for DNSSEC and/or experimental new RR types | What's the state of the art in DNS resolver libraries? I am particularly interested in full (not stub) resolvers that support any or all of: making multiple queries in one request packet, complete DNSSEC validation, returning detailed information about DNSSEC validation to the application, and can handle experimental ... | [
"The best library I know of (and it includes DNSSEC validation) is libunbound which is part of the Unbound distribution.\nNote that the DNS protocol itself does not support your first requirement (multiple queries in one packet). The best you can do is use TCP and then issue multiple sequential queries over one so... | [
1,
0
] | [] | [] | [
"c",
"dns",
"javascript",
"python"
] | stackoverflow_0003604814_c_dns_javascript_python.txt |
Q:
As a software developer what is your SNMP suite that easy to integrate into your software
Well, altough the S of the SNMP stands for Simple, yet, so far I haven't experienced it that way. And now that I am about to deploy my software on around around 180 remote Linux servers and wants to monitor the servers and co... | As a software developer what is your SNMP suite that easy to integrate into your software | Well, altough the S of the SNMP stands for Simple, yet, so far I haven't experienced it that way. And now that I am about to deploy my software on around around 180 remote Linux servers and wants to monitor the servers and configure my daemons all from a centralized point.
I simply want you to recommend me the library ... | [
"I wouldn't describe it as easy, but the easiest I've found (quite a while ago) was pysnmp -- I had to wrap it with a couple of façades to make it somewhat usable by people who weren't deep SNMP experts (and that code I had to leave behind at a previous employer, was never open-sourced, and I couldn't reconstruct i... | [
3,
2,
0,
0
] | [] | [] | [
"c",
"c++",
"linux",
"python",
"snmp"
] | stackoverflow_0003446087_c_c++_linux_python_snmp.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.