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:
Build a web client integrated facebook chat?
I'm using Google App Engine and I'm interested in creating a web site integrated facebook chat.
I read Integrating with Facebook Chat and with what I read, I think their example code only works for desktop applications. I tried some applications integrated facebook chat such as pidgin, meebo... There is a web client named tokbox but I think their chat application build on flash.
Does somebody know how to implement facebook chat to a web client by python ?
Thank you.
A:
Well, Google App Engine has a XMPP feature, it could probably be what you need.
| Build a web client integrated facebook chat? | I'm using Google App Engine and I'm interested in creating a web site integrated facebook chat.
I read Integrating with Facebook Chat and with what I read, I think their example code only works for desktop applications. I tried some applications integrated facebook chat such as pidgin, meebo... There is a web client named tokbox but I think their chat application build on flash.
Does somebody know how to implement facebook chat to a web client by python ?
Thank you.
| [
"Well, Google App Engine has a XMPP feature, it could probably be what you need.\n"
] | [
0
] | [] | [] | [
"facebook_chat",
"google_app_engine",
"python"
] | stackoverflow_0004213244_facebook_chat_google_app_engine_python.txt |
Q:
difference between an object property and type property
Some one to help me this, What is the difference between an object property and type property? if possible with an example in python.. thanks!
A:
class A:
class_property = 10
def __init__(self):
self.object_property = 20
The difference is that you can access class_property through class A:
print A.class_property
but you can access object_property only through an instance of A:
a = A()
print a.object_property
| difference between an object property and type property | Some one to help me this, What is the difference between an object property and type property? if possible with an example in python.. thanks!
| [
"class A:\n class_property = 10\n\n def __init__(self):\n self.object_property = 20\n\nThe difference is that you can access class_property through class A:\nprint A.class_property\n\nbut you can access object_property only through an instance of A:\na = A()\nprint a.object_property\n\n"
] | [
4
] | [] | [] | [
"properties",
"python",
"types"
] | stackoverflow_0004213697_properties_python_types.txt |
Q:
Python, url from request
I am trying to get the url of the page I just fetched - as it can change after redirects...
opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
self.response = opener.open(url)
self.page_contents = self.response.read()
However, due to redirects sometimes the page I request isn't the page I get.... how can I get the final url - I have tried to find a param on the self.response and looking at the docs isn't helping....
Any pointers?
A:
This is done with
self.response.geturl()
| Python, url from request | I am trying to get the url of the page I just fetched - as it can change after redirects...
opener = urllib2.build_opener(redirect_handler.MyHTTPRedirectHandler())
opener.addheaders = [('Accept-encoding', 'gzip')]
self.response = opener.open(url)
self.page_contents = self.response.read()
However, due to redirects sometimes the page I request isn't the page I get.... how can I get the final url - I have tried to find a param on the self.response and looking at the docs isn't helping....
Any pointers?
| [
"This is done with\nself.response.geturl()\n\n"
] | [
1
] | [] | [] | [
"python",
"redirect",
"urllib2"
] | stackoverflow_0004213676_python_redirect_urllib2.txt |
Q:
Blocking HTML tags in a webpage
So, I have a web 2.0 site I'm building with a lot of user input but as with any web 2.0 site, I'm gonna have trouble with spam. Easiest way in my case as far as I'm aware is to block any HTML tags. Users do not need formatting and I'll use for fixing spacing.
But I don't think there's any blocking tags, xmb sounds perfect but been depreceated since the 90s so pretty dumb.
Otherwise, what kind of filtering would I need? I see stack overflow allows 'basic' HTML... How do I do it? Block certain tags or allow certain tags, etc. As I said, users shouldn't need any tags.
Edit: using django
A:
In Django, you can escape (encode) the special HTML characters like < and > so tags can be displayed as readable text, but don't function as HTML :
from django.utils.html import escape
print escape('<div class="q">Q & A</div>')
Note that your template variables may have already been escaped, you may want to check it first to see if you need to use escape.
Or you can completely remove the tags as follows :
from django.utils.html import strip_tags
strip_tags(string_value)
Or, you can use a template filter to remove them like :
{{ value|striptags }}
A:
If you don't want to allow any HTML, then just convert characters with special meaning to their respective entities. e.g. > to > and & to &. How you do this depends on the language you are processing the data with, in TT I would [% some_data | html %] while in PHP the htmlspecialchars function would come into play.
If you want to allow some content, you will need to run it through and HTML parser, check every element and attribute against a white list and then serialize it back to HTML. There are tools to help with this but, again, it depends on the language you are working in.
| Blocking HTML tags in a webpage | So, I have a web 2.0 site I'm building with a lot of user input but as with any web 2.0 site, I'm gonna have trouble with spam. Easiest way in my case as far as I'm aware is to block any HTML tags. Users do not need formatting and I'll use for fixing spacing.
But I don't think there's any blocking tags, xmb sounds perfect but been depreceated since the 90s so pretty dumb.
Otherwise, what kind of filtering would I need? I see stack overflow allows 'basic' HTML... How do I do it? Block certain tags or allow certain tags, etc. As I said, users shouldn't need any tags.
Edit: using django
| [
"In Django, you can escape (encode) the special HTML characters like < and > so tags can be displayed as readable text, but don't function as HTML :\nfrom django.utils.html import escape\nprint escape('<div class=\"q\">Q & A</div>')\n\nNote that your template variables may have already been escaped, you may want to... | [
3,
2
] | [] | [] | [
"django",
"html",
"python"
] | stackoverflow_0004213884_django_html_python.txt |
Q:
Running a Command in Tomcat CGI using Python
I've encountered and weired behaviour when running python in Tomcat-CGI. All things workfine expect calling a this command
subprocess.Popen('"C:\Program Files\AutoIt3\Aut2Exe\Aut2exe.exe" /in "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\python\install.au3" /out "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\python\install.exe"')
Running this code generates an exe as expected, however, it also puts the following in the HTML
<subprocess.Popen object at 0x0094BC10>
If I call the same inside an batch file, it prints the entire output in the HTML and doesn't create the exe too.
Any Ideas?
A:
I do not hnow much about TomCat and your environment, but I would say that your
<subprocess.Popen object at 0x0094BC10>
is returnvalue of subprocess.Popen() call.
I would try to move the subprocess.Popen() somewhere, where its returnvalue is not captured into your html (if what you want is eliminate the returnvalue from your html). Just my first idea, hope it helps.
| Running a Command in Tomcat CGI using Python | I've encountered and weired behaviour when running python in Tomcat-CGI. All things workfine expect calling a this command
subprocess.Popen('"C:\Program Files\AutoIt3\Aut2Exe\Aut2exe.exe" /in "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\python\install.au3" /out "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\python\install.exe"')
Running this code generates an exe as expected, however, it also puts the following in the HTML
<subprocess.Popen object at 0x0094BC10>
If I call the same inside an batch file, it prints the entire output in the HTML and doesn't create the exe too.
Any Ideas?
| [
"I do not hnow much about TomCat and your environment, but I would say that your\n<subprocess.Popen object at 0x0094BC10>\n\nis returnvalue of subprocess.Popen() call.\nI would try to move the subprocess.Popen() somewhere, where its returnvalue is not captured into your html (if what you want is eliminate the retur... | [
1
] | [] | [] | [
"cgi",
"python",
"tomcat"
] | stackoverflow_0004213909_cgi_python_tomcat.txt |
Q:
Facing problem with XLWT and XLRD - Reading and writing simultaneously
I am facing a problem with xlrd and xlwt. Pasting the sample code
below.
from xlwt import Workbook, Formula, XFStyle
import xlrd
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
myFontStyle = XFStyle()
myFontStyle.num_format_str = '0.00'
sheet1.write(0,0,10, myFontStyle)
sheet1.write(0,1,20, myFontStyle)
sheet1.write(1,0,Formula('AVERAGE(A1:B1)'), myFontStyle)
book.save('formula.xls')
wb = xlrd.open_workbook('formula.xls')
sh = wb.sheet_by_index(0)
for rownum in range(sh.nrows):
print sh.row_values(rownum)
The idea is to write some values to Excel file, have some excel
specific functions like LogNormal, StdDev etc and read the calculated
values using XLRD.
By running the above code, I get the following results which are
undesirable:-
[10.0, 20.0]
[u'', '']
Ideally I should have got 15 on the second row. It writes the Excel
perfectly when I open it but XLRD does not return the results. I am
stuck with this for a very critical project. Request you to kindly
respond earliest.
Thanks and Regards
Tarun Pasrija
A:
Here is the answer I gave to the same question on the python-excel google-group yesterday.
[Background: I'm the author/maintainer of xlrd and the maintainer of xlwt]
Neither xlrd nor xlwt contains a formula evaluation engine. This is in common with other packages which are free (in any sense) and written in an interpreted language. This is documented in the tutorial that you can download via http://www.python-excel.org ... see pages 17 and 36.
If you break up your script into two pieces, execute the first, open the result XLS file with Excel/OOo calc/Gnumeric, [may need to hit F9 here to recalculate], save again, execute the 2nd script piece: xlrd will display the results.
Other possibilities:
(1) Ask on the gnumeric mailing list if it is possible to drive gnumeric programmatically to the extent of: open named XLS file, [re-]calculate all formulas, save as named XLS file (with the recalculated formula results included -- it is necessary to stress this because the last time I asked, the native gnumeric file format did NOT included the calculated formula results).
(2) You could ask the same question about Openoffice.org's calc program, perhaps on news:comp.lang.python and/or www.stackoverflow.com ... it has a set of APIs called "PyUNO"; last time I looked, most folk gave up trying to wade through and understand the humungous quantity of documentation. Any better news would I'm sure be gratefully received in the Python+spreadsheet world.
(3) "LogNormal" (I presume you mean LOGNORMDIST and/or LOGINV) and "StdDev" are scarcely Excel-specific. You could calculate your own results in Python; xlwt would need to be augmented to allow the caller to supply a result value for a Formula cell, instead of plugging in an invariant zero-length string as you noticed.
(4) Tell us your higher-level objectives ... we may be then able to come up with other suggestions.
Is this "very critical project" academic / for a charity / for a commercial enterprise? Have you considered Resolver One (http://www.resolversystems.com/products/resolver-one/) ? AFAIK, they offer discounts and their product is dirt-cheap anyway at about USD 100 per licence.
A:
You need to open it in Excel and resave it before running the second bit. xlwt/xlrd don't actually work out the formula themselves, so you'd need Excel to do that. I've just tested with OpenOffice, and it works after resaving the file.
Also, please tell me you are not using this method just to calculate an average? You can do that in Python very easily:
average = float(sum(mynumbers))/len(mynumbers)
(In Python 3, you can leave out the float())
| Facing problem with XLWT and XLRD - Reading and writing simultaneously | I am facing a problem with xlrd and xlwt. Pasting the sample code
below.
from xlwt import Workbook, Formula, XFStyle
import xlrd
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
myFontStyle = XFStyle()
myFontStyle.num_format_str = '0.00'
sheet1.write(0,0,10, myFontStyle)
sheet1.write(0,1,20, myFontStyle)
sheet1.write(1,0,Formula('AVERAGE(A1:B1)'), myFontStyle)
book.save('formula.xls')
wb = xlrd.open_workbook('formula.xls')
sh = wb.sheet_by_index(0)
for rownum in range(sh.nrows):
print sh.row_values(rownum)
The idea is to write some values to Excel file, have some excel
specific functions like LogNormal, StdDev etc and read the calculated
values using XLRD.
By running the above code, I get the following results which are
undesirable:-
[10.0, 20.0]
[u'', '']
Ideally I should have got 15 on the second row. It writes the Excel
perfectly when I open it but XLRD does not return the results. I am
stuck with this for a very critical project. Request you to kindly
respond earliest.
Thanks and Regards
Tarun Pasrija
| [
"Here is the answer I gave to the same question on the python-excel google-group yesterday.\n[Background: I'm the author/maintainer of xlrd and the maintainer of xlwt]\nNeither xlrd nor xlwt contains a formula evaluation engine. This is in common with other packages which are free (in any sense) and written in an i... | [
8,
2
] | [] | [] | [
"excel",
"python",
"xlrd",
"xlwt"
] | stackoverflow_0004198365_excel_python_xlrd_xlwt.txt |
Q:
IPython on Windows - No highlighting or Auto-complete
this has been an issue for a long time for me, but as I mainly develop using Linux I never really cared much about this problem till now.
iPython on Windows lacks various features.
I really miss color highlighting and auto-completion.
Edit: fixed highlighting by installing pyreadline
pip install pyreadline
Anyone already dealt with this?
A:
You need to install PyReadline,
documentation is here.
| IPython on Windows - No highlighting or Auto-complete | this has been an issue for a long time for me, but as I mainly develop using Linux I never really cared much about this problem till now.
iPython on Windows lacks various features.
I really miss color highlighting and auto-completion.
Edit: fixed highlighting by installing pyreadline
pip install pyreadline
Anyone already dealt with this?
| [
"You need to install PyReadline,\ndocumentation is here.\n"
] | [
21
] | [] | [] | [
"django",
"django_shell",
"ipython",
"python",
"windows"
] | stackoverflow_0004214354_django_django_shell_ipython_python_windows.txt |
Q:
Use file like objects for Tk().iconbitmap()
I am writing a program using Tkinter that is to be eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, either by locating the exe file or using a file-like object? I know that win32api can find the current exe file that's running, but I believe that py2exe extracts the original file to temp, and then runs it, so the original exe couldn't be found that way. I also thought of putting it in an include folder, but I don't know if the cwd would be set correctly for that. Thanks for the help in advance!
A:
Tk images have a -data option which lets you embed the image within the code. You just have to base64-encode the image. I think the image has to originally be in the GIF format.
Here's a working example:
import Tkinter as tk
root = tk.Tk()
data = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9P
T6Ai8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYY
fh8GIEvpoUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYw
YtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEi
gnKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5Fo
fsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
'''
img = tk.PhotoImage(data=data)
label = tk.Label(image=img)
label.pack()
root.mainloop()
A:
You can embedd the icon in the py2exe binary with the icon_resources option
setup(windows=[
{'script':'toto.py', "icon_resources": [(1, "toto.ico")]},
],
Then you can retrieve it with the windows api
import win32gui, win32api, win32con
from ctypes import c_int, windll
hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 13), True)
and then attach to a window as long as you know his HWND.
windll.user32.SendMessageA(c_int(hwnd), c_int(win32con.WM_SETICON), c_int(win32con.ICON_SMALL), c_int(hicon))
The 13 constant used in the LoadResource has been retrieved with a tool like ResourceHacker. In ResourceHacker, it corresponds to the folder name of the icon. I don't know how it is calculated by py2exe and if there is a way to force this value.
I don't know also if there is a pure TkInter way to do that and if the icon can be used as-is in a tkinter window.
I hope it helps
| Use file like objects for Tk().iconbitmap() | I am writing a program using Tkinter that is to be eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, either by locating the exe file or using a file-like object? I know that win32api can find the current exe file that's running, but I believe that py2exe extracts the original file to temp, and then runs it, so the original exe couldn't be found that way. I also thought of putting it in an include folder, but I don't know if the cwd would be set correctly for that. Thanks for the help in advance!
| [
"Tk images have a -data option which lets you embed the image within the code. You just have to base64-encode the image. I think the image has to originally be in the GIF format. \nHere's a working example:\nimport Tkinter as tk\nroot = tk.Tk()\ndata = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6... | [
3,
2
] | [] | [] | [
"py2exe",
"python",
"tkinter"
] | stackoverflow_0004211064_py2exe_python_tkinter.txt |
Q:
how to retrieve field value (values are itself string)in given line using regular expression in python
I am newbie to python,i am facing below issue please help me:
I read line by line from one file, each line having field name and its value,
now i have to find out field name and filevalue in the line.example of line is:
line=" A= 4 | B='567' |c=4|D='aaa' "
Since some field values are itself a string so I am unable to create regex to retrieve field name and filed value.
Please let me know regex for above example.
the output should be
A=4
B='567'
c=4
D='aaa'
A:
The simplest solution I can think of is converting each line into a dictionary. I assume that you don't have any quote marks or | marks in your strings (see my comments on the question).
result={} # Initialize a dictionary
for line in open('input.txt'): # Read file line by line in a memory-efficient way
# Split line to pairs using '|', split each pair using '='
pairs = [pair.split('=') for pair in line.split('|')]
for pair in pairs:
key, value = pair[0].strip(), pair[1].strip()
try: # Try an int conversion
value=int(value)
except: # If fails, strip quotes
value=value.strip("'").strip('"')
result[key]=value # Add current item to the results dictionary
which, for the following input:
A= 4 | B='567' |c=4|D='aaa'
E= 4 | F='567' |G=4|D='aaa'
Would give:
{'A': 4, 'c': 4, 'B': '567', 'E': 4, 'D': 'aaa', 'G': 4, 'F': '567'}
Notes:
If you consider '567' to be a number, you can strip the " and ' before trying to convert it to integer.
If you need to take floats into account, you can try value=float(value). Remeber to do it after the int convertion attempt, because every int is also a float.
A:
try this one:
import re
line = " A= 4 | B='567' |c=4|D='aaa' "
re.search( '(?P<field1>.*)=(?P<value1>.*)\|(?P<field2>.*)=(?P<value2>.*)\|(?P<field3>.*)=(?P<value3>.*)\|(?P<field4>.*)=(?P<value4>.*)', line ).groups()
output:
(' A', ' 4 ', ' B', "'567' ", 'c', '4', 'D', "'aaa' ")
you can also try using \S* instead of .* if your fields and values do not contain whitespaces. this will eliminate the whitespaces from output:
re.search( '(?P<field1>\S*)\s*=\s*(?P<value1>\S*)\s*\|\s*(?P<field2>\S*)\s*=\s*(?P<value2>\S*)\s*\|\s*(?P<field3>\S*)\s*=\s*(?P<value3>\S*)\s*\|\s*(?P<field4>\S*)\s*=\s*(?P<value4>\S*)', line ).groupdict()
output:
{'field1': 'A',
'field2': 'B',
'field3': 'c',
'field4': 'D',
'value1': '4',
'value2': "'567'",
'value3': '4',
'value4': "'aaa'"
}
this will create related groups:
[ re.search( '\s*([^=]+?)\s*=\s*(\S+)', group ).groups( ) for group in re.findall( '([^=|]*\s*=\s*[^|]*)', line ) ]
output:
[('A', '4'), ('B', "'567'"), ('c', '4'), ('D', "'aaa'")]
does it help?
A:
Assuming you don't have nasty things like nested quotes or unmatched quotes you can do it all with split and strip:
>>> line = " A= 4 | B='567' |c=4|D='aaa' "
>>> values = dict((x.strip(" '"), y.strip(" '")) for x,y in (entry.split('=') for entry in line.split('|')))
>>> values
{'A': '4', 'c': '4', 'B': '567', 'D': 'aaa'}
| how to retrieve field value (values are itself string)in given line using regular expression in python | I am newbie to python,i am facing below issue please help me:
I read line by line from one file, each line having field name and its value,
now i have to find out field name and filevalue in the line.example of line is:
line=" A= 4 | B='567' |c=4|D='aaa' "
Since some field values are itself a string so I am unable to create regex to retrieve field name and filed value.
Please let me know regex for above example.
the output should be
A=4
B='567'
c=4
D='aaa'
| [
"The simplest solution I can think of is converting each line into a dictionary. I assume that you don't have any quote marks or | marks in your strings (see my comments on the question).\nresult={} # Initialize a dictionary\nfor line in open('input.txt'): # Read file line by line in a memory-e... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004213300_python.txt |
Q:
Python loop for image and pil module
I'm using PIL and Image modes in Python.
I want to create an image with this code:
imagesize = (12,12)
image = Image.new("RGB",imagesize,color=None)
I will use this function to put pixels on my image:
.putpixel(xy, color)
color is in a list of tuples. For exemple:
RGB = [((255, 255, 255),(207, 103, 36),(204, 93, 21),(204, 93, 21),(204, 93, 21), (.......some more RGB tuples.....)]
I need a loop that in .putpixel(xy, color):
color is incremented one step every time. For example RGB[0], next loop RGB[1] and so on.
While this loop is being made the x and y is the more difficult to me.
x goes from 1 to 12 (image size) while y is 0 and then, when x reaches imagesize it returns to 1 to 12 but y is now 1. The loop is ended when x and both reach to the end of image size.
Can anyone help me? I'm new in Python.
Regards,
Favolas
EDIT
P:S - Forgot to say that since this is for a school project I cant use any methods besides img.new, img.show and img.outpixel
A:
Ok, my comment from above should've really gone into an answer. I should catch some sleep. You can basically just put your pixel data into the image at once. The putdata method of a PIL.Image accepts a list of tuples that make up the pixels of the images. So:
img = PIL.Image.new("RGB", (12, 12))
img.show() # see a black image
pixels = [(255,0,0)]*(12*12)
img.putdata(pixels)
img.show() # see a red image
A:
It depends on how you want to put RGB colors. For example:
for y in range(12):
for x in range(12):
img.putpixel(x, y, RGB[(x + 12*y)%len(RBG)]
will put 0 to N RBG colors in 0 to N pixels, 0 to N RGBs to 0+N, 2N pixels and so on.
There are another options - choose the color randomly:
import random
...
for y in range(12):
for x in range(12):
img.putpixel(x, y, RBG[random.randint(0, len(RGB)-1)]
Optimization for both cases is left as an exercise.
A:
If you have nested loops, i from 0 to 11 and j from 0 to 11, then to index incrementally into a one-dimensional vector you need to get X[j + i * 11].
>>> for i in range(5):
... for j in range(5):
... print j + i*5
will print 0 to 24.
See other answers for better ways to fill Images, and there are probably more pythonic ways of doing this too. But this is the generic answer!
Note this is for variables that start at ZERO, not ONE. For your 12x12 pixel image the valid xy range is from 0 to 11.
A:
If we have these two lists:
xy = [(1,2),(3,4),(5,6),(7,8)]
rgb = [(0,0,255), (0,255,0), (255,0,0), (255,255,0), (255,255,255)]
We can map the XY list to the RGB list into a dictionary:
d = dict(zip(xy,rgb))
Which looks like this:
>>> print(d)
{(1, 2): (0, 0, 255), (5, 6): (255, 0, 0), (3, 4): (0, 255, 0), (7, 8): (255, 255, 0)}
So we now have a dictionary, the key is the XY and the value is the corresponding RGB. Now we can map these key-value pairs using list comprehension:
[putpixel(x,col) for x,col in d.items()]
As a test, a mock putpixel() method that prints the inputs verify the results:
def putpixel(xy,col):
print('%s set to %s' % (xy,col))
>>> result = [putpixel(x,col) for x,col in d.items()]
(1, 2) set to (0, 0, 255)
(5, 6) set to (255, 0, 0)
(3, 4) set to (0, 255, 0)
(7, 8) set to (255, 255, 0)
List comprehension usually returns a list of processed items, in this case we don't return a result from putpixel(), thus our result list would contain empties.
| Python loop for image and pil module | I'm using PIL and Image modes in Python.
I want to create an image with this code:
imagesize = (12,12)
image = Image.new("RGB",imagesize,color=None)
I will use this function to put pixels on my image:
.putpixel(xy, color)
color is in a list of tuples. For exemple:
RGB = [((255, 255, 255),(207, 103, 36),(204, 93, 21),(204, 93, 21),(204, 93, 21), (.......some more RGB tuples.....)]
I need a loop that in .putpixel(xy, color):
color is incremented one step every time. For example RGB[0], next loop RGB[1] and so on.
While this loop is being made the x and y is the more difficult to me.
x goes from 1 to 12 (image size) while y is 0 and then, when x reaches imagesize it returns to 1 to 12 but y is now 1. The loop is ended when x and both reach to the end of image size.
Can anyone help me? I'm new in Python.
Regards,
Favolas
EDIT
P:S - Forgot to say that since this is for a school project I cant use any methods besides img.new, img.show and img.outpixel
| [
"Ok, my comment from above should've really gone into an answer. I should catch some sleep. You can basically just put your pixel data into the image at once. The putdata method of a PIL.Image accepts a list of tuples that make up the pixels of the images. So:\nimg = PIL.Image.new(\"RGB\", (12, 12))\nimg.show() # s... | [
2,
1,
1,
1
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0004214382_python_python_imaging_library.txt |
Q:
Reducing memory footprint with multiprocessing?
One of my applications runs about 100 workers. It started out as a threading application, but performance (latency) issues were hit. So I converted those workers to multiprocessing.Processes. The benchmark below shows that the reduction in load was achieved at the cost of more memory usage (factor 6).
So where precisely does the memory usage come from if Linux uses cow and the workers do not share any data?
How can I reduce the memory footprint? (Alternative question: How can I reduce the load for threading?)
Benchmarks on Linux 2.6.26, 4 CPUs 2G RAM:
(Note that cpu usage is given in % of one cpu, so full load is 400%. The numbers are derived from looking at Munin graphs.)
| threading | multiprocessing
------------------+-----------+----------------
memory usage | ~0.25GB | ~1.5GB
context switches | ~1.5e4/s | ~5e2/s
system cpu usage | ~30% | ~3%
total cpu usage | ~100% | ~50%
load avg | ~1.5 | ~0.7
Background: The application is processing events from the network and storing some of them in a MySQL database.
A:
My understanding is that with dynamic languages, like Python, copy-on-write is not as effective as a lot more memory gets written to (and therefore copied) after forking. As the Python interpretor progresses through the program there's a lot more going on than just your code. For example reference-counting - very object will be written too pretty quickly as reference counting needs to write the reference count to memory (triggering a copy).
With that in mind you probably need to have a hybrid threading/processing approach. Have multiple process to take advantage of multiple cores etc, but have each one run multiple threads (so you can deal with the level of concurrency you need). You'll just need to experiment with how many threads vs processes you run.
| Reducing memory footprint with multiprocessing? | One of my applications runs about 100 workers. It started out as a threading application, but performance (latency) issues were hit. So I converted those workers to multiprocessing.Processes. The benchmark below shows that the reduction in load was achieved at the cost of more memory usage (factor 6).
So where precisely does the memory usage come from if Linux uses cow and the workers do not share any data?
How can I reduce the memory footprint? (Alternative question: How can I reduce the load for threading?)
Benchmarks on Linux 2.6.26, 4 CPUs 2G RAM:
(Note that cpu usage is given in % of one cpu, so full load is 400%. The numbers are derived from looking at Munin graphs.)
| threading | multiprocessing
------------------+-----------+----------------
memory usage | ~0.25GB | ~1.5GB
context switches | ~1.5e4/s | ~5e2/s
system cpu usage | ~30% | ~3%
total cpu usage | ~100% | ~50%
load avg | ~1.5 | ~0.7
Background: The application is processing events from the network and storing some of them in a MySQL database.
| [
"My understanding is that with dynamic languages, like Python, copy-on-write is not as effective as a lot more memory gets written to (and therefore copied) after forking. As the Python interpretor progresses through the program there's a lot more going on than just your code. For example reference-counting - ver... | [
3
] | [] | [] | [
"benchmarking",
"memory_management",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0004214775_benchmarking_memory_management_multiprocessing_multithreading_python.txt |
Q:
How to use Post_save in Django
I am trying to add points to a User's profile after they submit a comment- using the Django comment framework. I think I need to use a post_save but am not sure to be perfectly honest.
Here is what I have as a method in my models.py:
def add_points(request, Comment):
if Comment.post_save():
request.user.get_profile().points += 2
request.user.get_profile().save()
From the examples of post_save I've found, this is far from what is shown - so I think I am way off the mark.
Thank you for your help.
A:
Unfortunately this makes no sense at all.
Firstly, this can't be a method, as it doesn't have self as the first parameter.
Secondly, it seems to be taking the class, not an instance. You can't save the class itself, only an instance of it.
Thirdly, post_save is not a method of the model (unless you've defined one yourself). It's a signal, and you don't call a signal, you attach a signal handler to it and do logic there. You can't return data from a signal to a method, either.
And finally, the profile instance that you add 2 to will not necessarily be the same as the one you save in the second line, because Django model instances don't have identity. Get it once and put it into a variable, then save that.
The Comments framework defines its own signals that you can use instead of the generic post_save. So, what you actually need is to register a signal handler on comment_was_posted. Inside that handler, you'll need to get the user's profile, and update that.
def comment_handler(sender, comment, request, **kwargs):
profile = request.user.get_profile()
profile.points += 2
profile.save()
from django.contrib.comments.signals import comment_was_posted
comment_was_posted.connect(comment_handler, sender=Comment)
| How to use Post_save in Django | I am trying to add points to a User's profile after they submit a comment- using the Django comment framework. I think I need to use a post_save but am not sure to be perfectly honest.
Here is what I have as a method in my models.py:
def add_points(request, Comment):
if Comment.post_save():
request.user.get_profile().points += 2
request.user.get_profile().save()
From the examples of post_save I've found, this is far from what is shown - so I think I am way off the mark.
Thank you for your help.
| [
"Unfortunately this makes no sense at all.\nFirstly, this can't be a method, as it doesn't have self as the first parameter.\nSecondly, it seems to be taking the class, not an instance. You can't save the class itself, only an instance of it.\nThirdly, post_save is not a method of the model (unless you've defined o... | [
2
] | [] | [] | [
"django",
"django_comments",
"django_models",
"python"
] | stackoverflow_0004214680_django_django_comments_django_models_python.txt |
Q:
i have a string variable which comes with function names, how do I call the function in Python?
I have a string variable which comes with different function names, and I have a file which contains an often different set of functions which matchs the content of the string, how do I call that function in Python?
Example:
In File 1
def function1: ...
def function2: ...
def function3: ...
In File 2
functionname = "function2"
I need to call the function2 from the File1 from this file
A:
myfunction = getattr(mymodule, functionname)
myfunction()
A:
eval("function2")()
getattr(<module>, fname)()
A:
name = 'function2'
assert re.match('^(?i)[_a-z][_a-z0-9]*$', name)
eval(name)()
| i have a string variable which comes with function names, how do I call the function in Python? | I have a string variable which comes with different function names, and I have a file which contains an often different set of functions which matchs the content of the string, how do I call that function in Python?
Example:
In File 1
def function1: ...
def function2: ...
def function3: ...
In File 2
functionname = "function2"
I need to call the function2 from the File1 from this file
| [
"myfunction = getattr(mymodule, functionname)\nmyfunction()\n\n",
"eval(\"function2\")()\ngetattr(<module>, fname)()\n",
"name = 'function2'\n\nassert re.match('^(?i)[_a-z][_a-z0-9]*$', name)\n\neval(name)()\n\n"
] | [
6,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004214261_python.txt |
Q:
UnicodeDecodeError while running Django dev server
UnicodeDecodeError
Appears while trying to access any of the files from site media folder.
Full traceback presented in debug mode:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/site-media/img/image.png
Django Version: 1.2.3
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.markup',
'special']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "C:\Languages\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Languages\Python27\lib\site-packages\django\views\static.py" in serve
59. mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'
File "C:\Languages\Python27\lib\mimetypes.py" in guess_type
294. init()
File "C:\Languages\Python27\lib\mimetypes.py" in init
355. db.read_windows_registry()
File "C:\Languages\Python27\lib\mimetypes.py" in read_windows_registry
260. for ctype in enum_types(mimedb):
File "C:\Languages\Python27\lib\mimetypes.py" in enum_types
250. ctype = ctype.encode(default_encoding) # omit in 3.x!
Exception Type: UnicodeDecodeError at /site-media/img/image.png
Exception Value: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)
A:
It seems to be a problem in Python 2.7 mimetypes.py. Look at the following discussion thread:
http://groups.google.com/group/django-users/browse_thread/thread/613909b35a7462a0
There is a link to a russian article which says when google-translated:
The presence of the standard library
source Python-and allowed us to find
the problem pretty quickly. Windows XP. I am using
Windows XP.
[HKEY_CLASSES_ROOT\CLSID{4063BE15-3B08-470D-A0D5-B37161CFFD69}\EnableFullPage\MIME]
In my case the
problem was that in the registry under
[HKEY_CLASSES_ROOT \ CLSID \
{4063BE15-3B08-470D-A0D5-B37161CFFD69}
\ EnableFullPage \ MIME] contain
subsections containing the name of the
Cyrillic alphabet. If you delete these
keys, they are automatically
re-create. Therefore helped
to rename, just replaced the Cyrillic
alphabet in Latin.
Here is the article:
http://translate.google.fr/translate?js=n&prev=_t&hl=fr&ie=UTF-8&layout=2&eotf=1&sl=ru&tl=en&u=http%3A%2F%2Fvictor-k-development.blogspot.com%2F2010%2F07%2Funicodedecodeerror-django.html
| UnicodeDecodeError while running Django dev server | UnicodeDecodeError
Appears while trying to access any of the files from site media folder.
Full traceback presented in debug mode:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/site-media/img/image.png
Django Version: 1.2.3
Python Version: 2.7.0
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.markup',
'special']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "C:\Languages\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Languages\Python27\lib\site-packages\django\views\static.py" in serve
59. mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'
File "C:\Languages\Python27\lib\mimetypes.py" in guess_type
294. init()
File "C:\Languages\Python27\lib\mimetypes.py" in init
355. db.read_windows_registry()
File "C:\Languages\Python27\lib\mimetypes.py" in read_windows_registry
260. for ctype in enum_types(mimedb):
File "C:\Languages\Python27\lib\mimetypes.py" in enum_types
250. ctype = ctype.encode(default_encoding) # omit in 3.x!
Exception Type: UnicodeDecodeError at /site-media/img/image.png
Exception Value: 'ascii' codec can't decode byte 0xe0 in position 0: ordinal not in range(128)
| [
"It seems to be a problem in Python 2.7 mimetypes.py. Look at the following discussion thread:\nhttp://groups.google.com/group/django-users/browse_thread/thread/613909b35a7462a0\nThere is a link to a russian article which says when google-translated:\n\nThe presence of the standard library\n source Python-and allo... | [
5
] | [] | [] | [
"django",
"encoding",
"python"
] | stackoverflow_0004214151_django_encoding_python.txt |
Q:
Transition from small scripts to bigger apps is not easy
I believe that readability and the KISS principle are the most important things in programming. That's why I use Python :)
And here is exact situation, which I encounter very often:
Say, I have a nice and clean script, which is a wrapper for database handling:
import database_schema as schema
loader = schema.Loader("sqlite:///var/database.db")
session = loader.session
def addUser(name, full_name, password):
user = schema.User(name, full_name, password)
session.add(user)
session.commit()
def listUsers():
all_users = session.query(schema.User).all()
return all_users
Which is used like this:
import database
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
At some point, I want to rewrite that module, so that it can work with databases on different path (for unit testing, for instance).
So, what are my options?
The most intuitive thing is to add database_path == "" variable, and then... what? Setting it with setPath(new_path) function, and then adding exception (if database_path == "": raise SomeException) to every single function, is just ugly and shouldn't be done by anyone.
Full featured class, with setting the self._database_path at initialization time.
Which is then used this way:
from database import Database
database = Database("sqlite:///var/database.db")
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
This is already more lines of code than in the first example, and addition of the naming problem: having a class called Database in the module database is kind of dumb, no?
Sorry for the long read, here my final questions:
Why there's no such thing as __init__ functions for modules, in Python?
Am I missing something (static class variables, etc), that can do what I want (a constant set at the import time) the easy and clean way, that is still not far away from a module with a bunch of simple functions that was at first?
P.S. sorry for my English.
Edit:
So, to make this clear, how this code may look like in my imaginative Python universe:
import database_schema as schema
def __init__(database_path):
loader = schema.Loader(database_path)
global session
session = loader.session
def addUser(name, full_name, password):
user = schema.User(name, full_name, password)
session.add(user)
session.commit()
def listUsers():
all_users = session.query(schema.User).all()
return all_users
And used like this:
import database("sqlite:///var/database.db")
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
A:
A module is a Python object with arbitrarily named attributes that you can bind and reference. The Python code for a module named mod normally resides in a file named mod.py. When you try to import it, a new namespace is created that contains all the attributes of that module.
Though all said, it is not the same as class and creation of object instances of that class.
These are different abstractions and should be used as such.
instead of testing for
if database_path == "":
....
do it pythonic way
if database_path:
....
And rather than raising exception, you could use assert
assert database_path != "", 'database path empty'
A module does not exist in flavors like object instances of class does. Importing a module will create a namespace with the same set of attributes every time you import it.
In such situation, init may not make much sense.
There is nothing wrong with the second form of code you have provided.
and you if you do not want to do that them some of the above idioms may ease your pain :)
A:
For this type of situations, I use the optional parameter.
def addUser(name, full_name, password, _loader=None):
user = schema.User(name, full_name, password)
if (_loader is None):
# Use global values.
session.add(user)
session.commit()
else:
_session = _loader.session
# ...
I, myself, stay away from initializing stuffs like this at module loading. Imagine you want to create documentation with tools like epydoc. It makes no sense to create a connection in that context just because epydoc loads the module. I would definitely go with the class approach.
A:
The only solution that I found is to load configuration from a file:
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read('config.ini')
def getSession():
loader = schema.Loader( config.get('Global', 'database') )
return( loader.session )
...
Which is not perfect: name of the file itself is hardcoded, and if you want to do unit tests on different (for instance, empty) database, you have to reassign config and then revert it back when you done, not very elegant.
| Transition from small scripts to bigger apps is not easy | I believe that readability and the KISS principle are the most important things in programming. That's why I use Python :)
And here is exact situation, which I encounter very often:
Say, I have a nice and clean script, which is a wrapper for database handling:
import database_schema as schema
loader = schema.Loader("sqlite:///var/database.db")
session = loader.session
def addUser(name, full_name, password):
user = schema.User(name, full_name, password)
session.add(user)
session.commit()
def listUsers():
all_users = session.query(schema.User).all()
return all_users
Which is used like this:
import database
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
At some point, I want to rewrite that module, so that it can work with databases on different path (for unit testing, for instance).
So, what are my options?
The most intuitive thing is to add database_path == "" variable, and then... what? Setting it with setPath(new_path) function, and then adding exception (if database_path == "": raise SomeException) to every single function, is just ugly and shouldn't be done by anyone.
Full featured class, with setting the self._database_path at initialization time.
Which is then used this way:
from database import Database
database = Database("sqlite:///var/database.db")
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
This is already more lines of code than in the first example, and addition of the naming problem: having a class called Database in the module database is kind of dumb, no?
Sorry for the long read, here my final questions:
Why there's no such thing as __init__ functions for modules, in Python?
Am I missing something (static class variables, etc), that can do what I want (a constant set at the import time) the easy and clean way, that is still not far away from a module with a bunch of simple functions that was at first?
P.S. sorry for my English.
Edit:
So, to make this clear, how this code may look like in my imaginative Python universe:
import database_schema as schema
def __init__(database_path):
loader = schema.Loader(database_path)
global session
session = loader.session
def addUser(name, full_name, password):
user = schema.User(name, full_name, password)
session.add(user)
session.commit()
def listUsers():
all_users = session.query(schema.User).all()
return all_users
And used like this:
import database("sqlite:///var/database.db")
database.addUser("mike", "Mike Driscoll", "password")
database.listUsers()
| [
"A module is a Python object with arbitrarily named attributes that you can bind and reference. The Python code for a module named mod normally resides in a file named mod.py. When you try to import it, a new namespace is created that contains all the attributes of that module.\nThough all said, it is not the same ... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003861916_python.txt |
Q:
Parsing an xml file and storing it into a database
Is there a generic/automatic way in R or in python to parse xml files with its nodes and attributes, automatically generate mysql tables for storing that information and then populate those tables.
A:
Regarding
Is there a generic/automatic way in R
to parse xml files with its nodes and
attributes, automatically generate
mysql tables for storing that
information and then populate those
tables.
the answer is a good old yes you can, at least in R.
The XML package for R can read XML documents and return R data.frame types in a single call using the xmlToDataFrame() function.
And the RMySQL package can transfer data.frame objects to the database in a single command---including table creation if need be---using the dbWriteTable() function defined in the common DBI backend for R and provided for MySQL by RMySQL.
So in short: two lines can do it, so you can easily write yourself a new helper function that does it along with a commensurate amount of error checking.
A:
They're three separate operations: parsing, table creation, and data population. You can do all three with python, but there's nothing "automatic" about it. I don't think it's so easy.
For example, XML is hierarchical and SQL is relational, set-based. I don't think it's always so easy to get a good relational schema for every single XML stream you can encounter.
A:
There's the XML package for reading XML into R, and the RMySQL package for writing data from R into MySQL.
Between the two there's a lot of work. XML surpasses the scope of a RDBMS like MySQL so something that could handle any XML thrown at it would be either ridiculously complex or trivially useless.
A:
We do something like this at work sometimes but not in python. In that case, each usage requires a custom program to be written. We only have a SAX parser available. Using an XML decoder to get a dictionary/hash in a single step would help a lot.
At the very least you'd have to tell it which tags map to which to tables and fields, no pre-existing lib can know that...
| Parsing an xml file and storing it into a database | Is there a generic/automatic way in R or in python to parse xml files with its nodes and attributes, automatically generate mysql tables for storing that information and then populate those tables.
| [
"Regarding\n\nIs there a generic/automatic way in R\n to parse xml files with its nodes and\n attributes, automatically generate\n mysql tables for storing that\n information and then populate those\n tables.\n\nthe answer is a good old yes you can, at least in R. \nThe XML package for R can read XML document... | [
5,
4,
1,
0
] | [] | [] | [
"mysql",
"python",
"r",
"xml"
] | stackoverflow_0004213696_mysql_python_r_xml.txt |
Q:
kill process with python
I need to make a script that gets from the user the following:
1) Process name (on linux).
2) The log file name that this process write to it.
It needs to kill the process and verify that the process is down.
Change the log file name to a new file name with the time and date.
And then run the process again, verify that it's up in order it will continue to write to the log file.
Thanks in advance for the help.
A:
You can retrieve the process id (PID) given it name using pgrep command like this:
import subprocess
import signal
import os
from datetime import datetime as dt
process_name = sys.argv[1]
log_file_name = sys.argv[2]
proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE)
# Kill process.
for pid in proc.stdout:
os.kill(int(pid), signal.SIGTERM)
# Check if the process that we killed is alive.
try:
os.kill(int(pid), 0)
raise Exception("""wasn't able to kill the process
HINT:use signal.SIGKILL or signal.SIGABORT""")
except OSError as ex:
continue
# Save old logging file and create a new one.
os.system("cp {0} '{0}-dup-{1}'".format(log_file_name, dt.now()))
# Empty the logging file.
with open(log_file_name, "w") as f:
pass
# Run the process again.
os.sytsem("<command to run the process>")
# you can use os.exec* if you want to replace this process with the new one which i think is much better in this case.
# the os.system() or os.exec* call will failed if something go wrong like this you can check if the process is runninh again.
Hope this can help
A:
If you know how to do it in the terminal, then you could use the following:
import os
os.system("your_command_here; second_command; third; etc")
So that you end up having sort of a mini shell script inside python. I would also consider making this shell script exist on its own and then call it from python:
import os
os.system("path/to/my_script.sh")
Cheers!
| kill process with python | I need to make a script that gets from the user the following:
1) Process name (on linux).
2) The log file name that this process write to it.
It needs to kill the process and verify that the process is down.
Change the log file name to a new file name with the time and date.
And then run the process again, verify that it's up in order it will continue to write to the log file.
Thanks in advance for the help.
| [
"You can retrieve the process id (PID) given it name using pgrep command like this:\nimport subprocess\nimport signal\nimport os\nfrom datetime import datetime as dt\n\n\nprocess_name = sys.argv[1]\nlog_file_name = sys.argv[2]\n\n\nproc = subprocess.Popen([\"pgrep\", process_name], stdout=subprocess.PIPE) \n\n# Kil... | [
21,
2
] | [] | [] | [
"kill",
"linux",
"process",
"python"
] | stackoverflow_0004214773_kill_linux_process_python.txt |
Q:
Any benefits of turning libraries for Django into an App?
When developing some functionality for use with django. In this case a middleware and some other utils like a decorator. Is there any upside of making it into a Django App. The library has no models, so there is no point in a models.py (which you need to make django see it as an app), or putting into INSTALLED_APPS. But I see people doing it anyway, what are the benefits?
A:
You'll have to make it an app if you want to provide templates, template tags or filters with your library. Otherwise, Django won't pick them up.
A:
In my opinion, there is no benefits for middleware and decorators. My rule of thumb: If it has a model and/or views, I'll make it an app..
Even for custom template tags I chose to make it an egg and import it into the apps that will be using it.
Good question.
A:
IMO it's handy to instantly see the list of used apps/libraries- if you miss anything, you can just pip install or easy_install it in the blink of an eye.
| Any benefits of turning libraries for Django into an App? | When developing some functionality for use with django. In this case a middleware and some other utils like a decorator. Is there any upside of making it into a Django App. The library has no models, so there is no point in a models.py (which you need to make django see it as an app), or putting into INSTALLED_APPS. But I see people doing it anyway, what are the benefits?
| [
"You'll have to make it an app if you want to provide templates, template tags or filters with your library. Otherwise, Django won't pick them up.\n",
"In my opinion, there is no benefits for middleware and decorators. My rule of thumb: If it has a model and/or views, I'll make it an app..\nEven for custom templa... | [
2,
1,
0
] | [] | [] | [
"django",
"django_apps",
"python"
] | stackoverflow_0004213138_django_django_apps_python.txt |
Q:
Why does this get a syntax error when exec() is called?
I have a database of questions, and a few of those questions have need of special validation. So, I added a field to my model called py_validation and when those questions are answered, I validate them by running the code that is stored in py_validation. When I paste the code into the interpereter, it works correctly, but when I pass it into exec, it fails with the error:
Traceback (most recent call last):
File "<string>", line 2, in <fragment>
invalid syntax: <string>, line 2, pos 31
The code looks like:
# This code relies on the field type being a char field
if len(value.split('\n')) < 5:
raise ValidationError(_("You must specify at least 5 widgets, one per line"))
super(CharField, self).validate(value)
I'm calling it using:
def do_py_validate(field, value):
exec field.py_validation
so that variable value is in local scope while executing. Doesn't quite make sense that the code that works just fine, bails when executed like this.
A:
Turns out to have a simple answer. The string contained \r characters that python was not happy swallowing. The answer came as I was trying to figure out how to make a file like object to read the string from. The solution is:
def do_py_validate(field, value):
exec field.py_validation.replace('\r', '')
This was almost as much fun as programming in Whitespace.
| Why does this get a syntax error when exec() is called? | I have a database of questions, and a few of those questions have need of special validation. So, I added a field to my model called py_validation and when those questions are answered, I validate them by running the code that is stored in py_validation. When I paste the code into the interpereter, it works correctly, but when I pass it into exec, it fails with the error:
Traceback (most recent call last):
File "<string>", line 2, in <fragment>
invalid syntax: <string>, line 2, pos 31
The code looks like:
# This code relies on the field type being a char field
if len(value.split('\n')) < 5:
raise ValidationError(_("You must specify at least 5 widgets, one per line"))
super(CharField, self).validate(value)
I'm calling it using:
def do_py_validate(field, value):
exec field.py_validation
so that variable value is in local scope while executing. Doesn't quite make sense that the code that works just fine, bails when executed like this.
| [
"Turns out to have a simple answer. The string contained \\r characters that python was not happy swallowing. The answer came as I was trying to figure out how to make a file like object to read the string from. The solution is:\ndef do_py_validate(field, value):\n exec field.py_validation.replace('\\r', '')\... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0004215660_python.txt |
Q:
Can't "define" two databases in the same file of Python?
I've just started learning Python and I'm slowly getting the hang of it, but I've faced a problem.
I'm trying to make a simple website with articles using Google's App Launcher SDK.
Now, everything worked fine when I followed the little guide in Google's site, but now I want to create another database:
class Articles(db.Model):
title = db.TextProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
No error here.
I then try to make a query, fetch all info and post it into a template:
class Articles(webapp.RequestHandler):
def get(self):
articles_query = Articles.all().order('-date')
articles = articles_query.fetch(10)
template_values = {'articles': articles}
path = os.path.join(os.path.dirname(__file__), 'articles.html')
self.response.out.write(template.render(path, template_values))
Here I received an error:
line 45, in get
articles_query = Articles.all().order('-date')
AttributeError: type object 'Articles' has no attribute 'all'
I basically copied the query from Google's tutorial and just change the variables, yet it doesn't work.
Any ideas?
A:
It's not that you've defined two databases, but that you've tried to create two classes called Articles. Python can't keep both of them in its head at once, so once you made class Articles(webapp.RequestHandler), it replaced class Articles(db.Model).
webapp.RequestHandler doesn't have an all() method, and you've not defined one in the second Articles class. That's why you get the particular error that you do.
You should use different names for your classes.
A:
I would refactor in this way *:
rename class Articles(webapp.RequestHandler) in class ArticlesHandler(webapp.RequestHandler)
move your Articles model in a separate file called models.py
add from models import Articles to your webhandlers file
Have a Handler suffix help you to distinguish canonical classes from Web handlers;
a different models.py module isolates your model implementations in one place and could be useful when your project will become more complex.
* step 1 is enough for resolving your specific issue
| Can't "define" two databases in the same file of Python? | I've just started learning Python and I'm slowly getting the hang of it, but I've faced a problem.
I'm trying to make a simple website with articles using Google's App Launcher SDK.
Now, everything worked fine when I followed the little guide in Google's site, but now I want to create another database:
class Articles(db.Model):
title = db.TextProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
No error here.
I then try to make a query, fetch all info and post it into a template:
class Articles(webapp.RequestHandler):
def get(self):
articles_query = Articles.all().order('-date')
articles = articles_query.fetch(10)
template_values = {'articles': articles}
path = os.path.join(os.path.dirname(__file__), 'articles.html')
self.response.out.write(template.render(path, template_values))
Here I received an error:
line 45, in get
articles_query = Articles.all().order('-date')
AttributeError: type object 'Articles' has no attribute 'all'
I basically copied the query from Google's tutorial and just change the variables, yet it doesn't work.
Any ideas?
| [
"It's not that you've defined two databases, but that you've tried to create two classes called Articles. Python can't keep both of them in its head at once, so once you made class Articles(webapp.RequestHandler), it replaced class Articles(db.Model).\nwebapp.RequestHandler doesn't have an all() method, and you've ... | [
7,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004215694_google_app_engine_python.txt |
Q:
Change content of multiline file into a list
How can I parse through the following file, and turn each line to an element of a list (there is a whitespace at the beginning of each line) ? Unfortunately I've always sucked at regex :/ So turn this:
32.42.4.120', '32.42.4.127
32.42.5.128', '32.42.5.255
32.42.15.136', '32.42.15.143
32.58.129.0', '32.58.129.7
32.58.131.0', '32.58.131.63
46.7.0.0', '46.7.255.255
into a list :
('32.42.4.120', '32.42.4.127'),
('32.42.5.128', '32.42.5.255'),
('32.42.15.136', '32.42.15.143'),
('32.58.129.0', '32.58.129.7'),
('32.58.131.0', '32.58.131.63'),
A:
no regex needed:
l = []
with open("name_file", "r") as f:
for line in f:
l.append(line.split(", "))
if you want to remove first space and to have tuple you can do:
l = []
with open("name_file", "r") as f:
for line in f:
data = line.split(", ")
l.append((data[0].strip(), data[1].strip()))
A:
How about this? (If I am wrong, at least let me know before down-voting)
>>> x = [tuple(line.strip().split("', '")) for line in open('file')]
>>> x
[('32.42.4.120', '32.42.4.127'), ('32.42.5.128', '32.42.5.255'), ('32.42.15.136', '32.42.15.143'), ('32.58.129.0', '32.58.129.7'), ('32.58.131.0', '32.58.131.63'), ('46.7.0.0', '46.7.255.255')]
A:
l = []
f = open("test_data.txt")
for line in f:
elems = line[1:-1].split("', '")
l.append((elems[0], elems[1]))
f.close()
print l
Output:
[('32.42.4.120', '32.42.4.127'), ('32.42.5.128', '32.42.5.255'), ('32.42.15.136', '32.42.15.143'), ('32.58.129.0', '32.58.129.7'), ('32.58.131.0', '32.58.131.63'), ('46.7.0.0', '46.7.255.25')]
| Change content of multiline file into a list | How can I parse through the following file, and turn each line to an element of a list (there is a whitespace at the beginning of each line) ? Unfortunately I've always sucked at regex :/ So turn this:
32.42.4.120', '32.42.4.127
32.42.5.128', '32.42.5.255
32.42.15.136', '32.42.15.143
32.58.129.0', '32.58.129.7
32.58.131.0', '32.58.131.63
46.7.0.0', '46.7.255.255
into a list :
('32.42.4.120', '32.42.4.127'),
('32.42.5.128', '32.42.5.255'),
('32.42.15.136', '32.42.15.143'),
('32.58.129.0', '32.58.129.7'),
('32.58.131.0', '32.58.131.63'),
| [
"no regex needed:\nl = []\n\nwith open(\"name_file\", \"r\") as f:\n for line in f:\n l.append(line.split(\", \"))\n\nif you want to remove first space and to have tuple you can do:\nl = []\n\nwith open(\"name_file\", \"r\") as f:\n for line in f:\n data = line.split(\", \")\n l.append((data[0... | [
1,
1,
1
] | [] | [] | [
"list",
"parsing",
"python",
"regex"
] | stackoverflow_0004215840_list_parsing_python_regex.txt |
Q:
Python Generator Function Names -- is a prefix helpful?
Most functions are easy to name. Generally, a function name is based on what it does or the type of result it produces.
In the case of a generator function, however, the result could be a iterable over some other type.
def sometype( iterable ):
for x in iterable:
yield some_transformation( x )
The sometype name feels misleading, since the function doesn't return an object of the named type. It's really an iterable over sometype.
A name like iter_sometype or gen_sometype feels a bit too much like Hungarian Notation. However, it also seems to clarify the intent of the function.
Going further, there are a number of more specialized cases, where a prefix might be helpful.
These are typical examples, some of which are available in itertools. However, we often have to write a version that's got some algorithmic complexity that makes it
similar to itertools, but not a perfect fit.
def reduce_sometype( iterable ):
summary = sometype()
for x in iterable:
if some_rule(x):
yield summary
summary= sometype()
summary.update( x )
def map_sometype( iterable ):
for x in iterable:
yield some_complex_mapping( x )
def filter_sometype( iterable ):
for x in iterable:
if some_complex_rule(x):
yield x
Does the iter_, map_, reduce_, filter_ prefix help clarify the name of a generator function? Or is it just visual clutter?
If a prefix is helpful, what prefix suggestions do you have?
Alternatively, if a suffix is helpful, what suffix suggestions do you have?
A:
Python dicts have iter* methods. And lxml trees also have an iter method.
Reading
for node in doc.iter():
seems familiar, so
following that pattern, I'd consider naming the a generator of sometypes sometypes_iter
so that I could write analgously,
for item in sometypes_iter():
Python provides a sorted function.
Following that pattern, I might make the verb-functions past tense:
sometypes_reduced
sometypes_mapped
sometypes_filtered
If you have enough of these functions, it might make sense to make a SomeTypes class so the method names could be shortened to reduce, map, and filter.
If the functions can be generalized to accept or return types other than sometype, then of course it would make sense to remove sometype from the function name, and instead choose a name that emphasizes what it does rather than the types.
| Python Generator Function Names -- is a prefix helpful? | Most functions are easy to name. Generally, a function name is based on what it does or the type of result it produces.
In the case of a generator function, however, the result could be a iterable over some other type.
def sometype( iterable ):
for x in iterable:
yield some_transformation( x )
The sometype name feels misleading, since the function doesn't return an object of the named type. It's really an iterable over sometype.
A name like iter_sometype or gen_sometype feels a bit too much like Hungarian Notation. However, it also seems to clarify the intent of the function.
Going further, there are a number of more specialized cases, where a prefix might be helpful.
These are typical examples, some of which are available in itertools. However, we often have to write a version that's got some algorithmic complexity that makes it
similar to itertools, but not a perfect fit.
def reduce_sometype( iterable ):
summary = sometype()
for x in iterable:
if some_rule(x):
yield summary
summary= sometype()
summary.update( x )
def map_sometype( iterable ):
for x in iterable:
yield some_complex_mapping( x )
def filter_sometype( iterable ):
for x in iterable:
if some_complex_rule(x):
yield x
Does the iter_, map_, reduce_, filter_ prefix help clarify the name of a generator function? Or is it just visual clutter?
If a prefix is helpful, what prefix suggestions do you have?
Alternatively, if a suffix is helpful, what suffix suggestions do you have?
| [
"Python dicts have iter* methods. And lxml trees also have an iter method.\nReading \nfor node in doc.iter():\n\nseems familiar, so\nfollowing that pattern, I'd consider naming the a generator of sometypes sometypes_iter\nso that I could write analgously, \nfor item in sometypes_iter():\n\nPython provides a sorted ... | [
7
] | [] | [] | [
"functional_programming",
"generator",
"hungarian_notation",
"python"
] | stackoverflow_0004215906_functional_programming_generator_hungarian_notation_python.txt |
Q:
Passing data to j_security_check with python
I have a j_security_check page on a server, and I need to pass data to it. I use Python urllib2 module, sending POST-request with j_username and j_password as parameters. The problem is that I have HTTPError 408 as a response: "The time allowed for the login process has been exceeded".
What should I do with it?
A:
You could try GETing the login page first and storing the cookie.
This j_security_check-thingie looks like acegi security stuff.
import urllib, urllib2
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor)
urllib2.install_opener(opener)
urllib2.urlopen('http://server/login_form/')
urllib2.urlopen('http://server/j_security_check',
data=urllib.urlencode({'j_username':'scott','j_password':'wombat'}))
| Passing data to j_security_check with python | I have a j_security_check page on a server, and I need to pass data to it. I use Python urllib2 module, sending POST-request with j_username and j_password as parameters. The problem is that I have HTTPError 408 as a response: "The time allowed for the login process has been exceeded".
What should I do with it?
| [
"You could try GETing the login page first and storing the cookie.\nThis j_security_check-thingie looks like acegi security stuff.\nimport urllib, urllib2\n\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor)\nurllib2.install_opener(opener)\nurllib2.urlopen('http://server/login_form/')\nurllib2.urlopen('htt... | [
2
] | [] | [] | [
"j_security_check",
"python",
"urllib2"
] | stackoverflow_0004173016_j_security_check_python_urllib2.txt |
Q:
Python development under Mac
I've been developing python web apps using django and appengine.
I'm planning on buying a macbook to develop iPhone apps.
I wonder if I will be able to develop my python apps without too much changes on a mac , or if keeping them on a PC will be better?
Thanks
A:
Macs run Unix, Unix makes python development even easier! (IMHO)
In other news: one of python's big selling points is that it's multi-platform, it can run as well on Windows as on Linux as on a Mac. Heck, here's a list of other platforms it can run on.
All that to say, you can move your python projects back and forth between a mac and pc with relative ease as long as you don't use any platform specific libraries. So, no you shouldn't have to do anything terribly special to make it work.
A:
Developing python for app-engine on a mac works like a charm.
A:
Python development on a Mac will be similar to Python development on other *NIX-based operating systems which, in some ways, can be easier than on Windows. As long as none of the modules you are using are Windows-only then you should have no problem!
A:
I usually develop with Python on OS X and it's a real pleasure to work it.
Just remember to install Macports;
with macports installing Python versions, Python libraries, Eclipse and so on is really easy.
A:
I would look at Homebrew instead of MacPorts - Link
| Python development under Mac | I've been developing python web apps using django and appengine.
I'm planning on buying a macbook to develop iPhone apps.
I wonder if I will be able to develop my python apps without too much changes on a mac , or if keeping them on a PC will be better?
Thanks
| [
"Macs run Unix, Unix makes python development even easier! (IMHO)\nIn other news: one of python's big selling points is that it's multi-platform, it can run as well on Windows as on Linux as on a Mac. Heck, here's a list of other platforms it can run on.\nAll that to say, you can move your python projects back and... | [
3,
1,
0,
0,
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0004215164_macos_python.txt |
Q:
Page auto-update like in Twitter
I wanna add page auto-update on my web site. It's written in Python and jquery, so I wanna try Twisted (or another COMET thing). The problem is about I don't know what exactly I need and what docs I have to read.
A:
Two options for using Twisted for COMET:
Orbited
Divmod Athena
Both of these have tutorials you'll have to read and work through, which won't fit into this small answer area, but you should be able to find them fairly easily. Good luck!
A:
use an ajax call with a setInterval, add new content - if any - on the success function of JQuery's AJAX to the according div.
| Page auto-update like in Twitter | I wanna add page auto-update on my web site. It's written in Python and jquery, so I wanna try Twisted (or another COMET thing). The problem is about I don't know what exactly I need and what docs I have to read.
| [
"Two options for using Twisted for COMET:\n\nOrbited\nDivmod Athena\n\nBoth of these have tutorials you'll have to read and work through, which won't fit into this small answer area, but you should be able to find them fairly easily. Good luck!\n",
"use an ajax call with a setInterval, add new content - if any -... | [
3,
1
] | [] | [] | [
"jquery",
"python",
"twisted",
"twitter"
] | stackoverflow_0004215816_jquery_python_twisted_twitter.txt |
Q:
Paramiko SFTP problems when no password is used
I need to upload some files using SFTP, this works from the command line:
$sftp myuser@my_remote_host
Connected to my_remote_host
sftp>
This is my Paramiko script:
#!/usr/bin/env python
import paramiko
import sys
import os
host = "my_remote_host"
port = 22
transport = paramiko.Transport((host, port))
username = "myuser"
LOCAL_PATH = "/tmp/"
REMOTE_PATH = "/dcs/tmp/"
FILE = "myfile"
transport.connect(username = username)
sftp = paramiko.SFTPClient.from_transport(transport)
path = LOCAL_PATH + FILE
sftp.put(LOCAL_PATH + FILE, REMOTE_PATH + FILE)
sftp.close()
transport.close()
print 'Upload done.'
When executing I get this error:
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "./my_sftp.py", line 19, in ?
sftp = paramiko.SFTPClient.from_transport(transport)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 102, in from_transport
chan = t.open_session()
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 655, in open_session
return self.open_channel('session')
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 745, in open_channel
raise e
EOFError
When adding a private key I get this error:
path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
key = paramiko.DSSKey.from_private_key_file(path)
transport.connect(username = username, pkey=key)
Traceback (most recent call last):
File "./my_sftp.py", line 24, in ?
transport.connect(username = username, pkey=key)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1007, in connect
self.auth_publickey(username, pkey)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1234, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/usr/lib/python2.4/site-packages/paramiko/auth_handler.py", line 174, in wait_for_response
raise e
paramiko.AuthenticationException: Authentication failed.
A:
In your first example, you can't authenticate with only a username, so the session can't be started.
I can't tell why your privatekey example isn't working without some more information. Is it possible that its the incorrect key for that server? SSH on the command line may be trying multiple keys, or getting it from an agent.
Anyway, it easier to start off with the SSHClient class. It will wrap up all the authentication, and host verification pieces in one package. It also has an open_sftp() convenience method to return an SFTPClient instance.
| Paramiko SFTP problems when no password is used | I need to upload some files using SFTP, this works from the command line:
$sftp myuser@my_remote_host
Connected to my_remote_host
sftp>
This is my Paramiko script:
#!/usr/bin/env python
import paramiko
import sys
import os
host = "my_remote_host"
port = 22
transport = paramiko.Transport((host, port))
username = "myuser"
LOCAL_PATH = "/tmp/"
REMOTE_PATH = "/dcs/tmp/"
FILE = "myfile"
transport.connect(username = username)
sftp = paramiko.SFTPClient.from_transport(transport)
path = LOCAL_PATH + FILE
sftp.put(LOCAL_PATH + FILE, REMOTE_PATH + FILE)
sftp.close()
transport.close()
print 'Upload done.'
When executing I get this error:
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "./my_sftp.py", line 19, in ?
sftp = paramiko.SFTPClient.from_transport(transport)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 102, in from_transport
chan = t.open_session()
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 655, in open_session
return self.open_channel('session')
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 745, in open_channel
raise e
EOFError
When adding a private key I get this error:
path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
key = paramiko.DSSKey.from_private_key_file(path)
transport.connect(username = username, pkey=key)
Traceback (most recent call last):
File "./my_sftp.py", line 24, in ?
transport.connect(username = username, pkey=key)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1007, in connect
self.auth_publickey(username, pkey)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1234, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/usr/lib/python2.4/site-packages/paramiko/auth_handler.py", line 174, in wait_for_response
raise e
paramiko.AuthenticationException: Authentication failed.
| [
"In your first example, you can't authenticate with only a username, so the session can't be started.\nI can't tell why your privatekey example isn't working without some more information. Is it possible that its the incorrect key for that server? SSH on the command line may be trying multiple keys, or getting it f... | [
2
] | [] | [] | [
"paramiko",
"python"
] | stackoverflow_0004209397_paramiko_python.txt |
Q:
What is causing paramiko.SSHException: Invalid packet blocking?
When I attempt to connect to one of our internal servers using paramiko (inside of fabric, for what it's worth) I get this error:
Retrieving packages from server p-websvr-004
[p-websvr-004] run: /usr/sbin/pkg_info -aD|grep "Information for"
starting thread (client mode): 0x179f090L
Banner: ----------------------------------------------------------------------
Banner: Welcome to Mycompany, Inc. Unauthorized access, is strictly prohibited
Connected (version 2.0, client OpenSSH_4.5p1)
Exception: Invalid packet blocking
Traceback (most recent call last):
File "/Users/crose/virtualenv/mycompany/lib/python2.6/site-packages/paramiko/transport.py", line 1491, in run
ptype, m = self.packetizer.read_message()
File "/Users/crose/virtualenv/mycompany/lib/python2.6/site-packages/paramiko/packet.py", line 344, in read_message
raise SSHException('Invalid packet blocking')
Every other host we have works, as far as I can tell. What's causing this to happen, and how can I fix it?
A:
First obvious question, how is this host different than the rest?
By the looks of it, it could be a bug in the SSH server. Does openssh on the command line work, and is it using a different cipher?
| What is causing paramiko.SSHException: Invalid packet blocking? | When I attempt to connect to one of our internal servers using paramiko (inside of fabric, for what it's worth) I get this error:
Retrieving packages from server p-websvr-004
[p-websvr-004] run: /usr/sbin/pkg_info -aD|grep "Information for"
starting thread (client mode): 0x179f090L
Banner: ----------------------------------------------------------------------
Banner: Welcome to Mycompany, Inc. Unauthorized access, is strictly prohibited
Connected (version 2.0, client OpenSSH_4.5p1)
Exception: Invalid packet blocking
Traceback (most recent call last):
File "/Users/crose/virtualenv/mycompany/lib/python2.6/site-packages/paramiko/transport.py", line 1491, in run
ptype, m = self.packetizer.read_message()
File "/Users/crose/virtualenv/mycompany/lib/python2.6/site-packages/paramiko/packet.py", line 344, in read_message
raise SSHException('Invalid packet blocking')
Every other host we have works, as far as I can tell. What's causing this to happen, and how can I fix it?
| [
"First obvious question, how is this host different than the rest?\nBy the looks of it, it could be a bug in the SSH server. Does openssh on the command line work, and is it using a different cipher?\n"
] | [
0
] | [] | [] | [
"paramiko",
"python",
"ssh"
] | stackoverflow_0003834688_paramiko_python_ssh.txt |
Q:
Execute background process from django that can't be interrupted by the web server
I'm seeing all kinds of threads like this and they have accepted answers, and yet I'm still stuck on this.
I have a view that should start a backup procedure, and I got it to the point where the view returns, and the process is still running in the background, however if apache is restarted, the backup process then dies.
def partStartJob(request):
import subprocess
p=subprocess.Popen(['/usr/bin/nohup','/usr/bin/python', '/(somewhere)/scripts/backup/testbackup.py'] )
# FIXME: This process dies when apache restarts.
Thanks in advance.
A:
You need to use a completely separate process for the backup. The best way to do this is to use a message queue - the view puts the backup request on the queue, and a separate listener picks it up and runs the backup, independently of Apache.
Celery is a distributed task manager that deals with all this for you, although it would be fairly easy to roll your own with RabbitMQ and the Python AMQP library.
A:
Maybe less elegant, but definitely most simple, I scheduled my process for "now" with the at command. Done.
os.system("echo '/usr/bin/python /(somewhere)/scripts/backup/testbackup.py' | at now")
| Execute background process from django that can't be interrupted by the web server | I'm seeing all kinds of threads like this and they have accepted answers, and yet I'm still stuck on this.
I have a view that should start a backup procedure, and I got it to the point where the view returns, and the process is still running in the background, however if apache is restarted, the backup process then dies.
def partStartJob(request):
import subprocess
p=subprocess.Popen(['/usr/bin/nohup','/usr/bin/python', '/(somewhere)/scripts/backup/testbackup.py'] )
# FIXME: This process dies when apache restarts.
Thanks in advance.
| [
"You need to use a completely separate process for the backup. The best way to do this is to use a message queue - the view puts the backup request on the queue, and a separate listener picks it up and runs the backup, independently of Apache.\nCelery is a distributed task manager that deals with all this for you, ... | [
8,
2
] | [] | [] | [
"apache",
"background",
"django",
"linux",
"python"
] | stackoverflow_0004208624_apache_background_django_linux_python.txt |
Q:
Check integer base representation
I define an integer like this:
x = 0xFF
But when i ask for its value to the interpreter i get:
255
Is there a way to force the interpreter to return me the value the same way I defined it?
Is there a way to check the base representation for an integer?
A:
No. Neither Python nor any other language I know stores the base you write an integer literal in. 0xFF is indistinguishable from 255. These are both converted to the same underlying representation: binary.
If you want to remember a base then you need a different type than int. Perhaps store the integers in string form "0xFF", or as a tuple (0xFF, 16). int simply doesn't have the information you want.
More realistically, it is your responsibility to format output the way you want. If you feed a hexadecimal number into a function and get a result back, it's your job to format the result as hexadecimal as well. I would not expect this code to "do what you want":
print foobar(10)
print foobar(0xFF)
Make your intentions explicit. If the default formatting (decimal) isn't to your liking then override it:
print '%04d' % (foobar(10)))
print '%04x' % (foobar(0xff)))
A:
0x is hex.
To force the interpreter to show the original value:
hex(x)
>>> x = 0xFFF
>>> x
4095
>>> hex(x)
'0xfff'
>>>
A:
0xFF (hex) and 255 (decimal) are the same number. So are 0377 (octal) and 11111111 (binary). Whatever base you define it in, it's the same underlying value, and it no longer matters how you declared it.
A:
Anyway the value will be represented in binary.
Python doesn't remember the way you wrote the value when you decided to assign it to a variable.
If you want to store this information create a specific class that will store this information for you and display the value correctly. Note that when you will be assigning the value you will have to specify the base explicitly anyhow.
A:
The integer is represented using the standard integer representation (base 2). When you define the integer you assign it a value which is implicitly converted from your representation, so the original base is lost. If you wanted you could define your own class which stores this information along with the underlying integer value
A:
What everyone else says above is true - 0xff is the same as 255 decimal. If you need to be able to maintain the string representation for some other purpose, you can do something like this:
class VerboseInt(object):
def __init__(self, val):
'''
pass in a string containing an integer value -- we'll detect whether
it's hex (0x), binary (0x), octal (0), or decimal and be able to
display it that way later...
'''
self.base = 10
if val.startswith('0x'):
self.base = 16
elif val.startswith('0b'):
self.base = 2
elif val.startswith('0'):
self.base = 8
self.value = int(val, self.base)
def __str__(self):
''' convert our value into a string that's in the same base
representation that we were initialized with.
'''
formats = { 10 : ("", "{0}"),
2: ("0b", "{0:b}"),
8: ("0", "{0:o}"),
16: ("0x", "{0:x}")
}
fmt = formats[self.base]
return fmt[0] + fmt[1].format(self.value)
def __repr__(self):
return str(self)
def __int__(self):
''' get our value as an integer'''
return self.value
A:
What would you expect from:
x = 0x7F + 128
print x
The numeric base is not part of Python's internal representation of an integer. You could, if you wanted, maintain a string instead of an int, and explicitly convert to int when you needed to.
| Check integer base representation | I define an integer like this:
x = 0xFF
But when i ask for its value to the interpreter i get:
255
Is there a way to force the interpreter to return me the value the same way I defined it?
Is there a way to check the base representation for an integer?
| [
"No. Neither Python nor any other language I know stores the base you write an integer literal in. 0xFF is indistinguishable from 255. These are both converted to the same underlying representation: binary.\n\nIf you want to remember a base then you need a different type than int. Perhaps store the integers in stri... | [
4,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004216398_python.txt |
Q:
Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL?
I have a DLL that allocates memory and returns it. Function in DLL is like this:
void Foo( unsigned char** ppMem, int* pSize )
{
* pSize = 4;
* ppMem = malloc( * pSize );
for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i;
}
Also, i have a python code that access this function from my DLL:
from ctypes import *
Foo = windll.mydll.Foo
Foo.argtypes = [ POINTER( POINTER( c_ubyte ) ), POINTER( c_int ) ]
mem = POINTER( c_ubyte )()
size = c_int( 0 )
Foo( byref( mem ), byref( size ) ]
print size, mem[ 0 ], mem[ 1 ], mem[ 2 ], mem[ 3 ]
I'm expecting that print will show "4 0 1 2 3" but it shows "4 221 221 221 221" O_O. Any hints what i'm doing wrong?
A:
Post actual code. The C/C++ code doesn't compile as either C or C++. The Python code has syntax errors (] ending function call Foo). The code below works. The main issue after fixing syntax and compiler errors was declaring the function __stdcall so windll could be used in the Python code. The other option is to use __cdecl (normally the default) and use cdll instead of windll in the Python code.
mydll.c (cl /W4 /LD mydll.c)
#include <stdlib.h>
__declspec(dllexport) void __stdcall Foo(unsigned char** ppMem, int* pSize)
{
char i;
*pSize = 4;
*ppMem = malloc(*pSize);
for(i = 0; i < *pSize; i++)
(*ppMem)[i] = i;
}
demo.py (Python 2/3 and 32-/64-bit compatible)
from __future__ import print_function
from ctypes import *
Foo = WinDLL('./mydll').Foo
Foo.argtypes = POINTER(POINTER(c_ubyte)), POINTER(c_int)
Foo.restype = None
mem = POINTER(c_ubyte)()
size = c_int()
Foo(byref(mem),byref(size))
print(size.value, mem[0], mem[1], mem[2], mem[3])
Output
4 0 1 2 3
| Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL? | I have a DLL that allocates memory and returns it. Function in DLL is like this:
void Foo( unsigned char** ppMem, int* pSize )
{
* pSize = 4;
* ppMem = malloc( * pSize );
for( int i = 0; i < * pSize; i ++ ) (* ppMem)[ i ] = i;
}
Also, i have a python code that access this function from my DLL:
from ctypes import *
Foo = windll.mydll.Foo
Foo.argtypes = [ POINTER( POINTER( c_ubyte ) ), POINTER( c_int ) ]
mem = POINTER( c_ubyte )()
size = c_int( 0 )
Foo( byref( mem ), byref( size ) ]
print size, mem[ 0 ], mem[ 1 ], mem[ 2 ], mem[ 3 ]
I'm expecting that print will show "4 0 1 2 3" but it shows "4 221 221 221 221" O_O. Any hints what i'm doing wrong?
| [
"Post actual code. The C/C++ code doesn't compile as either C or C++. The Python code has syntax errors (] ending function call Foo). The code below works. The main issue after fixing syntax and compiler errors was declaring the function __stdcall so windll could be used in the Python code. The other option is... | [
33
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004213095_ctypes_python.txt |
Q:
Problems with Python 2.7 + wxPython 2.8.11? Should I switch back to Python 2.6.5 + wx.Python 2.8.10.1?
I'm currently using Python 2.7 + wxPython 2.8.11 on my windows machine. While trying to build a small project (which also uses comtypes and lets say any activex such as flashwindow) I'm getting the following error:
>>>"c:\Program Files\Python_2.7\python.exe" setup.py py2exe
running py2exe
*** searching for required modules ***
*** parsing results ***
*** finding dlls needed ***
error: MSVCP90.dll: No such file or directory
I fixed it by copying the .dll and .manifest file to the directory. It builds fine.
But again at the time of execution I got the errors like
'CreateActCtx' failed with error 0x0000007b
followed by
File "zipextimporter.pyo", line 82, in load_module
File "wx\lib\flashwin.pyo", line 15, in
File "zipextimporter.pyo", line 82, in load_module
File "wx\lib\activex.pyo", line 44, in <module>
ImportError: cannot import name myole4ax
So, I upgraded my wxPython to 2.9* (Python 2.7) where is fails with unable to find PROCESS_START. So, I had to revert back to 2.8.11 (with Python 2.7) Now, it fails with the following (after copying the MSVC*90.dll to local directory and after building into a single executable):
C:\testflv> testflv.exe
Traceback (most recent call last):
File "testflv.py", line 10, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "wx\__init__.pyo", line 45, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "wx\_core.pyo", line 4, in <module>
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading wx\_core_.pyd
It seems that there's a problem with myole4ax* as mention here (http://comments.gmane.org/gmane.comp.python.wxpython.devel/3114):
> Looks like the installer on windows does not include
> wx/lib/myole4ax.tlb and the brand new comtypes based ActiveX stuff
> does not work.
> After getting the missing stuff from SVN import errors go away.
Oops. Sorry about that. For the record here is the link to get the file.
http://trac.wxwidgets.org/browser/wxPython/branches/WX_2_8_BRANCH/wx/lib/myole4ax.tlb
How can I resolve the problem or do I need to switch back to the older versions? I'm stuck. Any help in this regards would be highly appreciated.
Thanks.
A:
I've tried the older version too but not of much help but it helped making things clear to me. While trying to bundle the things in executable I got this warning/error/message:
*** copy extensions ***
*** copy dlls ***
copying C:\Program Files\Python_2.6.5\w9xpopen.exe -> c:\wxpython\test\dist
copying C:\Program Files\Python_2.6.5\lib\site-packages\py2exe\run.exe -> c:\wxpython\test\dist\testactivex.exe
Adding python26.dll as resource to c:\wxpython\test\dist\testactivex.exe
The following modules appear to be missing
['comtypes.gen']
So, that's why when we execute the executable it failed with the following error:
c:\wxpython\test\dist>testactivex.exe
10:13:16: Debug: src/helpers.cpp(140): 'CreateActCtx' failed with error 0x0000007b (the filename, directory name, or volume label syntax is incorrect.).
Traceback (most recent call last):
File "testactivex.py", line 24, in <module>
ImportError: cannot import name myole4ax
But when we execute using
python.exe testactivex.py
It works fine. I have tried to dig more into it and I found some interesting links as follows:
http://markmail.org/message/btbsrqhvfvyclfgo#query:+page:1+mid:btbsrqhvfvyclfgo+state:results
http://translate.google.com/translate?hl=en&sl=ja&u=http://blog.loadlimits.info/2010/01/py2exewxpython%25E3%2581%25A7myole4ax%25E3%2581%258C%25E8%25A6%258B%25E3%2581%25A4%25E3%2581%258B%25E3%2582%2589%25E3%2581%25AA%25E3%2581%2584%25E3%2581%25A8%25E8%25A8%2580%25E3%2582%258F%25E3%2582%258C%25E3%2582%258B%25E5%2595%258F%25E9%25A1%258C/&ei=T3DlTNmwNIeqsAOe_JWxCw&sa=X&oi=translate&ct=result&resnum=6&ved=0CDUQ7gEwBQ&prev=/search%3Fq%3DImportError:%2Bcannot%2Bimport%2Bname%2Bmyole4ax%26hl%3Den%26rlz%3D1R2ADRA_enUS387%26prmd%3Div
Although I got an idea about the problem but I am not able to find the way how to resolve the myole4ax and comtypes.gen problem. If any of you guys know how to done packaging with this or create exe without any problem please please let me know.
ImportError: cannot import name myole4ax
myole4ax and comtypes.gen problem was because it din't have sufficient privileges. Compiled from commandline in administrator mode and problem got resolved.
Thanks a lot!
| Problems with Python 2.7 + wxPython 2.8.11? Should I switch back to Python 2.6.5 + wx.Python 2.8.10.1? | I'm currently using Python 2.7 + wxPython 2.8.11 on my windows machine. While trying to build a small project (which also uses comtypes and lets say any activex such as flashwindow) I'm getting the following error:
>>>"c:\Program Files\Python_2.7\python.exe" setup.py py2exe
running py2exe
*** searching for required modules ***
*** parsing results ***
*** finding dlls needed ***
error: MSVCP90.dll: No such file or directory
I fixed it by copying the .dll and .manifest file to the directory. It builds fine.
But again at the time of execution I got the errors like
'CreateActCtx' failed with error 0x0000007b
followed by
File "zipextimporter.pyo", line 82, in load_module
File "wx\lib\flashwin.pyo", line 15, in
File "zipextimporter.pyo", line 82, in load_module
File "wx\lib\activex.pyo", line 44, in <module>
ImportError: cannot import name myole4ax
So, I upgraded my wxPython to 2.9* (Python 2.7) where is fails with unable to find PROCESS_START. So, I had to revert back to 2.8.11 (with Python 2.7) Now, it fails with the following (after copying the MSVC*90.dll to local directory and after building into a single executable):
C:\testflv> testflv.exe
Traceback (most recent call last):
File "testflv.py", line 10, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "wx\__init__.pyo", line 45, in <module>
File "zipextimporter.pyo", line 82, in load_module
File "wx\_core.pyo", line 4, in <module>
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading wx\_core_.pyd
It seems that there's a problem with myole4ax* as mention here (http://comments.gmane.org/gmane.comp.python.wxpython.devel/3114):
> Looks like the installer on windows does not include
> wx/lib/myole4ax.tlb and the brand new comtypes based ActiveX stuff
> does not work.
> After getting the missing stuff from SVN import errors go away.
Oops. Sorry about that. For the record here is the link to get the file.
http://trac.wxwidgets.org/browser/wxPython/branches/WX_2_8_BRANCH/wx/lib/myole4ax.tlb
How can I resolve the problem or do I need to switch back to the older versions? I'm stuck. Any help in this regards would be highly appreciated.
Thanks.
| [
"I've tried the older version too but not of much help but it helped making things clear to me. While trying to bundle the things in executable I got this warning/error/message:\n*** copy extensions ***\n*** copy dlls ***\ncopying C:\\Program Files\\Python_2.6.5\\w9xpopen.exe -> c:\\wxpython\\test\\dist\ncopying C:... | [
0
] | [] | [] | [
"comtypes",
"py2exe",
"python",
"wxpython"
] | stackoverflow_0004208853_comtypes_py2exe_python_wxpython.txt |
Q:
How to split a string (using regex?) depending on digit/ not digit
I want to split a string into a list in python, depending on digit/ not digit.
For example,
5 55+6+ 5/
should return
['5','55','+','6','+','5','/']
I have some code at the moment which loops through the characters in a string and tests them using re.match("\d") or ("\D"). I was wondering if there was a better way of doing this.
P.S: must be compatible with python 2.4
A:
Assuming the + between 6 and 5 needs to be matched (which you're missing),
>>> import re
>>> s = '5 55+6+ 5/'
>>> re.findall(r'\d+|[^\d\s]+', s)
['5', '55', '+', '6', '+', '5', '/']
A:
this one is simplest one :)
re.findall('\d+|[^\d]+','134aaaaa')
A:
Use findall or finditer:
>>> re.findall(r'\d+|[^\s\d]+', '5 55+6+ 5/')
['5', '55', '+', '6', '+', '5', '/']
A:
If order doesn't matter, you could do 2 splits:
re.split('\D+', mystring)
re.split('\d+', mystring)
However, from your input, it looks like it might be mathematical... in which case order would matter. :)
You are best off using re.findall, as in one of the other answers.
| How to split a string (using regex?) depending on digit/ not digit | I want to split a string into a list in python, depending on digit/ not digit.
For example,
5 55+6+ 5/
should return
['5','55','+','6','+','5','/']
I have some code at the moment which loops through the characters in a string and tests them using re.match("\d") or ("\D"). I was wondering if there was a better way of doing this.
P.S: must be compatible with python 2.4
| [
"Assuming the + between 6 and 5 needs to be matched (which you're missing),\n>>> import re\n>>> s = '5 55+6+ 5/'\n>>> re.findall(r'\\d+|[^\\d\\s]+', s)\n['5', '55', '+', '6', '+', '5', '/']\n\n",
"this one is simplest one :)\nre.findall('\\d+|[^\\d]+','134aaaaa')\n\n",
"Use findall or finditer:\n>>> re.findall(... | [
5,
2,
1,
0
] | [] | [] | [
"python",
"regex",
"string",
"tokenize"
] | stackoverflow_0004218502_python_regex_string_tokenize.txt |
Q:
building a python module on windows using ms compiler
I am trying to build the example that comes with the source distribution of python under PC\example_nt
I copied example.c and setup.py to a directory C:\mymod
When I run C:\Python27\python.exe setup.py install I get the error....
error: Unable to find vcvarsall.bat
I did some digging around in distutils and saw that it was going after version 9 of microsoft visual studio but I only have version 8. Apparently it tries to get version 9 because of what the python under C:\Python27 was compiled with.
I modified setup.py and put the following at the very top.
from distutils import msvc9compiler
msvc9compiler.VERSION = 8.0
After doing this I was able to compile and got the following....
C:\mymod>C:\Python27\python.exe setup.py install
running install
running build
running build_ext
building 'example' extension
creating build
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\cl.exe /c /nologo /Ox /MD /W3
/GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tcexample.c /Fobuild\temp.
win32-2.7\Release\example.obj
example.c
creating build\lib.win32-2.7
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\link.exe /DLL /nologo /INCREME
NTAL:NO /LIBPATH:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild /EXPORT:initexamp
le build\temp.win32-2.7\Release\example.obj /OUT:build\lib.win32-2.7\example.pyd
/IMPLIB:build\temp.win32-2.7\Release\example.lib /MANIFESTFILE:build\temp.win32
-2.7\Release\example.pyd.manifest
Creating library build\temp.win32-2.7\Release\example.lib and object build\te
mp.win32-2.7\Release\example.exp
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\mt.exe -nologo -manifest build
\temp.win32-2.7\Release\example.pyd.manifest -outputresource:build\lib.win32-2.7
\example.pyd;2
running install_lib
copying build\lib.win32-2.7\example.pyd -> C:\Python27\Lib\site-packages
running install_egg_info
Removing C:\Python27\Lib\site-packages\example-1.0-py2.7.egg-info
Writing C:\Python27\Lib\site-packages\example-1.0-py2.7.egg-info
Now when I run C:\Python27\python.exe and try to import example I get the following...
ImportError: DLL load failed: The specified module could not be found.
Did I do something wrong? Is VS8 unsupported for creating Python 2.7 modules?
What should I do?
Ultimately I need to build bindings for some Windows C library so that I can use Python to extend some proprietary program instead of C. I have to use VS8 for creating the C extension. So where does that leave me.
Advice please.
Thanks,
~Eric
A:
Generally speaking you have to build the python modules using the same version of VS as python was built with. You have several options:
Use Python2.6, which i think is VS8 (or an even earlier version, I'm sure there was a change between 2.5 and 2.6)
Use VS9. I assume you can't because the proprietary library you are using was built with VS8. Same problem as is happening with python really.
Create your bindings using ctypes. This can be hard and its very easy to crash your program.
Build Python2.7 from source using VS8. If you can't use Python2.6 for some reason then this is probably the best bet.
I'd recommend option 1 if it works.
| building a python module on windows using ms compiler | I am trying to build the example that comes with the source distribution of python under PC\example_nt
I copied example.c and setup.py to a directory C:\mymod
When I run C:\Python27\python.exe setup.py install I get the error....
error: Unable to find vcvarsall.bat
I did some digging around in distutils and saw that it was going after version 9 of microsoft visual studio but I only have version 8. Apparently it tries to get version 9 because of what the python under C:\Python27 was compiled with.
I modified setup.py and put the following at the very top.
from distutils import msvc9compiler
msvc9compiler.VERSION = 8.0
After doing this I was able to compile and got the following....
C:\mymod>C:\Python27\python.exe setup.py install
running install
running build
running build_ext
building 'example' extension
creating build
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\cl.exe /c /nologo /Ox /MD /W3
/GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tcexample.c /Fobuild\temp.
win32-2.7\Release\example.obj
example.c
creating build\lib.win32-2.7
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\link.exe /DLL /nologo /INCREME
NTAL:NO /LIBPATH:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild /EXPORT:initexamp
le build\temp.win32-2.7\Release\example.obj /OUT:build\lib.win32-2.7\example.pyd
/IMPLIB:build\temp.win32-2.7\Release\example.lib /MANIFESTFILE:build\temp.win32
-2.7\Release\example.pyd.manifest
Creating library build\temp.win32-2.7\Release\example.lib and object build\te
mp.win32-2.7\Release\example.exp
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\mt.exe -nologo -manifest build
\temp.win32-2.7\Release\example.pyd.manifest -outputresource:build\lib.win32-2.7
\example.pyd;2
running install_lib
copying build\lib.win32-2.7\example.pyd -> C:\Python27\Lib\site-packages
running install_egg_info
Removing C:\Python27\Lib\site-packages\example-1.0-py2.7.egg-info
Writing C:\Python27\Lib\site-packages\example-1.0-py2.7.egg-info
Now when I run C:\Python27\python.exe and try to import example I get the following...
ImportError: DLL load failed: The specified module could not be found.
Did I do something wrong? Is VS8 unsupported for creating Python 2.7 modules?
What should I do?
Ultimately I need to build bindings for some Windows C library so that I can use Python to extend some proprietary program instead of C. I have to use VS8 for creating the C extension. So where does that leave me.
Advice please.
Thanks,
~Eric
| [
"Generally speaking you have to build the python modules using the same version of VS as python was built with. You have several options:\n\nUse Python2.6, which i think is VS8 (or an even earlier version, I'm sure there was a change between 2.5 and 2.6)\nUse VS9. I assume you can't because the proprietary library ... | [
1
] | [] | [] | [
"distutils",
"python",
"python_2.7",
"visual_studio",
"windows"
] | stackoverflow_0004218613_distutils_python_python_2.7_visual_studio_windows.txt |
Q:
twisted not detecting client disconnects
Does anybody have experience with this? I have a twisted app. The clients connect to the server. I added a feature so that if a client connects to a server, but there's already a client from that IP address running, it disconnects the new client.
Once in a while, I shutdown a client computer (or VM, to be precise) without manually turning off the Python program. When I do this, once in a while but pretty often, the server does not detect any disconnect. When the computer comes back up and tries to reconnect, the server insists that there is a connection from that IP already. The only solution I've found so far is to restart the server.
Could it be strange networking things not having the disconnect go through? Twisted bug?
I'm 99% certain it's not a bug with my code to handle disconnects. My code is set up such that connectionLost is called whenever a connection is lost, including most cases of shutting down a machine, and it either logs a string saying what disconnected or throws an exception if something strange happened. Neither of these things showed up in the log.
A:
This is a Twisted FAQ, even though it doesn't really have anything to do with Twisted specifically.
A:
Heh I can't believe I forgot all that I learned in networking class...
(2:09:44 PM) coworker: this is the expected behaviour
(2:10:15 PM) coworker: the server has no way to know if someone dies, or is just quiet
(2:10:35 PM) coworker: unless ofcourse the server has some kind of ping/keepalive message
(2:15:38 PM) claudiu: ah so if they have no communicatin
(2:15:42 PM) claudiu: there's no way to tell that a TCP connection has died
(2:15:47 PM) claudiu: i remember learning that now, yes..
(2:16:23 PM) claudiu: but if i just make the server ping the client then it'll figure out soon enough from lack of ACKs that it's dead, right?
(2:16:45 PM) coworker: right
| twisted not detecting client disconnects | Does anybody have experience with this? I have a twisted app. The clients connect to the server. I added a feature so that if a client connects to a server, but there's already a client from that IP address running, it disconnects the new client.
Once in a while, I shutdown a client computer (or VM, to be precise) without manually turning off the Python program. When I do this, once in a while but pretty often, the server does not detect any disconnect. When the computer comes back up and tries to reconnect, the server insists that there is a connection from that IP already. The only solution I've found so far is to restart the server.
Could it be strange networking things not having the disconnect go through? Twisted bug?
I'm 99% certain it's not a bug with my code to handle disconnects. My code is set up such that connectionLost is called whenever a connection is lost, including most cases of shutting down a machine, and it either logs a string saying what disconnected or throws an exception if something strange happened. Neither of these things showed up in the log.
| [
"This is a Twisted FAQ, even though it doesn't really have anything to do with Twisted specifically.\n",
"Heh I can't believe I forgot all that I learned in networking class...\n(2:09:44 PM) coworker: this is the expected behaviour\n(2:10:15 PM) coworker: the server has no way to know if someone dies, or is just ... | [
5,
2
] | [] | [] | [
"network_programming",
"networking",
"python",
"twisted"
] | stackoverflow_0004218169_network_programming_networking_python_twisted.txt |
Q:
Wait for a twisted service to start before starting another
I have written a proxy server that uses twisted's application framework. At it's core there it uses a DHT to resolve things. The DHT client takes a few seconds to start, so i want to make sure that the proxy only accepts connections after the DHT is ready.
# there is a class like
class EntangledDHT(object):
# connects to the dht
# create the client
dht = EntangledDHT.from_config(config)
# when it can be used this deferred fires
# i want to wait for this before creating the "real" application
dht.ready
# the proxy server, it uses the dht client
port = config.getint(section, 'port')
p = CosipProxy(host=config.get(section, 'listen'),
port=port,
dht=dht,
domain=config.get(section, 'domain'))
## for twistd
application = service.Application('cosip')
serv = internet.UDPServer(port, p)
serv.setServiceParent(service.IService(application))
How do I turn the EntangledDHT into some kind of service that Twisted will wait for before starting the CosipProxy service? Is there any mechanism in twisted that does this for me? Or do I have to add a callback to dht.ready that creates the rest of the application? Thanks
A:
Don't call serv.setServiceParent(service.IService(application)) right away. Instead, wait to call it in your callback to dht.ready. This will cause it to be started if the application service is already running.
Also, it doesn't look like dht itself is an IService. It should be; or rather, the thing that calls from_config should be a service, since apparently from_config is going to kick off some connections (at least, that's what it looks like, if dht.ready is ever going to fire, in this example). Your plugin or tac file should be constructing a service, not starting a service. Nothing should happen until that first startService is called.
| Wait for a twisted service to start before starting another | I have written a proxy server that uses twisted's application framework. At it's core there it uses a DHT to resolve things. The DHT client takes a few seconds to start, so i want to make sure that the proxy only accepts connections after the DHT is ready.
# there is a class like
class EntangledDHT(object):
# connects to the dht
# create the client
dht = EntangledDHT.from_config(config)
# when it can be used this deferred fires
# i want to wait for this before creating the "real" application
dht.ready
# the proxy server, it uses the dht client
port = config.getint(section, 'port')
p = CosipProxy(host=config.get(section, 'listen'),
port=port,
dht=dht,
domain=config.get(section, 'domain'))
## for twistd
application = service.Application('cosip')
serv = internet.UDPServer(port, p)
serv.setServiceParent(service.IService(application))
How do I turn the EntangledDHT into some kind of service that Twisted will wait for before starting the CosipProxy service? Is there any mechanism in twisted that does this for me? Or do I have to add a callback to dht.ready that creates the rest of the application? Thanks
| [
"Don't call serv.setServiceParent(service.IService(application)) right away. Instead, wait to call it in your callback to dht.ready. This will cause it to be started if the application service is already running.\nAlso, it doesn't look like dht itself is an IService. It should be; or rather, the thing that calls... | [
2
] | [] | [] | [
"python",
"twisted",
"twisted.application"
] | stackoverflow_0004218064_python_twisted_twisted.application.txt |
Q:
Set admin username to input field at Django admin
I'm developing a system based on Django admin. So all models could be edited also only from admin site. Model has a char field 'user'. I want to set current logged in admin username (or firstname, or lastname) as default value to 'user' field. How could I implement this?
Default values are set as parameters when defining model fields, so I guess no request object could be recieved? Maybe I should set the value when creating instance of model (inside init method), but how I could achieve this?
A:
I found this recipe helpful: http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser
A:
This is how you do it on the form level and not the save http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield%5Ffor%5Fforeignkey
| Set admin username to input field at Django admin | I'm developing a system based on Django admin. So all models could be edited also only from admin site. Model has a char field 'user'. I want to set current logged in admin username (or firstname, or lastname) as default value to 'user' field. How could I implement this?
Default values are set as parameters when defining model fields, so I guess no request object could be recieved? Maybe I should set the value when creating instance of model (inside init method), but how I could achieve this?
| [
"I found this recipe helpful: http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser\n",
"This is how you do it on the form level and not the save http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield%5Ffor%5Fforeignkey\n"
] | [
1,
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0004159659_django_django_admin_python.txt |
Q:
What is causing urllib2.urlopen() to connect via proxy?
I'm trying to read a URL within our corporate network. Spesifically the server I'm contacting is in one office and the client PC is in another:
print(urlopen(r"http://london.mycompany/mydir/").read())
Whenever I run this function I get:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
File "C:\Python24\lib\urllib2.py", line 364, in open
response = meth(req, response)
File "C:\Python24\lib\urllib2.py", line 471, in http_response
response = self.parent.error(
File "C:\Python24\lib\urllib2.py", line 402, in error
return self._call_chain(*args)
File "C:\Python24\lib\urllib2.py", line 337, in _call_chain
result = func(*args)
File "C:\Python24\lib\urllib2.py", line 480, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 407: Proxy Authentication Required
The odd thing is that there's no firewall between these two computers - for some reason url has decided to connect to the web-server via the proxy which we'd normally use to connect to content outside the company, and in this case that's failing because I've not authenticated it.
I'm pretty sure that the fault occurs within the client PC: I did a nslookup and a ping to the server to confirm that there's a connection between the two computers, however when I watch the transaction using TCPView for Windows I can see that the python.exe process is connecting to a completely different server (yes, the proxy!).
So what could be causing this? Note that the os.environ["http_proxy"] variable is NOT set - this variable is often used to make urllib connect via a proxy server. That's not the case here. Could there be something else which might have the same effect?
FYI, Running Python 2.4.4 on Windows XP 32bit in a very locked-down corporate environment.
A:
It reads from the system settings. Use urllib.FancyURLOpener:
opener = urllib.FancyURLopener({})
f = opener.open("http://london.mycompany/mydir/")
f.read()
| What is causing urllib2.urlopen() to connect via proxy? | I'm trying to read a URL within our corporate network. Spesifically the server I'm contacting is in one office and the client PC is in another:
print(urlopen(r"http://london.mycompany/mydir/").read())
Whenever I run this function I get:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\Python24\lib\urllib2.py", line 130, in urlopen
return _opener.open(url, data)
File "C:\Python24\lib\urllib2.py", line 364, in open
response = meth(req, response)
File "C:\Python24\lib\urllib2.py", line 471, in http_response
response = self.parent.error(
File "C:\Python24\lib\urllib2.py", line 402, in error
return self._call_chain(*args)
File "C:\Python24\lib\urllib2.py", line 337, in _call_chain
result = func(*args)
File "C:\Python24\lib\urllib2.py", line 480, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 407: Proxy Authentication Required
The odd thing is that there's no firewall between these two computers - for some reason url has decided to connect to the web-server via the proxy which we'd normally use to connect to content outside the company, and in this case that's failing because I've not authenticated it.
I'm pretty sure that the fault occurs within the client PC: I did a nslookup and a ping to the server to confirm that there's a connection between the two computers, however when I watch the transaction using TCPView for Windows I can see that the python.exe process is connecting to a completely different server (yes, the proxy!).
So what could be causing this? Note that the os.environ["http_proxy"] variable is NOT set - this variable is often used to make urllib connect via a proxy server. That's not the case here. Could there be something else which might have the same effect?
FYI, Running Python 2.4.4 on Windows XP 32bit in a very locked-down corporate environment.
| [
"It reads from the system settings. Use urllib.FancyURLOpener:\nopener = urllib.FancyURLopener({})\nf = opener.open(\"http://london.mycompany/mydir/\")\nf.read()\n\n"
] | [
2
] | [] | [] | [
"http",
"networking",
"python"
] | stackoverflow_0004218809_http_networking_python.txt |
Q:
Google App Engine compatibility layer
I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster.
I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.
However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).
Regards,
Iwan
A:
The appscale project is designed to do exactly this. See https://github.com/AppScale/appscale/wiki
A:
I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB
to offer near 100% compatibility
GAE/J uses DataNucleus for persistence. DataNucleus also has plugins for RDBMS, LDAP, XML, Excel, ODF, OODBMS, HBase (HADOOP), and Amazon S3. Consequently the persistence layer (using JDO or JPA) could, in principle, be used across any of those. To write a DataNucleus plugin for Amazon SimpleDB shouldn't be too hard either, or CouchDB.
--Andy (DataNucleus)
A:
Typhoonae Might be interesting to you, it is a new project to implement a full production server stack using exisiting technologies, capable of hosting AppEngine instances. It also aims to do this while staying compatable with the AppEngine API, to allow easy portability. I'm not sure what stage they have reached with the integration, but it should definatley be worth a look.
A:
Another taken from this question:
Waxy
A:
If you develop with web2py your code will run GAE other architectures wihtout changes using any of the 10 supported relational databases. The compatibility layer covers database api (including blobs and listproperty), email, and fetching).
| Google App Engine compatibility layer | I'm planning an application running on Google App Engine. The only worry I would have is portability. Or just the option to have the app run on a local, private cluster.
I expected an option for Google App Engine applications to run on other systems, a compatibility layer, to spring up. I could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB to offer near 100% compatibility, if needs be through an abstraction layer. I prefer Python though Java would be acceptable.
However, as far as I know, none such facility exists today. Am I mistaken and if so where could I find this Googe App Engine compatibility layer. If I'm not, the questions is "why"? Are there unforetold technical issues or is there just no demand from the market (which would potentially hint at low rates of GAE adoption).
Regards,
Iwan
| [
"The appscale project is designed to do exactly this. See https://github.com/AppScale/appscale/wiki\n",
"\nI could imagine a GAE compatible framework utilizing Amazon SimpleDB or CouchDB \n to offer near 100% compatibility\n\nGAE/J uses DataNucleus for persistence. DataNucleus also has plugins for RDBMS, LDAP, ... | [
6,
4,
2,
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0001589743_google_app_engine_python.txt |
Q:
ANSI graphic codes and Python
I was browsing the Django source code and I saw this function:
def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid options:
'bold'
'underscore'
'blink'
'reverse'
'conceal'
'noreset' - string will not be auto-terminated with the RESET code
Examples:
colorize('hello', fg='red', bg='blue', opts=('blink',))
colorize()
colorize('goodbye', opts=('underscore',))
print colorize('first line', fg='red', opts=('noreset',))
print 'this should be red too'
print colorize('and so should this')
print 'this should not be red'
"""
code_list = []
if text == '' and len(opts) == 1 and opts[0] == 'reset':
return '\x1b[%sm' % RESET
for k, v in kwargs.iteritems():
if k == 'fg':
code_list.append(foreground[v])
elif k == 'bg':
code_list.append(background[v])
for o in opts:
if o in opt_dict:
code_list.append(opt_dict[o])
if 'noreset' not in opts:
text = text + '\x1b[%sm' % RESET
return ('\x1b[%sm' % ';'.join(code_list)) + text
I removed it out of the context and placed in another file just to try it, the thing is that it doesn't seem to colour the text I pass it. It might be that I don't understand it correctly but isn't it supposed to just return the text surrounded with ANSI graphics codes which than the terminal will convert to actual colours.
I tried all the given examples of calling it, but it just returned the argument I specified as a text.
I'm using Ubuntu so I think the terminal should support colours.
A:
It's that you have many terms undefined, because it relies on several variables defined outside of the function.
Instead just
import django.utils.termcolors as termcolors
red_hello = termcolors.colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'
print red_hello
Or just also copy the first few lines of django/utils/termcolors.py specifically:
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
background = dict([(color_names[x], '4%s' % x) for x in range(8)])
RESET = '0'
def colorize( ... ):
...
print colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'
Also note:
>>> from django.utils.termcolors import colorize
>>> red_hello = colorize("Hello", fg="red")
>>> red_hello # by not printing; it will not appear red; special characters are escaped
'\x1b[31mHello\x1b[0m'
>>> print red_hello # by print it will appear red; special characters are not escaped
Hello
| ANSI graphic codes and Python | I was browsing the Django source code and I saw this function:
def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid options:
'bold'
'underscore'
'blink'
'reverse'
'conceal'
'noreset' - string will not be auto-terminated with the RESET code
Examples:
colorize('hello', fg='red', bg='blue', opts=('blink',))
colorize()
colorize('goodbye', opts=('underscore',))
print colorize('first line', fg='red', opts=('noreset',))
print 'this should be red too'
print colorize('and so should this')
print 'this should not be red'
"""
code_list = []
if text == '' and len(opts) == 1 and opts[0] == 'reset':
return '\x1b[%sm' % RESET
for k, v in kwargs.iteritems():
if k == 'fg':
code_list.append(foreground[v])
elif k == 'bg':
code_list.append(background[v])
for o in opts:
if o in opt_dict:
code_list.append(opt_dict[o])
if 'noreset' not in opts:
text = text + '\x1b[%sm' % RESET
return ('\x1b[%sm' % ';'.join(code_list)) + text
I removed it out of the context and placed in another file just to try it, the thing is that it doesn't seem to colour the text I pass it. It might be that I don't understand it correctly but isn't it supposed to just return the text surrounded with ANSI graphics codes which than the terminal will convert to actual colours.
I tried all the given examples of calling it, but it just returned the argument I specified as a text.
I'm using Ubuntu so I think the terminal should support colours.
| [
"It's that you have many terms undefined, because it relies on several variables defined outside of the function.\nInstead just \nimport django.utils.termcolors as termcolors\nred_hello = termcolors.colorize(\"Hello\", fg='red') # '\\x1b[31mHello\\x1b[0m'\nprint red_hello\n\nOr just also copy the first few lines of... | [
1
] | [] | [] | [
"ansi",
"python"
] | stackoverflow_0004219057_ansi_python.txt |
Q:
Can't understand a line in a "Collective intelligence" program
I'm working through "Programming collective intelligence". In chapter 4, Toby Segaran builds an artificial neural network. The following function appears on page of the book:
def generatehiddennode(self,wordids,urls):
if len(wordids)>3: return None
# Check if we already created a node for this set of words
sorted_words=[str(id) for id in wordids]
sorted_words.sort()
createkey='_'.join(sorted_words)
res=self.con.execute(
"select rowid from hiddennode where create_key='%s'" % createkey).fetchone()
# If not, create it
if res==None:
cur=self.con.execute(
"insert into hiddennode (create_key) values ('%s')" % createkey)
hiddenid=cur.lastrowid
# Put in some default weights
for wordid in wordids:
self.setstrength(wordid,hiddenid,0,1.0/len(wordids))
for urlid in urls:
self.setstrength(hiddenid,urlid,1,0.1)
self.con.commit()
What I can't possibly understand is the reason of the first line in this function: 'if len(wordids>3): return None`. Is it a debug code that needs to be removed later?
P.S. this is not a homework
A:
For a published book, that's pretty terrible code! (You can download all the examples for the book from here; the relevant file is chapter4/nn.py.)
No docstring. What is this function supposed to do? From its name, we can guess that it's generating one of the nodes in the "hidden layer" of a neural network, but what role do the wordids and urls play?
Database query uses string substitution and so is vulnerable to SQL injection attacks (especially since this is something to do with web searching, so the wordids probably come from a user query and so may be untrusted—but then, maybe they are ids rather than words so it's OK in practice but still a very bad habit to get into).
Not using the expressive power of the database: if all you want to do is to determine if a key exists in the database then you probably want to use a SELECT EXISTS(...) rather than asking the database to send you a bunch of records which you're then going to ignore.
Function does nothing if there was already a record with createkey. No error. Is that correct? Who can say?
The weighting for the words is scaled to the numbers of words, but the weighting for the urls is the constant 0.1 (perhaps there are always 10 URLs, but it would be better style to scale by len(urls) here).
I could go on and on, but I better not.
Anyway, to answer your question, it looks as though this function is adding a database entry for a node in the hidden layer of a neural network. This neural network has, I think, words in the input layer, and URLs in the output layer. The idea of the application is to attempt to train a neural network to find good search results (URLs) based on the words in the query. See the function trainquery, which takes the arguments (wordids, urlids, selectedurl). Presumably (since there's no docstring I have to guess) wordids were the words the user searched for, urlids are the URLs the search engine offered the user, and selectedurl is the one the user picked. The idea being to train the neural net to better predict which URLs users will pick, and so place those URLs higher in future search results.
So the mysterious line of code is preventing nodes being created in the hidden layer with links to more than three nodes in the input layer. In the context of the search application this makes sense: there's no point in training up the network on queries that are too specialized, because these queries won't recur often enough for the training to be worth it.
A:
You probably should have posted a little more context for code. Here is the paragraph in Programming Collective Intelligence which immediately precedes that code:
This function will create a new node
in the hidden layer every time it is
passed a combination of words that it
has never seen together before. The
function then creates default-weighted
links between the words and the hidden
node, and between the query node and
the URL results returned by this
query.
I realize it still doesn't help answer your question, but it would have helped Gareth Rees out with his answer by giving less guesswork. Gareth still got it correct, anyway, since he's clever. The intention is to restrict the number of word nodes a hidden node can be associated with, and the author chose the arbitrary number of 3.
Just to agree with Gareth, again, that paragraph should have totally been in the docstring, and the purpose of the line in question should have been in a comment above the line. I hope the next edition isn't so sloppy.
A:
To elaborate on the above comments look at this simple script...
def doSomething(wordids):
if len(wordids)>3: return None
print("The rest of the function executes")
blah = [2,3,4];
doSomething(blah)
blah = [2,3,4,5];
doSomething(blah)
. . so if the length of wordids is longer than 3 then the function does nothing. It is common to check the inputs to functions but errors are normally handled using exceptions in more advanced cases.
| Can't understand a line in a "Collective intelligence" program | I'm working through "Programming collective intelligence". In chapter 4, Toby Segaran builds an artificial neural network. The following function appears on page of the book:
def generatehiddennode(self,wordids,urls):
if len(wordids)>3: return None
# Check if we already created a node for this set of words
sorted_words=[str(id) for id in wordids]
sorted_words.sort()
createkey='_'.join(sorted_words)
res=self.con.execute(
"select rowid from hiddennode where create_key='%s'" % createkey).fetchone()
# If not, create it
if res==None:
cur=self.con.execute(
"insert into hiddennode (create_key) values ('%s')" % createkey)
hiddenid=cur.lastrowid
# Put in some default weights
for wordid in wordids:
self.setstrength(wordid,hiddenid,0,1.0/len(wordids))
for urlid in urls:
self.setstrength(hiddenid,urlid,1,0.1)
self.con.commit()
What I can't possibly understand is the reason of the first line in this function: 'if len(wordids>3): return None`. Is it a debug code that needs to be removed later?
P.S. this is not a homework
| [
"For a published book, that's pretty terrible code! (You can download all the examples for the book from here; the relevant file is chapter4/nn.py.)\n\nNo docstring. What is this function supposed to do? From its name, we can guess that it's generating one of the nodes in the \"hidden layer\" of a neural network, ... | [
6,
1,
0
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0004216108_debugging_python.txt |
Q:
how to build a python proxy server on google appengine
I live in China and the Great Firewall blocked Youtube and twitter. So I want to build a proxy server on google appengine in python to bypass that. Does anyone know any open source GAE project on that?
Thx~
A:
You may try gappproxy http://code.google.com/p/gappproxy/
But since the keyword gappproxy is blocked by censors, which means you cannot visit any url containing the keyword in China, you may first find a web proxy like http://4624.info to visit the project homepage.
By the way, you don't have to use those tools to access twitter, there are many twitter proxy websites accessible in China, which are based on twitter APIs. For example, http://rabr.in is a good alternative.
A:
please try to use http://proxy202.appspot.com
| how to build a python proxy server on google appengine | I live in China and the Great Firewall blocked Youtube and twitter. So I want to build a proxy server on google appengine in python to bypass that. Does anyone know any open source GAE project on that?
Thx~
| [
"You may try gappproxy http://code.google.com/p/gappproxy/\nBut since the keyword gappproxy is blocked by censors, which means you cannot visit any url containing the keyword in China, you may first find a web proxy like http://4624.info to visit the project homepage.\nBy the way, you don't have to use those tools ... | [
4,
1
] | [] | [] | [
"google_app_engine",
"proxy",
"python"
] | stackoverflow_0002264583_google_app_engine_proxy_python.txt |
Q:
Importing classes in python
I have a little module that creates a window (program1). I'd like to import this into another python program of mine (program2).
How would I make it so I can make so program1 makes a window when referred to by program2?
The module I'd like to import(program1).
import Tkinter
class Class(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.Main()
def Main(self):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
if __name__ == "__main__":
app = Class(None)
app.mainloop()
Edit
How do I make program 2 do the function call self.Main() that's in program1?
Also how do I go about transferring values across programs?
Say in program1 x = 'hello', how do I get the value of x in program2?
A:
If you want to run the mainloop from program2, then:
import program1
app = program1.Class(None)
app.mainloop()
or, for less duplication:
# program1.py
...
def main():
app = class(None)
app.mainloop()
if __name__ == "__main__":
main()
and then
# program2.py
import program1
program1.main()
| Importing classes in python | I have a little module that creates a window (program1). I'd like to import this into another python program of mine (program2).
How would I make it so I can make so program1 makes a window when referred to by program2?
The module I'd like to import(program1).
import Tkinter
class Class(Tkinter.Tk):
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.Main()
def Main(self):
self.button= Tkinter.Button(self,text='hello')
self.button.pack()
if __name__ == "__main__":
app = Class(None)
app.mainloop()
Edit
How do I make program 2 do the function call self.Main() that's in program1?
Also how do I go about transferring values across programs?
Say in program1 x = 'hello', how do I get the value of x in program2?
| [
"If you want to run the mainloop from program2, then:\nimport program1\napp = program1.Class(None)\napp.mainloop()\n\nor, for less duplication:\n# program1.py\n...\ndef main():\n app = class(None)\n app.mainloop()\n\nif __name__ == \"__main__\":\n main()\n\nand then\n# program2.py\nimport program1\nprogram1.main... | [
4
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004219716_python_tkinter.txt |
Q:
Why fmod(1.0,0.1) == .1?
I experienced this phenomenon in Python first, but it turned out that it is the common answer, for example MS Excel gives this. Wolfram Alpha gives an interesting schizoid answer, where it states that the rational approximation of zero is 1/5. ( 1.0 mod 0.1 )
On the other hand, if I implement the definition by hand it gives me the 'right' answer (0).
def myFmod(a,n):
return a - floor(a/n) * n
What is going on here. Do I miss something?
A:
Because 0.1 isn't 0.1; that value isn't representable in double precision, so it gets rounded to the nearest double-precision number, which is exactly:
0.1000000000000000055511151231257827021181583404541015625
When you call fmod, you get the remainder of division by the value listed above, which is exactly:
0.0999999999999999500399638918679556809365749359130859375
which rounds to 0.1 (or maybe 0.09999999999999995) when you print it.
In other words, fmod works perfectly, but you're not giving it the input that you think you are.
Edit: Your own implementation gives you the correct answer because it is less accurate, believe it or not. First off, note that fmod computes the remainder without any rounding error; the only source of inaccuracy is the representation error introduced by using the value 0.1. Now, let's walk through your implementation, and see how the rounding error that it incurs exactly cancels out the representation error.
Evaluate a - floor(a/n) * n one step at a time, keeping track of the exact values computed at each stage:
First we evaluate 1.0/n, where n is the closest double-precision approximation to 0.1 as shown above. The result of this division is approximately:
9.999999999999999444888487687421760603063276150363492645647081359...
Note that this value is not a representable double precision number -- so it gets rounded. To see how this rounding happens, let's look at the number in binary instead of decimal:
1001.1111111111111111111111111111111111111111111111111 10110000000...
The space indicates where the rounding to double precision occurs. Since the part after the round point is larger than the exact half-way point, this value rounds up to exactly 10.
floor(10.0) is, predictably, 10.0. So all that's left is to compute 1.0 - 10.0*0.1.
In binary, the exact value of 10.0 * 0.1 is:
1.0000000000000000000000000000000000000000000000000000 0100
again, this value is not representable as a double, and so is rounded at the position indicated by a space. This time it rounds down to exactly 1.0, and so the final computation is 1.0 - 1.0, which is of course 0.0.
Your implementation contains two rounding errors, which happen to exactly cancel out the representation error of the value 0.1 in this case. fmod, by contrast, is always exact (at least on platforms with a good numerics library), and exposes the representation error of 0.1.
A:
This result is due to machine floating point representation. In your method, you are 'casting' (kinda) the float to an int and do not have this issue. The 'best' way to avoid such issues (esp for mod) is to multiply by a sufficiently large enough int (only 10 is needed in your case) and perform the operation again.
fmod(1.0,0.1)
fmod(10.0,1.0) = 0
A:
From man fmod:
The fmod() function computes the floating-point remainder of dividing x
by y. The return value is x - n * y, where n is the quotient of x / y,
rounded towards zero to an integer.
So what happens is:
In fmod(1.0, 0.1), the 0.1 is actually slightly larger than 0.1 because the value cannot be exactly represented as a float.
So n = x / y = 1.0 / 0.1000something = 9.9999something
When rounded towards 0, n actually becomes 9
x - n * y = 1.0 - 9 * 0.1 = 0.1
Edit: As for why it works with floor(x/y), as far as I can tell this seems to be an FPU quirk. On x86, fmod uses the fprem instruction, whereas x/y will use fdiv. Curiously 1.0/0.1 seems to return exactly 10.0:
>>> struct.pack('d', 1.0/0.1) == struct.pack('d', 10.0)
True
I suppose fdiv uses a more precise algorithm than fprem. Some discussion can be found here: http://www.rapideuphoria.com/cgi-bin/esearch.exu?thread=1&fromMonth=A&fromYear=8&toMonth=C&toYear=8&keywords=%22Remainder%22
A:
fmod returns x-i*y, which is less than y, and i is an integer. 0.09.... is because of floating point precision. try fmod(0.3, 0.1) -> 0.09... but fmod(0.4, 0.1) -> 0.0 because 0.3 is 0.2999999... as a float.
fmod(1/(2.**n), 1/(2.**m) will never produce anything but 0.0 for integer n>=m.
A:
This gives the right answer:
a = 1.0
b = 0.1
a1,a2 = a.as_integer_ratio()
b1,b2 = b.as_integer_ratio()
div = float(a1*b2) / float(a2*b1)
mod = a - b*div
print mod
# 0.0
I think it works because by it uses rational equivalents of the two floating point numbers which provides a more accurate answer.
A:
The Python divmod function is instructive here. It tells you both the quotient and remainder of a division operation.
$ python
>>> 0.1
0.10000000000000001
>>> divmod(1.0, 0.1)
(9.0, 0.09999999999999995)
When you type 0.1, the computer can't represent that exact value in binary floating-point arithmetic, so it chooses the closest number that it can represent, 0.10000000000000001. Then when you perform the division operation, floating-point arithmetic decides that the quotient has to be 9, since 0.10000000000000001 * 10 is larger than 1.0. This leaves you with a remainder that is slightly less than 0.1.
I would want to use the new Python fractions module to get exact answers.
>>> from fractions import Fraction
>>> Fraction(1, 1) % Fraction(1, 10)
Fraction(0, 1)
IOW, (1/1) mod (1/10) = (0/1), which is equivalent to 1 mod 0.1 = 0.
Another option is to implement the modulus operator yourself, allowing you to specify your own policy.
>>> x = 1.0
>>> y = 0.1
>>> x / y - math.floor(x / y)
0.0
| Why fmod(1.0,0.1) == .1? | I experienced this phenomenon in Python first, but it turned out that it is the common answer, for example MS Excel gives this. Wolfram Alpha gives an interesting schizoid answer, where it states that the rational approximation of zero is 1/5. ( 1.0 mod 0.1 )
On the other hand, if I implement the definition by hand it gives me the 'right' answer (0).
def myFmod(a,n):
return a - floor(a/n) * n
What is going on here. Do I miss something?
| [
"Because 0.1 isn't 0.1; that value isn't representable in double precision, so it gets rounded to the nearest double-precision number, which is exactly:\n0.1000000000000000055511151231257827021181583404541015625\n\nWhen you call fmod, you get the remainder of division by the value listed above, which is exactly:\n0... | [
23,
1,
1,
0,
0,
0
] | [] | [] | [
"floating_point",
"math",
"python"
] | stackoverflow_0004218961_floating_point_math_python.txt |
Q:
Sorting data for plotting in mplot3d
I have been using mplot3d (part of matplotlib) for some various 3d plotting, and it has been performing the job admirably. However, I have run into a new problem.
Mplot3d expects data to be sorted in a certain fashion, to plot a wireframe. For example, it likes something like this:
x = array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
y = array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3])
where z is then an array of the same dimensions, with data corresponding to each of those positions in space.
Unfortunately, my data isn't formatted like this - every other row is reversed, because the data is collected by scanning in a raster pattern.
So I have something more like:
x = array([[1, 2, 3],
[3, 2, 1],
[1, 2, 3]])
My current approach is a very ugly, brute-force "do a for loop then check if you're in an odd row or not" that builds a new array out of the old one, but I am hoping there is a more elegant way of doing this. The tricky part is that I have to re-arrange the Z array in the same way I do the X and Y, to ensure that the data corresponding with each point is space is preserved.
Ideally, I'd like something that's robust and specifically designed to sort a set of 2-d arrays that contain arbitrary random position points, but even a more pythonic way of doing what I'm already doing would be appreciated. If I could make it more robust, and not dependent on this specific raster scanning pattern, it would probably save me headaches in the long term.
A:
If I understand you correctly, you just want to do this: x[1::2, :] = x[1::2, ::-1].
There are a few kinks... If you don't make an intermediate copy of x it doesn't quite do what you'd expect due to the way broadcasting works in numpy.
Nonetheless, it's still pretty simple to do with basic indexing:
import numpy as np
x = np.array([[1,2,3],[3,2,1],[1,2,3],[3,2,1],[1,2,3]])
x_rev = x.copy()
x_rev[1::2, :] = x[1::2, ::-1]
This converts this (x):
array([[1, 2, 3],
[3, 2, 1],
[1, 2, 3],
[3, 2, 1],
[1, 2, 3]])
Into this (x_rev):
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
In case you're not familiar with slicing in python, x[1::2] would select every other item of x, starting with the second item. (1 is the the start index, 2 is the increment) In contrast, x[::-1] just specifies an increment of -1, thus reversing the array. In this case we're only applying these slices to a particular axis, so we can select and reverse every other row, starting with the second row.
| Sorting data for plotting in mplot3d | I have been using mplot3d (part of matplotlib) for some various 3d plotting, and it has been performing the job admirably. However, I have run into a new problem.
Mplot3d expects data to be sorted in a certain fashion, to plot a wireframe. For example, it likes something like this:
x = array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
y = array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3])
where z is then an array of the same dimensions, with data corresponding to each of those positions in space.
Unfortunately, my data isn't formatted like this - every other row is reversed, because the data is collected by scanning in a raster pattern.
So I have something more like:
x = array([[1, 2, 3],
[3, 2, 1],
[1, 2, 3]])
My current approach is a very ugly, brute-force "do a for loop then check if you're in an odd row or not" that builds a new array out of the old one, but I am hoping there is a more elegant way of doing this. The tricky part is that I have to re-arrange the Z array in the same way I do the X and Y, to ensure that the data corresponding with each point is space is preserved.
Ideally, I'd like something that's robust and specifically designed to sort a set of 2-d arrays that contain arbitrary random position points, but even a more pythonic way of doing what I'm already doing would be appreciated. If I could make it more robust, and not dependent on this specific raster scanning pattern, it would probably save me headaches in the long term.
| [
"If I understand you correctly, you just want to do this: x[1::2, :] = x[1::2, ::-1]. \nThere are a few kinks... If you don't make an intermediate copy of x it doesn't quite do what you'd expect due to the way broadcasting works in numpy. \nNonetheless, it's still pretty simple to do with basic indexing:\nimport ... | [
2
] | [] | [] | [
"matplotlib",
"numpy",
"python",
"sorting"
] | stackoverflow_0004219723_matplotlib_numpy_python_sorting.txt |
Q:
Convert float 27.7 to 27.70
can anyone tell me a simple way to print out a float 27.7 as 27.70 ?
thanks.
A:
a = 27.7
print '%.2f' % a
27.70
A:
If you're worrying about number of digits after point, you probably need use decimal.Decimal Cite from the docs:
Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have an exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.
| Convert float 27.7 to 27.70 | can anyone tell me a simple way to print out a float 27.7 as 27.70 ?
thanks.
| [
"a = 27.7\nprint '%.2f' % a\n27.70\n\n",
"If you're worrying about number of digits after point, you probably need use decimal.Decimal Cite from the docs:\n\nDecimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have an exact representations in binary floating point. End users t... | [
8,
2
] | [] | [] | [
"python"
] | stackoverflow_0004220110_python.txt |
Q:
How can I fetch() more than 1MB on Google App Engine?
Google App Engine limits urlfetch.fetch() responses to 1MB. Is there any workaround of this (switching to paid version maybe)?
I'm using Python and if it's possible to provide an example that would be great.
A:
With the brand new SDK 1.4.0 you can download 32MByte; keep in mind that you still have the 10 seconds Deadline limit though ;-) . deadline can be up to a maximum of 60 seconds for request handlers and 10 minutes for tasks queue and cron job handlers.
URLFetch allowed response size has
been increased, up to 32 MB. Request
size is still limited to 1 MB.
A:
No, you cannot fetch more than 1MB per URL fetch (even if you enable billing). However, you might be able to fetch portions of the target URL using the Range header and then combine these pieces. This might even be faster since you could fetch each 1MB chunk simultaneously (using asynchronous fetches).
| How can I fetch() more than 1MB on Google App Engine? | Google App Engine limits urlfetch.fetch() responses to 1MB. Is there any workaround of this (switching to paid version maybe)?
I'm using Python and if it's possible to provide an example that would be great.
| [
"With the brand new SDK 1.4.0 you can download 32MByte; keep in mind that you still have the 10 seconds Deadline limit though ;-) . deadline can be up to a maximum of 60 seconds for request handlers and 10 minutes for tasks queue and cron job handlers.\n\nURLFetch allowed response size has\n been increased, up to ... | [
3,
2
] | [] | [] | [
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0004109255_google_app_engine_python_urlfetch.txt |
Q:
Best method to locate object with opencv
What is the most efficient way using opencv and python to locate and return the coordinates of a single object that has a constant color? I have seen a few ways to do so using c++, but info on object location using python is sparse.
A:
I am not sure what you are looking for exactly, but I think you should have a look at the Haar classification.
See here for example:
http://cgi.cse.unsw.edu.au/~cs4411/wiki/index.php?title=OpenCV_Guide#Haar_Classifier
A:
To be more specific if you have an object with single colour you can look at the camshift tracker. The camshift demo in Python is included with the OpenCV source. It is much more efficient for a single colour blob than Haar and requires virtually no training, just initialization with where the object is.
| Best method to locate object with opencv | What is the most efficient way using opencv and python to locate and return the coordinates of a single object that has a constant color? I have seen a few ways to do so using c++, but info on object location using python is sparse.
| [
"I am not sure what you are looking for exactly, but I think you should have a look at the Haar classification.\nSee here for example:\nhttp://cgi.cse.unsw.edu.au/~cs4411/wiki/index.php?title=OpenCV_Guide#Haar_Classifier\n",
"To be more specific if you have an object with single colour you can look at the camshif... | [
1,
1
] | [] | [] | [
"location",
"object",
"opencv",
"python"
] | stackoverflow_0004220271_location_object_opencv_python.txt |
Q:
Python/Tkinter: bind to event related to currently selected menu item
Wondering if there's a menu event I can bind to that's related to the currently selected menu item? By menu item I mean the items that show up in a popup menu like New, Open, Save, etc.
Use case: I would like to update a statusbar area of our application with a description of the currently selected menu item.
Any ideas appreciated.
Thank you,
Malcolm
A:
You need to bind to the <<MenuSelect>> event.
| Python/Tkinter: bind to event related to currently selected menu item | Wondering if there's a menu event I can bind to that's related to the currently selected menu item? By menu item I mean the items that show up in a popup menu like New, Open, Save, etc.
Use case: I would like to update a statusbar area of our application with a description of the currently selected menu item.
Any ideas appreciated.
Thank you,
Malcolm
| [
"You need to bind to the <<MenuSelect>> event.\n"
] | [
2
] | [
"There's an <Enter> event that is triggered when the mouse pointer enters a widget's space. Depending on how you're building your menu, you may be able to use it.\nSee http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm for more\n"
] | [
-1
] | [
"menu",
"python",
"tkinter"
] | stackoverflow_0004220441_menu_python_tkinter.txt |
Q:
Terminating raw_input() if other text displays
I have a simple server application I made in Python using SocketServer, it has a very primitive command line type input system. My main problem here is that when the server receives a message, it prints it to the screen. This is all fine and good except that the raw_input function is still waiting for text to entered and checked. Is there a way to, in the server handle() function, stop the raw_input or raise some exception that would end the input and display the information that the server is receiving?
Thanks,
Zack.
A:
As far as I know, this isn't possible because raw_input accepts input from the python command console. There are, however, some ways to get around it that may not be expected:
1 - Instead of using the console, create a simple Tkinter window with the output and an input line. Create a custom print function that appends the message to the end of the window text, (Which could be in a scroll bar using a fixed-width font) and then create a command prompt box that responds to enter. The code for that would look something like this:
from Tkinter import *
root = Tk()
topframe=Frame(root)
bottomframe=Frame(root)
bottomframe.pack(side=BOTTOM,fill=X)
topframe.pack(side=TOP,fill=BOTH)
scrollbar = Scrollbar(topframe)
scrollbar.pack(side=RIGHT,fill=Y)
text = Text(topframe,yscrollcommand=scrollbar.set)
text.pack(side=LEFT,fill=BOTH)
scrollbar.config(command=text.yview)
text.config(state=DISABLED)
v = StringVar()
e = Entry(bottomframe,textvariable=v)
def submit():
command = v.get()
v.set('')
#your input handling code goes here.
wprint(command)
#end your input handling
e.bind('<Return>',submit)
button=Button(bottomframe,text='RUN',command=submit)
button.pack(side=RIGHT)
e.pack(expand=True,side=LEFT,fill=X)
def wprint(obj):
text.config(state=NORMAL)
text.insert(END,str(obj)+'\n')
text.config(state=DISABLED)
root.mainloop()
Another option would be to create your own print and raw_input methods to look something like this:
import threading
wlock=threading.Lock()
printqueue=[]
rinput=False
def winput(text):
with wlock:
global printqueue,rinput
rinput=True
text = raw_input(text)
rinput=False
for text in printqueue:
print(text)
printqueue=[]
return text
def wprint(obj):
global printqueue
if not(rinput):
print(str(obj))
else:
printqueue.append(str(obj))
| Terminating raw_input() if other text displays | I have a simple server application I made in Python using SocketServer, it has a very primitive command line type input system. My main problem here is that when the server receives a message, it prints it to the screen. This is all fine and good except that the raw_input function is still waiting for text to entered and checked. Is there a way to, in the server handle() function, stop the raw_input or raise some exception that would end the input and display the information that the server is receiving?
Thanks,
Zack.
| [
"As far as I know, this isn't possible because raw_input accepts input from the python command console. There are, however, some ways to get around it that may not be expected:\n1 - Instead of using the console, create a simple Tkinter window with the output and an input line. Create a custom print function that ap... | [
1
] | [] | [] | [
"python",
"raw_input"
] | stackoverflow_0004220702_python_raw_input.txt |
Q:
pySerial freezing after reading 3 times
We are programming a pic and we've diagnosed that if we send data to serial port while its trying to send data to us, the program will lock up (both our python code and hyperterminal will crash when tested). It worked in hyperterminal and inputting it slowly (>.5 seconds between strokes), and would crash when the keyboard was bashed. So what we did was introduce a time.sleep which is longer than .5 seconds, but it is still not working.
Here's our test code.
import serial
import time
ser = serial.Serial("COM1")
ser.baudrate=2400
while 1:
for i in range(23):
ser.write(0x41)
time.sleep(.5)
print("ok")
rec = ser.read()
rec2 = ser.read()
rec3 = ser.read()
print(rec)
print(rec2)
print(rec3)
for i in range(23):
data = ser.read()
print(data)
print("ok")
time.sleep(5)
our receive data function. We used to have the "ok" being sent everytime it recieved a char (which is how we know that it freezes after 3 iterations). We brought it outside of the loop to see if that was causing the problem and it was not the case. It is not sending the "ok" at all with this code.
unsigned char receiveData(unsigned char *rxData, int length){
// 1. Flag bit, RCIF, will be set when reception is complete and an interrupt will be generated if enable bit, RCIE, was set.
char send[3] = "ok";
int index = 0;
if(rxData==(void*)0 || rxInitialized==FALSE) return FAILURE;
while(index<length){
while(PIR1bits.RCIF==0);
rxData[index]= RCREG;
Delay1KTCYx(5);
index++;
}
configureTransmission();
sendData(send,3);
// 2. Read the RCSTA register to get the 9th bit (if enabled) and determine if any error occurred during reception.
// 3. Read the 8-bit received data by reading the RCREG register.
// 4. If any error occurred, clear the error by clearing enable bit CREN.
return SUCCESS;
}
A:
(This answer assumes that you are using a PIC16, suggested by the names of certain registers.)
In short, it looks like a buffer overflow coupled with a bug in that loop in receiveData. The fact that it's freezing after three characters are sent in short succession might be explained by p117 of the manual:
It is possible for two bytes of data to be received and transferred to the RCREG FIFO and a third byte to begin shifting to the RSR register
This would explain the magic number three.
Stepping through your PIC code, consider the following scenario (just an example). First time around:
// One character already in RCREG - RCIF set
while(PIR1bits.RCIF==0);
// Reads ONE character - RCIF clear
rxData[index]= RCREG;
// While waiting here, two more characters are received - RCIF set
Delay1KTCYx(5);
index++;
Second time around:
// RCIF set from before
while(PIR1bits.RCIF==0);
// Reads ONE character - RCIF STILL set, ONE character remains in UART FIFO!
rxData[index]= RCREG;
// While waiting here, three more characters are received
// RCIF set, RCREG fills up and the third character is discarded!
Delay1KTCYx(5);
index++;
Now the rest of the loop will keep reading from RCREG until index == length, but since some characters were discarded while the UART FIFO was full, you'll never get there and appear to freeze!
What is even more likely is that you are receiving characters before you even get to that function, so the UART FIFO fills up before you even get there.
There are a few ways around this.
Do this in an interrupt so it's a bit faster to move the incoming characters into the buffer.
Use a loop for reading from RCREG: while(RCIF) rxData[index]= RCREG; this makes sure you empty the buffer when reading from the UART buffer, but it will not stop overflows outside of this function or during that delay though.
Check the OERR flag - if it is set, assume something bad happened and start over.
Have a stop character or start character (eg. end-of-line, punctuation, etc) that tells you when a valid command is starting or stopping. If you get two start characters without a stop character, or some other confusing combination, assume you're in a bad state and start over.
Some additional advice: you can go absolutely crazy trying to account and compensate for every missed character or problem like this in your PIC code, but ultimately it's just another comms error. Priorities in the PIC code should be: quick recovery from errors and not locking up. Error detection and sane recovery should be handled by the client code, where it's far, far easier.
A:
Does the communication from the PIC make use of the RTS/CTS lines of the serial port ? Probably the PIC expects some sort of flow control and you are sending data too fast to it without any flow control. Read up on the limitations of the PIC and if needed open the port with flow control enabled.
| pySerial freezing after reading 3 times | We are programming a pic and we've diagnosed that if we send data to serial port while its trying to send data to us, the program will lock up (both our python code and hyperterminal will crash when tested). It worked in hyperterminal and inputting it slowly (>.5 seconds between strokes), and would crash when the keyboard was bashed. So what we did was introduce a time.sleep which is longer than .5 seconds, but it is still not working.
Here's our test code.
import serial
import time
ser = serial.Serial("COM1")
ser.baudrate=2400
while 1:
for i in range(23):
ser.write(0x41)
time.sleep(.5)
print("ok")
rec = ser.read()
rec2 = ser.read()
rec3 = ser.read()
print(rec)
print(rec2)
print(rec3)
for i in range(23):
data = ser.read()
print(data)
print("ok")
time.sleep(5)
our receive data function. We used to have the "ok" being sent everytime it recieved a char (which is how we know that it freezes after 3 iterations). We brought it outside of the loop to see if that was causing the problem and it was not the case. It is not sending the "ok" at all with this code.
unsigned char receiveData(unsigned char *rxData, int length){
// 1. Flag bit, RCIF, will be set when reception is complete and an interrupt will be generated if enable bit, RCIE, was set.
char send[3] = "ok";
int index = 0;
if(rxData==(void*)0 || rxInitialized==FALSE) return FAILURE;
while(index<length){
while(PIR1bits.RCIF==0);
rxData[index]= RCREG;
Delay1KTCYx(5);
index++;
}
configureTransmission();
sendData(send,3);
// 2. Read the RCSTA register to get the 9th bit (if enabled) and determine if any error occurred during reception.
// 3. Read the 8-bit received data by reading the RCREG register.
// 4. If any error occurred, clear the error by clearing enable bit CREN.
return SUCCESS;
}
| [
"(This answer assumes that you are using a PIC16, suggested by the names of certain registers.) \nIn short, it looks like a buffer overflow coupled with a bug in that loop in receiveData. The fact that it's freezing after three characters are sent in short succession might be explained by p117 of the manual:\n\nIt ... | [
2,
1
] | [] | [] | [
"pic",
"pyserial",
"python",
"serial_port"
] | stackoverflow_0004219868_pic_pyserial_python_serial_port.txt |
Q:
Splitting a string into a list in python
I have a long string of characters which I want to split into a list of the individual characters. I want to include the whitespaces as members of the list too. How do I do this?
A:
you can do:
list('foo')
spaces will be treated as list members (though not grouped together, but you didn't specify you needed that)
>>> list('foo')
['f', 'o', 'o']
>>> list('f oo')
['f', ' ', 'o', 'o']
A:
Here some comparision on string and list of strings, and another way to make list out of string explicitely for fun, in real life use list():
b='foo of zoo'
a= [c for c in b]
a[0] = 'b'
print 'Item assignment to list and join:',''.join(a)
try:
b[0] = 'b'
except TypeError:
print 'Not mutable string, need to slice:'
b= 'b'+b[1:]
print b
A:
This isn't an answer to the original question but to your 'how do I use the dict option' (to simulate a 2D array) in comments above:
WIDTH = 5
HEIGHT = 5
# a dict to be used as a 2D array:
grid = {}
# initialize the grid to spaces
for x in range(WIDTH):
for y in range(HEIGHT):
grid[ (x,y) ] = ' '
# drop a few Xs
grid[ (1,1) ] = 'X'
grid[ (3,2) ] = 'X'
grid[ (0,4) ] = 'X'
# iterate over the grid in raster order
for x in range(WIDTH):
for y in range(HEIGHT):
if grid[ (x,y) ] == 'X':
print "X found at %d,%d"%(x,y)
# iterate over the grid in arbitrary order, but once per cell
count = 0
for coord,contents in grid.iteritems():
if contents == 'X':
count += 1
print "found %d Xs"%(count)
Tuples, being immutable, make perfectly good dictionary keys. Cells in the grid don't exist until you assign to them, so it's very efficient for sparse arrays if that's your thing.
| Splitting a string into a list in python | I have a long string of characters which I want to split into a list of the individual characters. I want to include the whitespaces as members of the list too. How do I do this?
| [
"you can do:\nlist('foo')\n\nspaces will be treated as list members (though not grouped together, but you didn't specify you needed that) \n>>> list('foo')\n['f', 'o', 'o']\n>>> list('f oo')\n['f', ' ', 'o', 'o']\n\n",
"Here some comparision on string and list of strings, and another way to make list out of st... | [
12,
0,
0
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0004216489_python_split_string.txt |
Q:
python regex grouping
Given string s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
I would like to get this output: (C /something_3),/,(D /something_4)(D /something_5)
I keep matching the whole string s, instead of getting above substring.
I am using re.search(r'(\(C.*\)),/,(\(D.*\))+')
Any help is appreciated...
A:
You're just about there - re.search(r'(\(C.*\)),/,(\(D.*\))+', s).group() will get you what you want.
>>> import re
>>> s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
>>> re.search(r'(\(C.*\)),/,(\(D.*\))+', s).group()
'(C /something_3),/,(D /something_4)(D /something_5)'
Are you wanting to further split that in groups?
A:
Using Python 2.7, I get the exact result you're after:
import re
s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
m = re.search(r'(\(C.*\)),/,(\(D.*\))+', s)
s[m.start():m.end()] == '(C /something_3),/,(D /something_4)(D /something_5)'
| python regex grouping | Given string s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
I would like to get this output: (C /something_3),/,(D /something_4)(D /something_5)
I keep matching the whole string s, instead of getting above substring.
I am using re.search(r'(\(C.*\)),/,(\(D.*\))+')
Any help is appreciated...
| [
"You're just about there - re.search(r'(\\(C.*\\)),/,(\\(D.*\\))+', s).group() will get you what you want.\n>>> import re\n>>> s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'\n>>> re.search(r'(\\(C.*\\)),/,(\\(D.*\\))+', s).group()\n'(C /something_3),/,(D /something_4)(D /s... | [
4,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004221534_python_regex.txt |
Q:
How to set up "front page" documentation on PYPI for a project?
I would like to add basic documentation content to the front page of PYPI of my module like it's done, for example, here: http://pypi.python.org/pypi/Jinja2.
Right now the askbot download page has a default look and does not have much useful info, how can it be added? That is - which parts of the distribution package files/which file must be edited?
Thanks!
A:
Did you take a look at : http://pypi.python.org/pypi/an_example_pypi_project
Also PyPI attempts to parse the "long_description" from your meta-data as ReStructuredText. You could use that to provide a good information rendering.
A:
If you're logged in you can edit the "Description" section of your packages.
They use the reStructuredText syntax for the field so you can use that for formatting: http://docutils.sourceforge.net/rst.html
| How to set up "front page" documentation on PYPI for a project? | I would like to add basic documentation content to the front page of PYPI of my module like it's done, for example, here: http://pypi.python.org/pypi/Jinja2.
Right now the askbot download page has a default look and does not have much useful info, how can it be added? That is - which parts of the distribution package files/which file must be edited?
Thanks!
| [
"Did you take a look at : http://pypi.python.org/pypi/an_example_pypi_project\nAlso PyPI attempts to parse the \"long_description\" from your meta-data as ReStructuredText. You could use that to provide a good information rendering.\n",
"If you're logged in you can edit the \"Description\" section of your package... | [
5,
1
] | [] | [] | [
"packaging",
"pypi",
"python"
] | stackoverflow_0004221555_packaging_pypi_python.txt |
Q:
Python Numpy nan_to_num help
I'm having some trouble with Numpy's nan_to_num function: I've got an array where the last column contains fewer elements than the other columns, and when I import it into Python, it places 'nan's to fill out the array. That's just fine until I need to do some other things that get tripped-up by the 'nan's.
I'm trying to use 'nan_to_num' with no success. It's likely a small thing I'm missing, but I can't figure it out.
Here's some simple input and output:
input:
a = numpy.array([[1, nan, 3]])
print a
numpy.nan_to_num(a)
print a
output
[[ 1. nan 3.]]
[[ 1. nan 3.]]
The second 'nan' should be a zero...
http://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html
Thanks in advance.
A:
You haven't changed the value of a. Try this:
a = numpy.array([[1, nan, 3]])
a = numpy.nan_to_num(a)
print a
| Python Numpy nan_to_num help | I'm having some trouble with Numpy's nan_to_num function: I've got an array where the last column contains fewer elements than the other columns, and when I import it into Python, it places 'nan's to fill out the array. That's just fine until I need to do some other things that get tripped-up by the 'nan's.
I'm trying to use 'nan_to_num' with no success. It's likely a small thing I'm missing, but I can't figure it out.
Here's some simple input and output:
input:
a = numpy.array([[1, nan, 3]])
print a
numpy.nan_to_num(a)
print a
output
[[ 1. nan 3.]]
[[ 1. nan 3.]]
The second 'nan' should be a zero...
http://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html
Thanks in advance.
| [
"You haven't changed the value of a. Try this:\na = numpy.array([[1, nan, 3]])\na = numpy.nan_to_num(a)\nprint a\n\n"
] | [
4
] | [] | [] | [
"function",
"numpy",
"python"
] | stackoverflow_0004221475_function_numpy_python.txt |
Q:
How do i get the username and email when someone logins to my site using google or openid? What does google return?
i used pinax, the user who login my site, use openid, is successful now.
i only want to get the username and email when they return .
the google openid url is :https://www.google.com/accounts/o8/id
and yahoo openid url is :http://yahoo.com/
How can i get it?
A:
Use http://code.google.com/p/django-openid/ (documentation available at http://django-openid.googlecode.com/svn/trunk/openid.html)
A:
There are two main methods to do this. One is using the "simple
registration" (sreg) extension of OpenID. This seems like the easiest
way, and while it worked when using myopenid.net as my endpoint, but I
couldn't get it to work with Google.
The second method is by using the "attribute exchange" (ax) extension. I was able to get it working using Authkit under Pylons with a bit of tweaking. I'm sure you can do the same with Django. I would recommend that you start with the Google docs regarding their AX support: http://code.google.com/apis/accounts/docs/OpenID.html
A:
@jamieb - maybe you meant myopenid.com?
Even if late, I wish to share my experience on the question to help others. I spent a day on these!
I used https://github.com/flashingpumpkin/django-socialregistration and only experimented with Simple Registration on the following sites:
Google - No information returned or perhaps I need to dig deeper
Yahoo - No information returned or perhaps I need to dig deeper
myOpenID - Yes! You need to add Registration Personas to which your user will select during the login/registration process. And for each Persona, you can specify picture, full name, nickname, email, birthday, gender, web/url, postal code, country, language.
So to answer the question, if you use Simple registration, you can't get the email or username of the user from Google or Yahoo.
| How do i get the username and email when someone logins to my site using google or openid? What does google return? | i used pinax, the user who login my site, use openid, is successful now.
i only want to get the username and email when they return .
the google openid url is :https://www.google.com/accounts/o8/id
and yahoo openid url is :http://yahoo.com/
How can i get it?
| [
"Use http://code.google.com/p/django-openid/ (documentation available at http://django-openid.googlecode.com/svn/trunk/openid.html)\n",
"There are two main methods to do this. One is using the \"simple\nregistration\" (sreg) extension of OpenID. This seems like the easiest\nway, and while it worked when using my... | [
1,
1,
0
] | [] | [] | [
"django",
"openid",
"pinax",
"python"
] | stackoverflow_0002264669_django_openid_pinax_python.txt |
Q:
How do I add tags to certain strings in python using re.sub?
I'm trying to add tags to some given query strings, and the tags should wrap around all the matching strings.
For example, I want to wrap tags around all the words that match the query iphone games mac in the sentence I love downloading iPhone games from my mac. It should be I love downloading <em>iPhone games</em> from my <em>mac</em>.
Currently, I tried
sentence = "I love downloading iPhone games from my mac."
query = r'((iphone|games|mac)\s*)+'
regex = re.compile(query, re.I)
sentence = regex.sub(r'<em>\1</em> ', sentence)
The sentence outputs
I love downloading <em>games </em> on my <em>mac</em> !
Where \1 is only replace by one word (games instead of iPhone games) and there are some unnecessary spaces after the word. How do I write the regular expression to get the desired output? Thanks!
Edit:
I just realized that both Fred and Chris's solutions have problems when I have words within words. For instance, if my query is game, then it will turn out to be <em>game</em>s while I want it not be highlighted. Another example is the in either shouldn't be highlighted.
Edit 2:
I took Chris' new solution and it works.
A:
First of all, to get the spaces as you want them, replace \s* with \s*? to make it non-greedy.
First fix:
>>> re.compile(r'(((iphone|games|mac)\s*?)+)', re.I).sub(r'<em>\1</em>', sentence)
'I love downloading <em>iPhone</em> <em>games</em> from my <em>mac</em>.'
Unfortunately, once the \s* is non-greedy, it splits phrases, as you can see. Without it, it goes like this, grouping the two together:
>>> re.compile(r'(((iPhone|games|mac)\s*)+)').sub(r'<em>\1</em>', sentence)
'I love downloading <em>iPhone games </em>from my <em>mac</em>.'
I can't think yet how to fix this.
Note also that in these I have stuck in an extra set of brackets around the + so that all matches get caught - that's the difference.
Further update: actually, I can think of a way to get around it. You decide whether you want it like that.
>>> regex = re.compile(r'((iphone|games|mac)(\s*(iphone|games|mac))*)', re.I)
>>> regex.sub(r'<em>\1</em>', sentence)
'I love downloading <em>iPhone games</em> from my <em>mac</em>.'
Update: taking your point about word boundaries into account, we only need to add in a few instances of \b, the word boundary matcher.
>>> regex = re.compile(r'(\b(iphone|games|mac)\b(\s*(iphone|games|mac)\b)*)', re.I)
>>> regex.sub(r'<em>\1</em>', 'I love downloading iPhone games from my mac')
'I love downloading <em>iPhone games</em> from my <em>mac</em>'
>>> regex.sub(r'<em>\1</em>', 'I love downloading iPhone gameses from my mac')
'I love downloading <em>iPhone</em> gameses from my <em>mac</em>'
>>> regex.sub(r'<em>\1</em>', 'I love downloading iPhoney games from my mac')
'I love downloading iPhoney <em>games</em> from my <em>mac</em>'
>>> regex.sub(r'<em>\1</em>', 'I love downloading iPhoney gameses from my mac')
'I love downloading iPhoney gameses from my <em>mac</em>'
>>> regex.sub(r'<em>\1</em>', 'I love downloading miPhone gameses from my mac')
'I love downloading miPhone gameses from my <em>mac</em>'
>>> regex.sub(r'<em>\1</em>', 'I love downloading miPhone games from my mac')
'I love downloading miPhone <em>games</em> from my <em>mac</em>'
>>> regex.sub(r'<em>\1</em>', 'I love downloading iPhone igames from my mac')
'I love downloading <em>iPhone</em> igames from my <em>mac</em>'
A:
>>> r = re.compile(r'(\s*)((?:\s*\b(?:iphone|games|mac)\b)+)', re.I)
>>> r.sub(r'\1<em>\2</em>', sentence)
'I love downloading <em>iPhone games</em> from my <em>mac</em>.'
The extra group fully containing the plus-repetition avoids losing words, while shifting the spaces before the words — but taking out leading spaces initially — handles that problem. The word boundary assertions require full word matching for the 3 words between them. However, NLP is hard and there will still be cases where this doesn't work as expected.
| How do I add tags to certain strings in python using re.sub? | I'm trying to add tags to some given query strings, and the tags should wrap around all the matching strings.
For example, I want to wrap tags around all the words that match the query iphone games mac in the sentence I love downloading iPhone games from my mac. It should be I love downloading <em>iPhone games</em> from my <em>mac</em>.
Currently, I tried
sentence = "I love downloading iPhone games from my mac."
query = r'((iphone|games|mac)\s*)+'
regex = re.compile(query, re.I)
sentence = regex.sub(r'<em>\1</em> ', sentence)
The sentence outputs
I love downloading <em>games </em> on my <em>mac</em> !
Where \1 is only replace by one word (games instead of iPhone games) and there are some unnecessary spaces after the word. How do I write the regular expression to get the desired output? Thanks!
Edit:
I just realized that both Fred and Chris's solutions have problems when I have words within words. For instance, if my query is game, then it will turn out to be <em>game</em>s while I want it not be highlighted. Another example is the in either shouldn't be highlighted.
Edit 2:
I took Chris' new solution and it works.
| [
"First of all, to get the spaces as you want them, replace \\s* with \\s*? to make it non-greedy.\nFirst fix:\n>>> re.compile(r'(((iphone|games|mac)\\s*?)+)', re.I).sub(r'<em>\\1</em>', sentence)\n'I love downloading <em>iPhone</em> <em>games</em> from my <em>mac</em>.'\n\nUnfortunately, once the \\s* is non-greedy... | [
5,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004221509_python_regex.txt |
Q:
Python: sqlite OR statement
Is there an OR sqlite statement? I've been trying to google it, but google seems to be filtering out the OR.
For example if I wanted to find someone in this table (people)
people:
+--fname--+--lname--+--has_squirrel--+
|Eric |Schmidt |0 |
+---------+---------+----------------+
|Elvis |Presley |1 |
+---------+---------+----------------+
|Richard |Stallman |0 |
+---------+---------+----------------+
with a first name of either Elvis or Richard, what would my query be?
I've tried things like select * from people where fname=('Elvis' or 'Richard'), but that always returns Eric Schmidt (the exact opposite rows of what I want)!
I've also tried select * from people where fname='Elvis' or 'Richard' but that returns all the rows in the table!
I'm using the Python 2.6 sqlite3 module on Ubuntu 10.10. Can someone give me a quick explanation of the sqlite OR statment or tell me if it doesn't exist? I've tried to RTFM and I couldn't find anything (searching for OR on the sqlite website spits out a bunch of errors!).
Thanks!
A:
It would be one of those :
SELECT * FROM people WHERE fname IN ('Elvis', 'Richard');
SELECT * FROM people WHERE fname = 'Elvis' OR fname = 'Richard';
I'm surprised your first query even works, and in your second, or 'Richard' basically means or 1=1, which is always true, for every row in your table.
Your computer doesn't think like you do. Even if fname = 'Elvis' or 'Richard' seems obvious to you, the RDBMS doesn't know what you mean and reads "if fname is equal to 'Elvis' or... true". It evalutes the string to a boolean, and I assume since it's not empty, it's evaluated to true. And proceeds to select every row from your table, as I said earlier.
A:
"SQLite logical operators" was my query, and found you this: http://zetcode.com/databases/sqlitetutorial/expressions/
As to your actual results, you're comparing cows with donkeys :D. When you say:
select * from people where fname='Elvis' or 'Richard'
You're saying:
Give me all the rows from people that
satisfy the following: it's true that
fname equals Elvis, or it's true that
Richard.
You're getting all the rows because Richard is considered true, being a non-empty string.
What you should do is:
select * from people where fname='Elvis' or fname='Richard'
Cheers!
A:
just a quick one, have you tried select * from people where fname='Elvis' or fname='Richard'
A:
Try this:
select * from people where fname = 'Elvis' or fname = 'Richard'
A:
OR is a logical statement that returns true or false.
So ("Elvis" or "Richard") returns probably false.
And your actual SQL is really " fname = False ". most databases would throw an error but because sqlite internally follows TCL's "everything is a string" philosophy it is a valid statement.
What you need is simply:
select * from people where fname='Elvis' or fname = 'Richard'
| Python: sqlite OR statement | Is there an OR sqlite statement? I've been trying to google it, but google seems to be filtering out the OR.
For example if I wanted to find someone in this table (people)
people:
+--fname--+--lname--+--has_squirrel--+
|Eric |Schmidt |0 |
+---------+---------+----------------+
|Elvis |Presley |1 |
+---------+---------+----------------+
|Richard |Stallman |0 |
+---------+---------+----------------+
with a first name of either Elvis or Richard, what would my query be?
I've tried things like select * from people where fname=('Elvis' or 'Richard'), but that always returns Eric Schmidt (the exact opposite rows of what I want)!
I've also tried select * from people where fname='Elvis' or 'Richard' but that returns all the rows in the table!
I'm using the Python 2.6 sqlite3 module on Ubuntu 10.10. Can someone give me a quick explanation of the sqlite OR statment or tell me if it doesn't exist? I've tried to RTFM and I couldn't find anything (searching for OR on the sqlite website spits out a bunch of errors!).
Thanks!
| [
"It would be one of those :\nSELECT * FROM people WHERE fname IN ('Elvis', 'Richard');\nSELECT * FROM people WHERE fname = 'Elvis' OR fname = 'Richard';\n\nI'm surprised your first query even works, and in your second, or 'Richard' basically means or 1=1, which is always true, for every row in your table.\nYour com... | [
21,
3,
0,
0,
0
] | [] | [] | [
"linux",
"python",
"sql",
"sqlite",
"ubuntu"
] | stackoverflow_0004221956_linux_python_sql_sqlite_ubuntu.txt |
Q:
Why pysqlite does not work properly?
I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:
python setup.py build
I got the following message in the end:
src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function)
src/module.c:287: error: ‘SQLITE_READ’ undeclared here (not in a function)
src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function)
src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function)
src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function)
src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function)
src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function)
src/module.c: In function ‘init_sqlite’:
src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’
src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast
error: command 'gcc' failed with exit status 1
I just ignored the last line and decided to continue. So, I typed:
python setup.py install
And than, again, I got similar error message:
src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function)
src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function)
src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function)
src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function)
src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function)
src/module.c: In function ‘init_sqlite’:
src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’
src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast
error: command 'gcc' failed with exit status 1
After that I wanted to try if pysqlite works.
If in the python-command-line mode I type
from pysqlite2 import *
Python does not complain. However, if I try to follow an exmaple in my book:
from pysqlite2 import dbapi2 as sqlite
I get a error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pysqlite2/dbapi2.py", line 27, in <module>
from pysqlite2._sqlite import *
ImportError: No module named _sqlite
Does anybody have any ideas why it happens and how this problem can be solved. By the way, I have installed a new version of Python. "python -V" gives me "Python 2.6.2". Thank you in advance for any help.
A:
I just ignored the last line and decided to continue.
You can't just ignore the last line. It was telling you there was an error, so it couldn't compile. The next thing you ran told you it couldn't install because it couldn't compile. Then, your python told you it couldn't run the code because it wasn't installed. You need to get the compile step working before you move on to installing it.
A:
A lesson in compiling python extensions is needed, which distribution are you using ? You seem to be missing the sqlite headers with the given macro definitions. When the python setup runs it compiles bindings to the sqlite native binary and copies a few .py files to the library. The _sqlite is typically a .pyd file (equivalent to a dll) which has calls to the sqlite library, in your case that did not get built.
Check the presence of the sqlite headers etc.
A:
The correct way to build pysqlite is now on the website.
$ tar xvfz <version>.tar.gz
$ cd <version>
$ python setup.py build_static install
The build_static will download the latest sqlite code and statically compile against it. For a note I just did this on a 1and1 shared host.
http://trac.edgewall.org/wiki/PySqlite#Buildingpysqlite
| Why pysqlite does not work properly? | I tried to install pysqlite. Some suspicious things start to appear during the installation. Why I typed:
python setup.py build
I got the following message in the end:
src/module.c:286: error: ‘SQLITE_PRAGMA’ undeclared here (not in a function)
src/module.c:287: error: ‘SQLITE_READ’ undeclared here (not in a function)
src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function)
src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function)
src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function)
src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function)
src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function)
src/module.c: In function ‘init_sqlite’:
src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’
src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast
error: command 'gcc' failed with exit status 1
I just ignored the last line and decided to continue. So, I typed:
python setup.py install
And than, again, I got similar error message:
src/module.c:288: error: ‘SQLITE_SELECT’ undeclared here (not in a function)
src/module.c:289: error: ‘SQLITE_TRANSACTION’ undeclared here (not in a function)
src/module.c:290: error: ‘SQLITE_UPDATE’ undeclared here (not in a function)
src/module.c:291: error: ‘SQLITE_ATTACH’ undeclared here (not in a function)
src/module.c:292: error: ‘SQLITE_DETACH’ undeclared here (not in a function)
src/module.c: In function ‘init_sqlite’:
src/module.c:419: warning: implicit declaration of function ‘sqlite3_libversion’
src/module.c:419: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast
error: command 'gcc' failed with exit status 1
After that I wanted to try if pysqlite works.
If in the python-command-line mode I type
from pysqlite2 import *
Python does not complain. However, if I try to follow an exmaple in my book:
from pysqlite2 import dbapi2 as sqlite
I get a error message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pysqlite2/dbapi2.py", line 27, in <module>
from pysqlite2._sqlite import *
ImportError: No module named _sqlite
Does anybody have any ideas why it happens and how this problem can be solved. By the way, I have installed a new version of Python. "python -V" gives me "Python 2.6.2". Thank you in advance for any help.
| [
"\nI just ignored the last line and decided to continue.\n\nYou can't just ignore the last line. It was telling you there was an error, so it couldn't compile. The next thing you ran told you it couldn't install because it couldn't compile. Then, your python told you it couldn't run the code because it wasn't insta... | [
3,
2,
2
] | [] | [] | [
"installation",
"pysqlite",
"python",
"sqlite"
] | stackoverflow_0001460136_installation_pysqlite_python_sqlite.txt |
Q:
ActivePython and MySQLdb
I have installed ActivePython and am trying to import MySQLdb
>> import mySQLdb
gives me an error stating No module called MySQLdb
I have tried searching but all the resources out there explain how to set up the mySQLdb for unix, not for windows, can you please tell me how I can do that with ActivePython? I am also planning to use pyDev (eclipse) from now on, how do I configure MySQLdb in both cases?
Thanks
A:
You can find a detailed HOWTO over here
A:
To install MySQL-Python,
pypm install mysql-python
| ActivePython and MySQLdb | I have installed ActivePython and am trying to import MySQLdb
>> import mySQLdb
gives me an error stating No module called MySQLdb
I have tried searching but all the resources out there explain how to set up the mySQLdb for unix, not for windows, can you please tell me how I can do that with ActivePython? I am also planning to use pyDev (eclipse) from now on, how do I configure MySQLdb in both cases?
Thanks
| [
"You can find a detailed HOWTO over here\n",
"To install MySQL-Python,\npypm install mysql-python\n\n"
] | [
0,
0
] | [] | [] | [
"activepython",
"mysql",
"python"
] | stackoverflow_0002551856_activepython_mysql_python.txt |
Q:
Get and set data on Google App Engine
How can I store some data on Google App Engine? I'm using Django.
A:
Assuming you don't want to just write web form pages to do this, you might want to take a look at http://code.google.com/appengine/docs/python/tools/uploadingdata.html which explains a few different ways to import/export data from the appengine datastore.
A:
You can use google app engine helper. Django cannot understand google app engine so you can use this helper to make the Django understand app engine and you are good to go..
http://code.google.com/p/google-app-engine-django/
| Get and set data on Google App Engine | How can I store some data on Google App Engine? I'm using Django.
| [
"Assuming you don't want to just write web form pages to do this, you might want to take a look at http://code.google.com/appengine/docs/python/tools/uploadingdata.html which explains a few different ways to import/export data from the appengine datastore.\n",
"You can use google app engine helper. Django cannot ... | [
0,
0
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0002656876_django_google_app_engine_python.txt |
Q:
Python/Urllib2/Threading: Single download thread faster than multiple download threads. Why?
i am working on a project that requires me to create multiple threads to download a large remote file. I have done this already but i cannot understand while it takes a longer amount of time to download a the file with multiple threads compared to using just a single thread. I used my xampp localhost to carry out the time elapsed test. I would like to know if its a normal behaviour or is it because i have not tried downloading from a real server.
Thanks
Kennedy
A:
9 women can't combine to make a baby in one month. If you have 10 threads, they each have only 10% the bandwidth of a single thread, and there is the additional overhead for context switching, etc.
A:
Python threading use something call the GIL (Golbal Interpreter Lock) that sometime degrade the programs execution time.
Without doing a lot of talk here i invite you to read this and this maybe it can help you to understand your problem, you can also see the two conference here and here.
Hope this can help :)
A:
Twisted uses non-blocking I/O, that means if data is not available on socket right now, doesn't block the entire thread, so you can handle many socket connections waiting for I/O in one thread simultaneous. But if doing something different than I/O (parsing large amounts of data) you still block the thread.
When you're using stdlib's socket module it does blocking I/O, that means when you're call socket.read and data is not available at the moment — it will block entire thread, so you need one thread per connection to handle concurrent download.
These are two approaches to concurrency:
Fork new thread for new connection (threading + socket from stdlib).
Multiplex I/O and handle may connections in one thread (Twisted).
| Python/Urllib2/Threading: Single download thread faster than multiple download threads. Why? | i am working on a project that requires me to create multiple threads to download a large remote file. I have done this already but i cannot understand while it takes a longer amount of time to download a the file with multiple threads compared to using just a single thread. I used my xampp localhost to carry out the time elapsed test. I would like to know if its a normal behaviour or is it because i have not tried downloading from a real server.
Thanks
Kennedy
| [
"9 women can't combine to make a baby in one month. If you have 10 threads, they each have only 10% the bandwidth of a single thread, and there is the additional overhead for context switching, etc. \n",
"Python threading use something call the GIL (Golbal Interpreter Lock) that sometime degrade the programs ex... | [
4,
1,
1
] | [] | [] | [
"download",
"multithreading",
"python",
"urllib2"
] | stackoverflow_0004219134_download_multithreading_python_urllib2.txt |
Q:
Python Program to use the resources of systems over internet?
i am fairly new to python , was wondering if i could remotely connect to another system over net , both the systems have different ISPs . can i write a program to connect to that system and use it resources , ofcourse with that systems permission.
PS: it kinda sounds like hacking into system without permission , but i have no intention of doing so .
A:
What you're describing sounds a lot like RPC (Remote Procedure Calls). Python has libraries that handle RPC using XML to pass parameters and results (which frees you from dealing with binary format issues), which are xmlrpclib on the client side and SimpleXMLRPCServer or DocXMLRPCServer on the server end.
It's only one solution out of many, but it can be a starting point.
A:
Also take a look at pyro
EDIT: I recommend you read about RPC and tell us is this what YOU want.
| Python Program to use the resources of systems over internet? | i am fairly new to python , was wondering if i could remotely connect to another system over net , both the systems have different ISPs . can i write a program to connect to that system and use it resources , ofcourse with that systems permission.
PS: it kinda sounds like hacking into system without permission , but i have no intention of doing so .
| [
"What you're describing sounds a lot like RPC (Remote Procedure Calls). Python has libraries that handle RPC using XML to pass parameters and results (which frees you from dealing with binary format issues), which are xmlrpclib on the client side and SimpleXMLRPCServer or DocXMLRPCServer on the server end.\nIt's on... | [
1,
0
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0004222595_networking_python.txt |
Q:
how stackless python can be fast for concurrency?
stackless python didn't take a good usage of multi-core, so where is the point it should be faster than python thread/multiprocessing ?
all the benchmark use stackless python tasklet to compare with python thread lock and queue, that's unfair, cause lock always has low efficiency
see, if use single thread function call without lock it should be as efficient as stackless python
A:
Focus on functionality first, and performance second (unless you know you have the need).
Most of the time on a server is spent with I/O, so multi-cores do not help so much. If it is mostly I/O that you are working with, multi-threading python may be the simplest answer.
If the server requests are CPU intensive, then having a parent process (be it multi-threaded or not), and respective child processes does make a good bit of sense.
If you really want to scale, you could look at a different platform, like Erlang. If you really want to scale and still use python, you could look at distributed erlang with Python processes managed as Erlang ports on a distributed cluster.
Lots of options, but unless you are dealing with someting big big, you could most likely take a simple approach.
release early, release often.
A:
There is this new and trendy thing called asynchronous-IO-loops and message-passing-concurrency and a few other trendy terms. Well, its not at all new, but it is only just these last 5 years being discovered by the mainstream.
Stackless Python is a version of Python where the VM has itself been modified to better support these message passing and IO loops, and its trick is green threading / coroutines.
There are other libraries for doing the same with different tools, e.g. Twisted and Tornado, on Python. You can even run hybrid Twisted on Stackless Python and so on.
The IO loop bit maps directly to how Berkley sockets do asynchronous IO, and with a bit of effort can be extended to be proactive rather than reactive and work with file systems as well as network sockets, e.g. the newest libevent.
To scale sideways to utilise more than one core is where you have two approaches - multithreading; shared state e.g. threads or between processes - multiprocessing e.g. message queues. It is a general limitation of current architectures that the threads approach works well for a large number of cores locally, whereas message passing overtakes performance-wise as the number of cores becomes massive or if those cores are on different machines. And you can make a hybrid approach.
Because of internal design choices in the Python VM, it is generally not as efficient at multi-threading as multi-processing, so you go to multiple processes with message passing sooner than you might on other platforms.
But generally the message passing approach is a cleaner, easily correct version.
And there are other languages that build on this same approach with different additional aims and constraints e.g. Erlang, node.js, Clojure, Go.
Of these, Clojure is perhaps the most informative. When you understand how Clojure ticks, and think through the whys, the whole aims and constraints of the other systems will fall into place...
| how stackless python can be fast for concurrency? | stackless python didn't take a good usage of multi-core, so where is the point it should be faster than python thread/multiprocessing ?
all the benchmark use stackless python tasklet to compare with python thread lock and queue, that's unfair, cause lock always has low efficiency
see, if use single thread function call without lock it should be as efficient as stackless python
| [
"Focus on functionality first, and performance second (unless you know you have the need). \nMost of the time on a server is spent with I/O, so multi-cores do not help so much. If it is mostly I/O that you are working with, multi-threading python may be the simplest answer. \nIf the server requests are CPU intens... | [
2,
0
] | [] | [] | [
"concurrency",
"python",
"python_stackless",
"stackless"
] | stackoverflow_0001854278_concurrency_python_python_stackless_stackless.txt |
Q:
Celery with non-homogenous tasks
I have two celery workers, worker 1 has tasks A and B, worker 2 with tasks A, B, and C. If I submit a task C, it doesn't seem to be executed in the celery worker that has task C; is there some way I can make sure that only worker 2 gets assigned tasks C?
A:
I'd take a look at routing tasks in the documentation. You can create queues with specific topics, and specify which worker(s) can handle which queue(s).
| Celery with non-homogenous tasks | I have two celery workers, worker 1 has tasks A and B, worker 2 with tasks A, B, and C. If I submit a task C, it doesn't seem to be executed in the celery worker that has task C; is there some way I can make sure that only worker 2 gets assigned tasks C?
| [
"I'd take a look at routing tasks in the documentation. You can create queues with specific topics, and specify which worker(s) can handle which queue(s).\n"
] | [
3
] | [] | [] | [
"celery",
"celery_task",
"python",
"task"
] | stackoverflow_0004222386_celery_celery_task_python_task.txt |
Q:
What are the first steps in order to start with Django/Python 2.7?
I have installed Python 2.7 for Windows, and downloaded Django-1.2.3. Now, I want to build my first website with them. How can I get to the first hello world page, in a browser? Can I use Apache/XAMPP to go to http://localhost ? What are the base principles to get a website working?
Thank you
A:
Just read the excellent and thorough Django tutorial. Django comes with a built-in simple web-server that you can run your websites on. It's just a Python script you run, and then you go to a port on localhost (by default port 8000). It's really quite simple and well-explained in the tutorial.
Specifically, look at the section named "The development server" in the page I linked to.
Personally I found this basic web-server to be very useful for all stages of website development.
A:
# django-admin.py startproject myone
# cd myone
# python manage.py runserver
| What are the first steps in order to start with Django/Python 2.7? | I have installed Python 2.7 for Windows, and downloaded Django-1.2.3. Now, I want to build my first website with them. How can I get to the first hello world page, in a browser? Can I use Apache/XAMPP to go to http://localhost ? What are the base principles to get a website working?
Thank you
| [
"Just read the excellent and thorough Django tutorial. Django comes with a built-in simple web-server that you can run your websites on. It's just a Python script you run, and then you go to a port on localhost (by default port 8000). It's really quite simple and well-explained in the tutorial.\nSpecifically, look ... | [
5,
0
] | [] | [] | [
"django",
"python",
"webserver"
] | stackoverflow_0004223070_django_python_webserver.txt |
Q:
Multi line log parsing for service times in PHP/Python
What's the best way to parse a multi line log file that require contextual knowledge from previous lines in php and/or python?
ex.
Date Time ID Call
1/1/10 00:00:00 1234 Start
1/1/10 00:00:01 1234 ServiceCall A Starts
1/1/10 00:00:05 1234 ServiceCall B Starts
1/1/10 00:00:06 1234 ServiceCall A Finishes
1/1/10 00:00:09 1234 ServiceCall B Finishes
1/1/10 00:00:10 1234 Stop
Each log line will have a unique id to bind it to a session but each consecutive set of lines is not guaranteed to be from the same session.
The ultimate goal is to find out how long each transaction took and how long each sub transaction took.
I'd love to use a library if one already exists.
A:
I can think of two different ways of doing this.
1) You can use a finite state machine to process the file line by line. When you hit a Start line, mark the time. When you hit a Stop line with the same ID, diff the time and report.
2) Use PHP's Perl-Compatible Regular Expressions with the m modifier to match all the text from each start/stop line set, then just look at the first and last lines of each match string returned.
In both cases, I would verify the IDs match to prevent against matching different sets.
A:
My first thought would be to create objects each time my parser encountered the start pattern with a new key. I'm assuming,from your example that 1234 is a key such that all log lines which must be correlated together can be mapped to the state of one "thing" (object).
So you see the pattern to start tracking one of these and every time you see a log entry that relates to it you call methods for the type of event (state change) that these subsequent lines represent.
From your example these "log state" objects (for lack of a more apropos term) might contain a list or dictionary (or other container) for each ServiceCall (which I would expect would be another class of objects).
So the overall design would be a parser/dispatcher that reads the log, if the log item relates to some existing object (key) then the item is dispatched to the object which
can then further create its own (ServiceCall or other) objects and/or dispatch events to those or raise exceptions or invoke callbacks or call outs to other functions as needed.
Presumably you also will need to have some collection or final disposition handler which could be called by your log objects when the Stop events are dispatched to them.
I'd guess you'd also want to support some sort or status reporting method so that the application can enumerate all live (uncollected) objects to in response to signals or commands in some other channel (perhaps from a non-blocking check performed by the parser/dispatcher)
A:
Here is a variation on a log parser I wrote a while ago, tailored to your log format. (The general approach tracks pretty closely with Jim Dennis's description, although I used a defaultdict of lists to accumulate all the entries for any given session.)
from pyparsing import Suppress,Word,nums,restOfLine
from datetime import datetime
from collections import defaultdict
def convertToDateTime(tokens):
month,day,year,hh,mm,ss = tokens
return datetime(year+2000, month, day, hh,mm,ss)
# define building blocks for parsing and processing log file entries
SLASH,COLON = map(Suppress,"/:")
integer = Word(nums).setParseAction(lambda t:int(t[0]))
date = integer + (SLASH + integer)*2
time = integer + (COLON + integer)*2
timestamp = date + time
timestamp.setParseAction(convertToDateTime)
# define format of a single line in the log file
logEntry = timestamp("timestamp") + integer("sessionid") + restOfLine("descr")
# summarize calls into single data structure
calls = defaultdict(list)
for logline in log:
entry = logEntry.parseString(logline)
calls[entry.sessionid].append(entry)
# first pass to find start/end time for each call
for sessionid in sorted(calls):
calldata = calls[sessionid]
print sessionid, calldata[-1].timestamp - calldata[0].timestamp
For your data, this prints out:
1234 0:00:10
You can process each session's list of entries with a similar approach to tease apart the sub-transactions.
| Multi line log parsing for service times in PHP/Python | What's the best way to parse a multi line log file that require contextual knowledge from previous lines in php and/or python?
ex.
Date Time ID Call
1/1/10 00:00:00 1234 Start
1/1/10 00:00:01 1234 ServiceCall A Starts
1/1/10 00:00:05 1234 ServiceCall B Starts
1/1/10 00:00:06 1234 ServiceCall A Finishes
1/1/10 00:00:09 1234 ServiceCall B Finishes
1/1/10 00:00:10 1234 Stop
Each log line will have a unique id to bind it to a session but each consecutive set of lines is not guaranteed to be from the same session.
The ultimate goal is to find out how long each transaction took and how long each sub transaction took.
I'd love to use a library if one already exists.
| [
"I can think of two different ways of doing this.\n1) You can use a finite state machine to process the file line by line. When you hit a Start line, mark the time. When you hit a Stop line with the same ID, diff the time and report.\n2) Use PHP's Perl-Compatible Regular Expressions with the m modifier to match a... | [
0,
0,
0
] | [] | [] | [
"multiline",
"php",
"python"
] | stackoverflow_0004221965_multiline_php_python.txt |
Q:
How to handle Out of memory with Python
I have huge dictionaries that I manipulate. More than 10 Million words are hashed. Its is too slow and some time it goes out of memory.
Is there a better way to handle these huge data structure ?
A:
Yes. It's called a database. Since a dictionary was working for you (aside from memory concerns) I would suppose that an sqlite database would work fine for you. You can use the sqlite3 quite easily and it is very well documented.
Of course this will only be a good solution if you can represent the values as something like json or are willing to trust pickled data from a local file. Maybe you should post details about what you have in the values of the dictionary. (I'm assuming the keys are words, if not please correct me)
You might also want to look at not generating the whole dictionary and only processing it in chunks. This may not be practical in your particular use case (It often isn't with the sort of thing that dictionaries are used for unfortunately) but if you can think of a way, it may be worth it to redesign your algorithm to allow it.
A:
I'm not sure what your words point to, but I guess they're quite big structures, if memory is an issue.
I did solve a Python MemoryError problem once by switching from Python 32 bits to Python 64 bits. In fact, some Python structures had become to large for the 4 GB address space. You might want to try that, as a simple potential solution to your problem.
| How to handle Out of memory with Python | I have huge dictionaries that I manipulate. More than 10 Million words are hashed. Its is too slow and some time it goes out of memory.
Is there a better way to handle these huge data structure ?
| [
"Yes. It's called a database. Since a dictionary was working for you (aside from memory concerns) I would suppose that an sqlite database would work fine for you. You can use the sqlite3 quite easily and it is very well documented.\nOf course this will only be a good solution if you can represent the values as some... | [
9,
1
] | [] | [] | [
"nlp",
"python"
] | stackoverflow_0004223130_nlp_python.txt |
Q:
Opencv + blobs in python
I need a bit of help with blobs in opencv (python).
This is the thing:
I've already written the preprocessing functions that work properly, they isolate the areas of interest and return a thresholded image, where these areas are white, the rest is black. The thing is, I'm only interested in the white areas but no matter what I do, I keep getting the background as a blob too.
I can't filter by size because I don't know how far the object is.
Is there a way to just process white blobs?
This is the gist of what i have now:
mask = cv.cvCreateImage(frame_size,8,1)
cvSet(mask,1)
.
.
.
blob_a_matches = CBlobResult(blob_a,mask,100, True)
blob_a_matches.filter_blobs(10, 1000)
for i in range(blob_a_matches.GetNumBlobs()):
numbered_blob = blob_a_matches.GetBlob(i)
area = numbered_blob.Area()
.
.
.
Except for the fact that the background is treated as a blob too, this works.
A:
CvSet is a class - so not sure what second line is doing. Also no Blobs as native in Python - is this a cv.CvSet or a cv.CvSeq sequence that is being returned ?
or are you finding contours after thresholding - then traversing them as in contours.py example ? which may be a better approach...
| Opencv + blobs in python | I need a bit of help with blobs in opencv (python).
This is the thing:
I've already written the preprocessing functions that work properly, they isolate the areas of interest and return a thresholded image, where these areas are white, the rest is black. The thing is, I'm only interested in the white areas but no matter what I do, I keep getting the background as a blob too.
I can't filter by size because I don't know how far the object is.
Is there a way to just process white blobs?
This is the gist of what i have now:
mask = cv.cvCreateImage(frame_size,8,1)
cvSet(mask,1)
.
.
.
blob_a_matches = CBlobResult(blob_a,mask,100, True)
blob_a_matches.filter_blobs(10, 1000)
for i in range(blob_a_matches.GetNumBlobs()):
numbered_blob = blob_a_matches.GetBlob(i)
area = numbered_blob.Area()
.
.
.
Except for the fact that the background is treated as a blob too, this works.
| [
"CvSet is a class - so not sure what second line is doing. Also no Blobs as native in Python - is this a cv.CvSet or a cv.CvSeq sequence that is being returned ?\nor are you finding contours after thresholding - then traversing them as in contours.py example ? which may be a better approach...\n"
] | [
0
] | [] | [] | [
"blobs",
"opencv",
"python"
] | stackoverflow_0004197242_blobs_opencv_python.txt |
Q:
Which registry / environment (or other) settings does urllib2.urlopen use to determine proxy settings?
Following on from this question: What is causing urllib2.urlopen() to connect via proxy?
I'd like to know which operating system & environmental settings can affect urllib2.urlopen?
For example, I've noticed that on some machines within our very large corporation urllib2.urlopen insists on connecting via a proxy. This is a problem because the resources our application needs to connect to are on the local network, and so adding the proxy to the mix causes authentication problems.
I'm using Windows 32bit XP / Python 2.4.4
A:
You can see the exact code, but as the docs say the registry section is Internet Settings:
HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings
| Which registry / environment (or other) settings does urllib2.urlopen use to determine proxy settings? | Following on from this question: What is causing urllib2.urlopen() to connect via proxy?
I'd like to know which operating system & environmental settings can affect urllib2.urlopen?
For example, I've noticed that on some machines within our very large corporation urllib2.urlopen insists on connecting via a proxy. This is a problem because the resources our application needs to connect to are on the local network, and so adding the proxy to the mix causes authentication problems.
I'm using Windows 32bit XP / Python 2.4.4
| [
"You can see the exact code, but as the docs say the registry section is Internet Settings:\nHKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\n\n"
] | [
2
] | [] | [] | [
"networking",
"python",
"urllib2",
"urlopen"
] | stackoverflow_0004223801_networking_python_urllib2_urlopen.txt |
Q:
django and csrf_token problem
I have a little problem with the token in django.
When I write a POST form and add {{csrf_token}}, when I submit it the token is checked .
But when I send a POST request (in ajax) and add the paramater manually csrfmiddlewaretoken , the token is not checked.
But I don't know why ?
Thanks.
A:
AJAX requests are not checked for CSRF: the browser's same origin policy means that CSRF attacks are much harder. See the explanation in the docs.
| django and csrf_token problem | I have a little problem with the token in django.
When I write a POST form and add {{csrf_token}}, when I submit it the token is checked .
But when I send a POST request (in ajax) and add the paramater manually csrfmiddlewaretoken , the token is not checked.
But I don't know why ?
Thanks.
| [
"AJAX requests are not checked for CSRF: the browser's same origin policy means that CSRF attacks are much harder. See the explanation in the docs.\n"
] | [
6
] | [] | [] | [
"django",
"python",
"token"
] | stackoverflow_0004223719_django_python_token.txt |
Q:
Django: When doing an include of URL's, should I specify project.app or just app
When including an app's URL's in the project's urls.py, my coding partner does it this way:
('^stops/', include('stops.urls'))
However, Django documentation specifies the following syntax:
('^clients/', include('project_name.app_name.urls'))
His way has worked. Is there a reason to specify the project name at all?
A:
It depends on your PYTHONPATH setting and the structure of your projects and apps.
We have many, many projects. Each with several apps. All are on our PYTHONPATH, so the project name is essential.
If you have only one project, and the top-level project directory is on your PYTHONPATH, then each app can be resolved separately and you can't use the project name.
A:
It also depends upon if the app is inside your project, or a reusable one.
I have a fresh virtualenv for every project, and use a separate mercurial repository for each app. These are then installed into the system path (either in editable form for development, or in non-editable form for deployment), meaning I have <appname> on the PYTHONPATH.
A:
if on the shell you run
import this
you will see that there is a zen of python ''explicit is better than implicit'' hence thats the reason to specify the project name.
| Django: When doing an include of URL's, should I specify project.app or just app | When including an app's URL's in the project's urls.py, my coding partner does it this way:
('^stops/', include('stops.urls'))
However, Django documentation specifies the following syntax:
('^clients/', include('project_name.app_name.urls'))
His way has worked. Is there a reason to specify the project name at all?
| [
"It depends on your PYTHONPATH setting and the structure of your projects and apps.\nWe have many, many projects. Each with several apps. All are on our PYTHONPATH, so the project name is essential.\nIf you have only one project, and the top-level project directory is on your PYTHONPATH, then each app can be reso... | [
2,
1,
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0004221070_django_django_urls_python.txt |
Q:
Any reason there are no returned value from set.add
Current, since the returned value from set.add is always None. I have to do the following.
if 1 in s:
print 'already found'
return
s.add(1)
Would it be nice if I can
if not s.add(1):
print 'already found'
return
A:
>>> None == False
False
>>> None == True
False
>>> None == None
True
>>> not None
True
If s.add always returns None, then your condition will always be True. But since s is a set, just add the value to it. You can't have duplicate values in a set, by definition :
>>> a = set()
>>> a.add(1)
>>> a
{1}
>>> a.add(1)
>>> a
{1}
If you just want to know if 1 is in the set, then do if 1 in s.
A:
Any reason there are no returned value from set.add
Yes.
The reason is that collection mutators, like set.add(), list.append(), etc., never return a value.
If a method mutates and object, it does not return a value. That's the rule.
There are minor exceptions, like pop.
| Any reason there are no returned value from set.add | Current, since the returned value from set.add is always None. I have to do the following.
if 1 in s:
print 'already found'
return
s.add(1)
Would it be nice if I can
if not s.add(1):
print 'already found'
return
| [
">>> None == False\nFalse\n>>> None == True\nFalse\n>>> None == None\nTrue\n>>> not None\nTrue\n\nIf s.add always returns None, then your condition will always be True. But since s is a set, just add the value to it. You can't have duplicate values in a set, by definition :\n>>> a = set()\n>>> a.add(1)\n>>> a\n{1}\... | [
7,
4
] | [] | [] | [
"python"
] | stackoverflow_0004221968_python.txt |
Q:
Python interpreter embedded in the application fails to load native modules
I have an application that statically links to libpython.a (2.7). From within the application's interpreter I try importing time module (time.so), which fails with:
ImportError: ./time.so: undefined symbol: PyExc_IOError
So, this module has unresolved symbols:
nm -D time.so | grep PyExc_IOError
U PyExc_IOError
I figured that this symbol is discarded by the linker when linking the application. OK, I'm now linking libpython with all symbols:
... -Wl,-whole-archive -lpython -Wl,-no-whole-archive ...
The symbol is now there:
$ nm app | grep PyExc_IOError
8638348 D PyExc_IOError
08638ca0 d _PyExc_IOError
But I still get the same import error. Where is the problem?
A:
Besides making sure all of libpython is included in your binary, you also need to make sure the symbols in the library are exposed to shared objects being loaded. When you're linking libpython (statically) into your main binary this means you need the --export-dynamic linker argument (so -Wl,--export-dynamic or -Xlinker --export-dynamic as the gcc argument.) When loading a shared object with libpython (say, when you embed libpython into a plugin for your app) this means you have to make sure the shared object is loaded with the RTLD_GLOBAL flag to dlopen().
| Python interpreter embedded in the application fails to load native modules | I have an application that statically links to libpython.a (2.7). From within the application's interpreter I try importing time module (time.so), which fails with:
ImportError: ./time.so: undefined symbol: PyExc_IOError
So, this module has unresolved symbols:
nm -D time.so | grep PyExc_IOError
U PyExc_IOError
I figured that this symbol is discarded by the linker when linking the application. OK, I'm now linking libpython with all symbols:
... -Wl,-whole-archive -lpython -Wl,-no-whole-archive ...
The symbol is now there:
$ nm app | grep PyExc_IOError
8638348 D PyExc_IOError
08638ca0 d _PyExc_IOError
But I still get the same import error. Where is the problem?
| [
"Besides making sure all of libpython is included in your binary, you also need to make sure the symbols in the library are exposed to shared objects being loaded. When you're linking libpython (statically) into your main binary this means you need the --export-dynamic linker argument (so -Wl,--export-dynamic or -X... | [
2
] | [] | [] | [
"c",
"linux",
"python"
] | stackoverflow_0004223312_c_linux_python.txt |
Q:
calling a function from dll in python
I am trying to make a call from python to a dll but am getting an access violation.Can some please tell me how to use ctypes correctly in the following code. GetItems is supposed return a struct that looks like this
struct ITEM
{
unsigned short id;
unsigned char i;
unsigned int c;
unsigned int f;
unsigned int p;
unsigned short e;
};
I'm really only interested in getting the id, do not need the other fields. I have my code listed below, what am i doing wrong? Thanks for the help.
import psutil
from ctypes import *
def _get_pid():
pid = -1
for p in psutil.process_iter():
if p.name == 'myApp.exe':
return p.pid
return pid
class MyDLL(object):
def __init__(self):
self._dll = cdll.LoadLibrary('MYDLL.dll')
self.instance = self._dll.CreateInstance(_get_pid())
@property
def access(self):
return self._dll.Access(self.instance)
def get_inventory_item(self, index):
return self._dll.GetItem(self.instance, index)
if __name__ == '__main__':
myDLL = MyDLL()
myDll.get_item(5)
A:
First off, you're calling get_item, while your class only has get_inventory_item defined, and you're discarding the result, and capitalization of myDLL is inconsistent.
You need to define a Ctypes type for your struct, like this:
class ITEM(ctypes.Structure):
_fields_ = [("id", c_ushort),
("i", c_uchar),
("c", c_uint),
("f", c_uint),
("p", c_uint),
("e", c_ushort)]
(see http://docs.python.org/library/ctypes.html#structured-data-types )
Then specify that the function type is ITEM:
myDLL.get_item.restype = ITEM
(see http://docs.python.org/library/ctypes.html#return-types )
Now you should be able to call the function and it should return an object with members of the struct as attributes.
| calling a function from dll in python | I am trying to make a call from python to a dll but am getting an access violation.Can some please tell me how to use ctypes correctly in the following code. GetItems is supposed return a struct that looks like this
struct ITEM
{
unsigned short id;
unsigned char i;
unsigned int c;
unsigned int f;
unsigned int p;
unsigned short e;
};
I'm really only interested in getting the id, do not need the other fields. I have my code listed below, what am i doing wrong? Thanks for the help.
import psutil
from ctypes import *
def _get_pid():
pid = -1
for p in psutil.process_iter():
if p.name == 'myApp.exe':
return p.pid
return pid
class MyDLL(object):
def __init__(self):
self._dll = cdll.LoadLibrary('MYDLL.dll')
self.instance = self._dll.CreateInstance(_get_pid())
@property
def access(self):
return self._dll.Access(self.instance)
def get_inventory_item(self, index):
return self._dll.GetItem(self.instance, index)
if __name__ == '__main__':
myDLL = MyDLL()
myDll.get_item(5)
| [
"First off, you're calling get_item, while your class only has get_inventory_item defined, and you're discarding the result, and capitalization of myDLL is inconsistent.\nYou need to define a Ctypes type for your struct, like this:\nclass ITEM(ctypes.Structure):\n _fields_ = [(\"id\", c_ushort),\n ... | [
0
] | [] | [] | [
"ctypes",
"dll",
"python"
] | stackoverflow_0004224331_ctypes_dll_python.txt |
Q:
Implementing sub-table (view into a table): designing class relationship
I'm using Python 3, but the question isn't really tied to the specific language.
I have class Table that implements a table with a primary key. An instance of that class contains the actual data (which is very large).
I want to allow users to create a sub-table by providing a filter for the rows of the Table. I don't want to copy the table, so I was planning to keep in the sub-table just the subset of the primary keys from the parent table.
Obviously, the sub-table is just a view into the parent table; it will change if the parent table changes, will become invalid if the parent table is destroyed, and will lose some of its rows if they are deleted from the parent table. [EDIT: to clarify, if parent table is changed, I don't care what happens to the sub-table; any behavior is fine.]
How should I connect the two classes? I was thinking of:
class Subtable(Table):
def __init__(self, table, filter_function):
# ...
My assumption was that Subtable keeps the interface of Table, except slightly overrides the inherited methods just to check if the row is in. Is this a good implementation?
The problem is, I'm not sure how to initialize the Subtable instance given that I don't want to copy the table object passed to it. Is it even possible?
Also I was thinking to give class Table an instance method that returns Subtable instance; but that creates a dependency of Table on Subtable, and I guess it's better to avoid?
A:
I'm going to use the following (I omitted many methods such as sort, which work quite well in this arrangement; also omitted error handling):
class Table:
def __init__(self, *columns, pkey = None):
self.pkey = pkey
self.__columns = columns
self.__data = {}
def __contains__(self, key):
return key in self.__data
def __iter__(self):
for key in self.__order:
yield key
def __len__(self):
return len(self.__data)
def items(self):
for key in self.__order:
yield key, self.__data[key]
def insert(self, *unnamed, **named):
if len(unnamed) > 0:
row_dict = {}
for column_id, column in enumerate(self.__columns):
row_dict[column] = unnamed[column_id]
else:
row_dict = named
key = row_dict[self.pkey]
self.__data[key] = row_dict
class Subtable(Table):
def __init__(self, table, row_filter):
self.__order = []
self.__data = {}
for key, row in table.items():
if row_filter(row):
self.__data[key] = row
Essentially, I'm copying the primary keys only, and create references to the data tied to them. If a row in the parent table is destroyed, it will still exist in the sub-table. If a row is modified in the parent table, it is also modified in the sub-table. This is fine, since my requirements was "anything goes when parent table is modified".
If you see any issues with this design, let me know please.
| Implementing sub-table (view into a table): designing class relationship | I'm using Python 3, but the question isn't really tied to the specific language.
I have class Table that implements a table with a primary key. An instance of that class contains the actual data (which is very large).
I want to allow users to create a sub-table by providing a filter for the rows of the Table. I don't want to copy the table, so I was planning to keep in the sub-table just the subset of the primary keys from the parent table.
Obviously, the sub-table is just a view into the parent table; it will change if the parent table changes, will become invalid if the parent table is destroyed, and will lose some of its rows if they are deleted from the parent table. [EDIT: to clarify, if parent table is changed, I don't care what happens to the sub-table; any behavior is fine.]
How should I connect the two classes? I was thinking of:
class Subtable(Table):
def __init__(self, table, filter_function):
# ...
My assumption was that Subtable keeps the interface of Table, except slightly overrides the inherited methods just to check if the row is in. Is this a good implementation?
The problem is, I'm not sure how to initialize the Subtable instance given that I don't want to copy the table object passed to it. Is it even possible?
Also I was thinking to give class Table an instance method that returns Subtable instance; but that creates a dependency of Table on Subtable, and I guess it's better to avoid?
| [
"I'm going to use the following (I omitted many methods such as sort, which work quite well in this arrangement; also omitted error handling):\nclass Table:\n def __init__(self, *columns, pkey = None):\n self.pkey = pkey\n self.__columns = columns\n self.__data = {}\n\n def __contains__(s... | [
1
] | [] | [] | [
"data_structures",
"design_patterns",
"oop",
"python",
"python_3.x"
] | stackoverflow_0004219032_data_structures_design_patterns_oop_python_python_3.x.txt |
Q:
Python libxml2 parsing xml having Chinese characters
i encountered encoding problems when using libxml2 in python to parse Chinese charactors
# coding=utf8
import libxml2
def output(data):
doc = libxml2.parseMemory(data, len(data))
ctxt = doc.xpathNewContext()
res_rslt = ctxt.xpathEval("/r/e/attribute::Name")
print res_rslt[0]
data = '''<r><e RoleID="3247" Name="中文"></e></r>'''
output(data)
the out put is
Name="中文"
while i'm expecting
Name="中文"
how could i make it?
A:
With lxml, things are easier and they work. It is Pythonic binding for the libxml2 library and works wonderfully.
>>> from lxml import etree
>>> x = etree.fromstring('''<r><e RoleID="3247" Name="中文"></e></r>''')
>>> name = x[0].get('Name')
>>> print name
中文
And yes, XPath is also supported. The documentation is here.
As for your program, have a look at this:
# -*- coding: utf-8 -*-
import libxml2
def output(data):
doc = libxml2.parseDoc(data)
ctxt = doc.xpathNewContext()
res_rslt = ctxt.xpathEval("/r/e/attribute::Name")
return res_rslt[0]
data = u'''<?xml version="1.0" encoding="UTF-8"?><r><e RoleID="3247" Name="中文"></e></r>'''.encode("UTF-8")
print output(data)
A:
My answer to these sorts of things always seems to be "use Beautiful Soup". And I always get upvoted for it, too (which shows, I think, that others agree with me that it's good).
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup(u'''<r><e RoleID="3247" Name="中文"></e></r>''')
>>> print soup.r.e['name']
中文
The thing is that libxml2 is converting those characters into the proper XML entities which for XML is correct. Beautiful Soup doesn't have any such notions of feeling a need to be correct - so it just gives you what you want.
(Note in this case that using either u'...' or '...' will work; I just put it as a unicode because it feels better that way - whatever you do, Beautiful Soup gives you Unicode.)
| Python libxml2 parsing xml having Chinese characters | i encountered encoding problems when using libxml2 in python to parse Chinese charactors
# coding=utf8
import libxml2
def output(data):
doc = libxml2.parseMemory(data, len(data))
ctxt = doc.xpathNewContext()
res_rslt = ctxt.xpathEval("/r/e/attribute::Name")
print res_rslt[0]
data = '''<r><e RoleID="3247" Name="中文"></e></r>'''
output(data)
the out put is
Name="中文"
while i'm expecting
Name="中文"
how could i make it?
| [
"With lxml, things are easier and they work. It is Pythonic binding for the libxml2 library and works wonderfully.\n>>> from lxml import etree\n>>> x = etree.fromstring('''<r><e RoleID=\"3247\" Name=\"中文\"></e></r>''')\n>>> name = x[0].get('Name')\n>>> print name\n中文\n\nAnd yes, XPath is also supported. The documen... | [
2,
0
] | [] | [] | [
"encoding",
"libxml2",
"python",
"utf_8"
] | stackoverflow_0004225045_encoding_libxml2_python_utf_8.txt |
Q:
How to insert a string(Fri Nov 19 16:23:54 +0800 2010) into a table field whose type is TIMESTAMP?
I'm using Python and MYSQLdb to connect to Mysql.
and now i need to insert a string "Fri Nov 19 16:23:54 +0800 2010" into a field, how can i do?
A:
You can parse that sting with Python time.strptime() method and then convert it to string required by MySQL using strftime(). Unfortunately my Python 2.6 cannot handle %z directive, but you can check on your implementation that code:
import datetime
def test_dt(d, f):
dt = datetime.datetime.strptime(d, f)
print('%s -> %s' % (d, dt.strftime('%Y-%m-%d %H:%M:%S %Z')))
print('-' * 10)
test_dt('Fri Nov 19 16:23:54 2010', '%a %b %d %H:%M:%S %Y')
test_dt('Fri Nov 19 16:23:54 +8000 2010', '%a %b %d %H:%M:%S %z %Y')
If it fails with %z then think if you need that time zone, or if you can remove it from string and apply it to dt object other way.
It seems that %z issue was reported and solved: http://bugs.python.org/issue6641
| How to insert a string(Fri Nov 19 16:23:54 +0800 2010) into a table field whose type is TIMESTAMP? | I'm using Python and MYSQLdb to connect to Mysql.
and now i need to insert a string "Fri Nov 19 16:23:54 +0800 2010" into a field, how can i do?
| [
"You can parse that sting with Python time.strptime() method and then convert it to string required by MySQL using strftime(). Unfortunately my Python 2.6 cannot handle %z directive, but you can check on your implementation that code:\nimport datetime\n\ndef test_dt(d, f):\n dt = datetime.datetime.strptime(d, f)... | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004224710_mysql_python.txt |
Q:
Adding column In table with Python
Im trying to create a logging output using python 2.6.
The data come a database. What I would like to do is add a column to all rows with a time stamp = strftime("%Y-%m-%d %H:%M:%S"). There are about 50 rows.
Then drop into a csv table.
.append and .extend seem to add rows but not columns. Is there an easy way to do this?
Should I splice data to add col?
A:
A quick example:
If you have a two-dimensional list like
l = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
then l.append(13) gets you
l = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
13]
which I assume is what you mean by "it adds rows, not columns".
You probably want l[0].append(13) which gives you
[[1,2,3,4,13],
[5,6,7,8],
[9,10,11,12]]
If you want to do this for all rows, you could use
for row in l:
row.append(13)
giving you
[[1, 2, 3, 4, 13],
[5, 6, 7, 8, 13],
[9, 10, 11, 12, 13]]
Of course, in your case you will want to add the timestamp instead of 13, but the principle is the same. And then it's trivial to convert the 2D list into a csv object.
| Adding column In table with Python | Im trying to create a logging output using python 2.6.
The data come a database. What I would like to do is add a column to all rows with a time stamp = strftime("%Y-%m-%d %H:%M:%S"). There are about 50 rows.
Then drop into a csv table.
.append and .extend seem to add rows but not columns. Is there an easy way to do this?
Should I splice data to add col?
| [
"A quick example:\nIf you have a two-dimensional list like\nl = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12]]\n\nthen l.append(13) gets you\nl = [[1,2,3,4],\n [5,6,7,8],\n [9,10,11,12],\n 13]\n\nwhich I assume is what you mean by \"it adds rows, not columns\".\nYou probably want l[0].append(13) which... | [
4
] | [] | [] | [
"logging",
"python"
] | stackoverflow_0004225358_logging_python.txt |
Q:
container where values expire in python
I am after a thread safe Python container where the values are automatically removed after a time. Does such a class exist?
A:
Here is a thread safe version of ExpireCounter:
import datetime
import collections
import threading
class ExpireCounter:
"""Tracks how many events were added in the preceding time period
"""
def __init__(self, timeout=1):
self.lock=threading.Lock()
self.timeout = timeout
self.events = collections.deque()
def add(self,item):
"""Add event time
"""
with self.lock:
self.events.append(item)
threading.Timer(self.timeout,self.expire).start()
def __len__(self):
"""Return number of active events
"""
with self.lock:
return len(self.events)
def expire(self):
"""Remove any expired events
"""
with self.lock:
self.events.popleft()
def __str__(self):
with self.lock:
return str(self.events)
which can be used like this:
import time
c = ExpireCounter()
assert(len(c) == 0)
print(c)
# deque([])
c.add(datetime.datetime.now())
time.sleep(0.75)
c.add(datetime.datetime.now())
assert(len(c) == 2)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 91426), datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])
time.sleep(0.75)
assert(len(c) == 1)
print(c)
# deque([datetime.datetime(2010, 11, 19, 8, 50, 0, 842715)])
A:
Perhaps you want an LRU cache. Here's one I've been meaning to try out:
http://pypi.python.org/pypi/repoze.lru
It seems to be thread safe.
A:
This is more or less what I want for now:
from datetime import datetime, timedelta
from collections import deque
class ExpireCounter:
"""Tracks how many events were added in the preceding time period
"""
def __init__(self, timeout=timedelta(seconds=1)):
self.timeout = timeout
self.events = deque()
def add(self):
"""Add event time
"""
self.events.append(datetime.now())
def __len__(self):
"""Return number of active events
"""
self.expire()
return len(self.events)
def expire(self):
"""Remove any expired events
"""
now = datetime.now()
try:
while self.events[0] + self.timeout < now:
self.events.popleft()
except IndexError:
pass # no more events
if __name__ == '__main__':
import time
c = ExpireCounter()
assert(len(c) == 0)
c.inc()
time.sleep(0.75)
c.inc()
assert(len(c) == 2)
time.sleep(0.75)
assert(len(c) == 1)
| container where values expire in python | I am after a thread safe Python container where the values are automatically removed after a time. Does such a class exist?
| [
"Here is a thread safe version of ExpireCounter:\nimport datetime\nimport collections\nimport threading\n\nclass ExpireCounter:\n \"\"\"Tracks how many events were added in the preceding time period\n \"\"\"\n\n def __init__(self, timeout=1):\n self.lock=threading.Lock() \n self.timeou... | [
8,
0,
0
] | [] | [] | [
"containers",
"multithreading",
"python",
"timeout"
] | stackoverflow_0004219843_containers_multithreading_python_timeout.txt |
Q:
python tcp socketserver and the differences between windows and unix clients
I feel this is a very basic question, but my google-fu is not yielding any specific hits. My problem is related to socket communication differences between windows and unix tcp clients. If i serve up the very basic tcp server code below, and establish a connection via bsd/macos/linux via telnet or netcat (eg telnet remotehost 9997), i am able to enter a line of text, followed by a new-line (\r\n), and the server responds.
When i establish a connection from a windows XP client, via the telnet application (or putty using telnet), i am able to connect, but can only type a single character before the service returns the response. I realize the windows vs unix network stacks handle sockets differently, but the odd bit is, that from my packet capture, i do not see the windows client adding a carriage return .
sample code :
import SocketServer as socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.request.send("Welcome\r\n")
self.data = self.request.recv(1024).strip()
print("%s wrote:" % self.client_address[0])
print(self.data)
self.request.send(self.data.upper())
if __name__ == "__main__":
server = socketserver.TCPServer(('', 9997), MyTCPHandler)
server.serve_forever()
Here is a packet capture on the server side when connecting from a windows client. 0x62 (b) is the character i typed, during my attempt to type : blah
0000 00 00 00 01 00 06 00 23 33 74 d5 3f 00 00 08 00 .......# 3t.?....
0010 45 00 00 35 77 86 40 00 3c 06 02 5a 0a 0e 14 29 E..5w.@. <..Z...)
0020 0a 03 9c a9 c6 0e 27 0d 20 ed 36 de 87 f2 30 a2 ......'. .6...0.
0030 80 18 ff ff 48 ee 00 00 01 01 08 0a 08 00 46 01 ....H... ......F.
0040 94 f6 26 6f 62 ..&ob
The server responds with 0x42 (B)
0000 00 04 00 01 00 06 00 50 56 86 1a 4e 00 00 08 00 .......P V..N....
0010 45 00 00 35 16 fd 40 00 40 06 5e e3 0a 03 9c a9 E..5..@. @.^.....
0020 0a 0e 14 29 27 0d c6 0e 87 f2 30 a2 20 ed 36 df ...)'... ..0. .6.
0030 80 18 00 b5 c5 0a 00 00 01 01 08 0a 94 f6 29 a0 ........ ......).
0040 08 00 46 01 42 ..F.B
Here is the packet dump from a unix client (netcat remotehost 9997), i enter the letter t (0x74), and and required to forcefully hit the carriage return which generates the 0x0d0a.
0000 00 00 00 01 00 06 00 23 33 74 d5 3f 00 00 08 00 .......# 3t.?....
0010 45 00 00 37 ee d2 40 00 3c 06 8b 0b 0a 0e 14 29 E..7..@. <......)
0020 0a 03 9c a9 c6 10 27 0d 69 ac 8e d6 b8 7b 92 b4 ......'. i....{..
0030 80 18 ff ff c4 b1 00 00 01 01 08 0a 08 00 48 1d ........ ......H.
0040 94 f6 59 2b 74 0d 0a ..Y+t..
So my question is, how can i get this socket server to work with windows clients? Or what do i change in the windows environment, that will allow me to pass a string of characters.
A:
It works as expected (programs don't do what we wanted, they do what we told them to do). If your question is how to make windows XP telnet send CRLF, you can set the appropriate option:
telnet
set ?
set crlf
open <host> <port>
But I think you should re-consider your code, because the server doesn't read a line, it tries to read 1024 bytes.
This is helpful.
| python tcp socketserver and the differences between windows and unix clients | I feel this is a very basic question, but my google-fu is not yielding any specific hits. My problem is related to socket communication differences between windows and unix tcp clients. If i serve up the very basic tcp server code below, and establish a connection via bsd/macos/linux via telnet or netcat (eg telnet remotehost 9997), i am able to enter a line of text, followed by a new-line (\r\n), and the server responds.
When i establish a connection from a windows XP client, via the telnet application (or putty using telnet), i am able to connect, but can only type a single character before the service returns the response. I realize the windows vs unix network stacks handle sockets differently, but the odd bit is, that from my packet capture, i do not see the windows client adding a carriage return .
sample code :
import SocketServer as socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.request.send("Welcome\r\n")
self.data = self.request.recv(1024).strip()
print("%s wrote:" % self.client_address[0])
print(self.data)
self.request.send(self.data.upper())
if __name__ == "__main__":
server = socketserver.TCPServer(('', 9997), MyTCPHandler)
server.serve_forever()
Here is a packet capture on the server side when connecting from a windows client. 0x62 (b) is the character i typed, during my attempt to type : blah
0000 00 00 00 01 00 06 00 23 33 74 d5 3f 00 00 08 00 .......# 3t.?....
0010 45 00 00 35 77 86 40 00 3c 06 02 5a 0a 0e 14 29 E..5w.@. <..Z...)
0020 0a 03 9c a9 c6 0e 27 0d 20 ed 36 de 87 f2 30 a2 ......'. .6...0.
0030 80 18 ff ff 48 ee 00 00 01 01 08 0a 08 00 46 01 ....H... ......F.
0040 94 f6 26 6f 62 ..&ob
The server responds with 0x42 (B)
0000 00 04 00 01 00 06 00 50 56 86 1a 4e 00 00 08 00 .......P V..N....
0010 45 00 00 35 16 fd 40 00 40 06 5e e3 0a 03 9c a9 E..5..@. @.^.....
0020 0a 0e 14 29 27 0d c6 0e 87 f2 30 a2 20 ed 36 df ...)'... ..0. .6.
0030 80 18 00 b5 c5 0a 00 00 01 01 08 0a 94 f6 29 a0 ........ ......).
0040 08 00 46 01 42 ..F.B
Here is the packet dump from a unix client (netcat remotehost 9997), i enter the letter t (0x74), and and required to forcefully hit the carriage return which generates the 0x0d0a.
0000 00 00 00 01 00 06 00 23 33 74 d5 3f 00 00 08 00 .......# 3t.?....
0010 45 00 00 37 ee d2 40 00 3c 06 8b 0b 0a 0e 14 29 E..7..@. <......)
0020 0a 03 9c a9 c6 10 27 0d 69 ac 8e d6 b8 7b 92 b4 ......'. i....{..
0030 80 18 ff ff c4 b1 00 00 01 01 08 0a 08 00 48 1d ........ ......H.
0040 94 f6 59 2b 74 0d 0a ..Y+t..
So my question is, how can i get this socket server to work with windows clients? Or what do i change in the windows environment, that will allow me to pass a string of characters.
| [
"It works as expected (programs don't do what we wanted, they do what we told them to do). If your question is how to make windows XP telnet send CRLF, you can set the appropriate option:\ntelnet\nset ?\nset crlf\nopen <host> <port>\n\nBut I think you should re-consider your code, because the server doesn't read a ... | [
1
] | [] | [] | [
"client",
"python",
"socketserver",
"tcp"
] | stackoverflow_0004225426_client_python_socketserver_tcp.txt |
Q:
Why can I update a list slice but not a string slice in python?
Just curious more than anything why python will allow me to update a slice of a list but not a string?
>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"
>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]
Is there a good reason for this? (I am sure there is.)
A:
Because in python, strings are immutable.
A:
Python distinguishes mutable and immutable data types. Making strings immutable is a general design decision in Python. Integers are immutable, you can't change the value of 42. Strings are also considered values in Python, so you can't change "fourty-two" to something else.
This design decision allows for several optimisations. For example, if a string operation does not change the value of a string, CPython usually simply returns the original string. If strings were mutable, it would always be necessary to make a copy.
| Why can I update a list slice but not a string slice in python? | Just curious more than anything why python will allow me to update a slice of a list but not a string?
>>> s = "abc"
>>> s[1:2]
'b'
>>> s[1:3]
'bc'
>>> s[1:3] = "aa"
>>> l = [1,2,3]
>>> l[1:3]
[2, 3]
>>> l[1:3] = [9,0]
>>> l
[1, 9, 0]
Is there a good reason for this? (I am sure there is.)
| [
"Because in python, strings are immutable.\n",
"Python distinguishes mutable and immutable data types. Making strings immutable is a general design decision in Python. Integers are immutable, you can't change the value of 42. Strings are also considered values in Python, so you can't change \"fourty-two\" to s... | [
9,
5
] | [] | [] | [
"python",
"slice",
"string"
] | stackoverflow_0004225743_python_slice_string.txt |
Q:
Long integer to 16 character Hex for Google Reader sync
Python Code
h = "%s"%("0000000000000000%x"%(i&0xffffffffffffffff))[16:]
I'd like to know how this would be done in PHP.
The application is for google reader syncronization.
An initial sync list comes with numeric values, but the actual article id hex.
Example Long Integer = 8643979098044673995
Example Google Reader Article ID = tag:google.com,2005:reader/item/77f5953120daafcb
A:
sprintf("%016x", 8643979098044673995);
| Long integer to 16 character Hex for Google Reader sync | Python Code
h = "%s"%("0000000000000000%x"%(i&0xffffffffffffffff))[16:]
I'd like to know how this would be done in PHP.
The application is for google reader syncronization.
An initial sync list comes with numeric values, but the actual article id hex.
Example Long Integer = 8643979098044673995
Example Google Reader Article ID = tag:google.com,2005:reader/item/77f5953120daafcb
| [
"sprintf(\"%016x\", 8643979098044673995);\n\n"
] | [
2
] | [] | [] | [
"php",
"python"
] | stackoverflow_0004225926_php_python.txt |
Q:
Twisted, FTP, and "streaming" large files
I'm attempting to implement what can best be described as "an FTP interface to an HTTP API". Essentially, there is an existing REST API that can be used to manage a user's files for a site, and I'm building a mediator server that re-exposes this API as an FTP server. So you can login with, say, Filezilla and list your files, upload new ones, delete old ones, etc.
I'm attempting this with twisted.protocols.ftp for the (FTP) server, and twisted.web.client for the (HTTP) client.
The thing I'm running up against is, when a user tries to download a file, "streaming" that file from an HTTP response to my FTP response. Similar for uploading.
The most straightforward approach would be to download the entire file from the HTTP server, then turn around and send the contents to the user. The problem with this is that any given file could be many gigabytes large (think drive images, ISO files, etc). With this approach, though, the contents of the file would be held in memory between the time I download it from the API and the time I send it to the user - not good.
So my solution is to try to "stream" it - as I get chunks of data from the API's HTTP response, I just want to turn around and send those chunks along to the FTP user. Seems straightforward.
For my "custom FTP functionality", I'm using a subclass of ftp.FTPShell. The reading method of this, openForReading, returns a Deferred that fires with an implementation of IReadFile.
Below is my (initial, simple) implementation for "streaming HTTP". I use the fetch function to setup an HTTP request, and the callback I pass in gets called with each chunk I get from the response.
I thought I could use some sort of two-ended buffer object to transport the chunks between the HTTP and FTP, by using the buffer object as the file-like object required by ftp._FileReader, but that's quickly proving not to work, as the consumer from the send call almost immediately closes the buffer (because it's returning an empty string, because there's no data to read yet, etc). Thus, I'm "sending" empty files before I even start receiving the HTTP response chunks.
Am I close, but missing something? Am I on the wrong path altogether? Is what I want to do really impossible (I highly doubt that)?
from twisted.web import client
import urlparse
class HTTPStreamer(client.HTTPPageGetter):
def __init__(self):
self.callbacks = []
def addHandleResponsePartCallback(self, callback):
self.callbacks.append(callback)
def handleResponsePart(self, data):
for cb in self.callbacks:
cb(data)
client.HTTPPageGetter.handleResponsePart(self, data)
class HTTPStreamerFactory(client.HTTPClientFactory):
protocol = HTTPStreamer
def __init__(self, *args, **kwargs):
client.HTTPClientFactory.__init__(self, *args, **kwargs)
self.callbacks = []
def addChunkCallback(self, callback):
self.callbacks.append(callback)
def buildProtocol(self, addr):
p = client.HTTPClientFactory.buildProtocol(self, addr)
for cb in self.callbacks:
p.addHandleResponsePartCallback(cb)
return p
def fetch(url, callback):
parsed = urlparse.urlsplit(url)
f = HTTPStreamerFactory(parsed.path)
f.addChunkCallback(callback)
from twisted.internet import reactor
reactor.connectTCP(parsed.hostname, parsed.port or 80, f)
As a side note, this is only my second day with Twisted - I spent most of yesterday reading through Dave Peticolas' Twisted Introduction, which has been a great starting point, even if based on an older version of twisted.
That said, I may be doing things wrong.
A:
I thought I could use some sort of two-ended buffer object to transport the chunks between the HTTP and FTP, by using the buffer object as the file-like object required by ftp._FileReader, but that's quickly proving not to work, as the consumer from the send call almost immediately closes the buffer (because it's returning an empty string, because there's no data to read yet, etc). Thus, I'm "sending" empty files before I even start receiving the HTTP response chunks.
Instead of using ftp._FileReader, you want something that will do a write whenever a chunk arrives from your HTTPStreamer to a callback it supplies. You never need/want to do a read from a buffer on the HTTP, because there's no reason to even have such a buffer. As soon as HTTP bytes arrive, write them to the consumer. Something like...
class FTPStreamer(object):
implements(IReadFile)
def __init__(self, url):
self.url = url
def send(self, consumer):
fetch(url, consumer.write)
# You also need a Deferred to return here, so the
# FTP implementation knows when you're done.
return someDeferred
You may also want to use Twisted's producer/consumer interface to allow the transfer to be throttled, as may be necessary if your connection to the HTTP server is faster than your user's FTP connection to you.
| Twisted, FTP, and "streaming" large files | I'm attempting to implement what can best be described as "an FTP interface to an HTTP API". Essentially, there is an existing REST API that can be used to manage a user's files for a site, and I'm building a mediator server that re-exposes this API as an FTP server. So you can login with, say, Filezilla and list your files, upload new ones, delete old ones, etc.
I'm attempting this with twisted.protocols.ftp for the (FTP) server, and twisted.web.client for the (HTTP) client.
The thing I'm running up against is, when a user tries to download a file, "streaming" that file from an HTTP response to my FTP response. Similar for uploading.
The most straightforward approach would be to download the entire file from the HTTP server, then turn around and send the contents to the user. The problem with this is that any given file could be many gigabytes large (think drive images, ISO files, etc). With this approach, though, the contents of the file would be held in memory between the time I download it from the API and the time I send it to the user - not good.
So my solution is to try to "stream" it - as I get chunks of data from the API's HTTP response, I just want to turn around and send those chunks along to the FTP user. Seems straightforward.
For my "custom FTP functionality", I'm using a subclass of ftp.FTPShell. The reading method of this, openForReading, returns a Deferred that fires with an implementation of IReadFile.
Below is my (initial, simple) implementation for "streaming HTTP". I use the fetch function to setup an HTTP request, and the callback I pass in gets called with each chunk I get from the response.
I thought I could use some sort of two-ended buffer object to transport the chunks between the HTTP and FTP, by using the buffer object as the file-like object required by ftp._FileReader, but that's quickly proving not to work, as the consumer from the send call almost immediately closes the buffer (because it's returning an empty string, because there's no data to read yet, etc). Thus, I'm "sending" empty files before I even start receiving the HTTP response chunks.
Am I close, but missing something? Am I on the wrong path altogether? Is what I want to do really impossible (I highly doubt that)?
from twisted.web import client
import urlparse
class HTTPStreamer(client.HTTPPageGetter):
def __init__(self):
self.callbacks = []
def addHandleResponsePartCallback(self, callback):
self.callbacks.append(callback)
def handleResponsePart(self, data):
for cb in self.callbacks:
cb(data)
client.HTTPPageGetter.handleResponsePart(self, data)
class HTTPStreamerFactory(client.HTTPClientFactory):
protocol = HTTPStreamer
def __init__(self, *args, **kwargs):
client.HTTPClientFactory.__init__(self, *args, **kwargs)
self.callbacks = []
def addChunkCallback(self, callback):
self.callbacks.append(callback)
def buildProtocol(self, addr):
p = client.HTTPClientFactory.buildProtocol(self, addr)
for cb in self.callbacks:
p.addHandleResponsePartCallback(cb)
return p
def fetch(url, callback):
parsed = urlparse.urlsplit(url)
f = HTTPStreamerFactory(parsed.path)
f.addChunkCallback(callback)
from twisted.internet import reactor
reactor.connectTCP(parsed.hostname, parsed.port or 80, f)
As a side note, this is only my second day with Twisted - I spent most of yesterday reading through Dave Peticolas' Twisted Introduction, which has been a great starting point, even if based on an older version of twisted.
That said, I may be doing things wrong.
| [
"\nI thought I could use some sort of two-ended buffer object to transport the chunks between the HTTP and FTP, by using the buffer object as the file-like object required by ftp._FileReader, but that's quickly proving not to work, as the consumer from the send call almost immediately closes the buffer (because it'... | [
2
] | [] | [] | [
"ftp",
"python",
"twisted"
] | stackoverflow_0004222293_ftp_python_twisted.txt |
Q:
regarding backslash from postgresql
i have a noob question.
I have a record in a table that looks like '\1abc'
I then use this string as a regex replacement in re.sub("([0-9])",thereplacement,"2")
I'm a little confused with the backslashes. The string i got back was "\\1abc"
A:
Are you using python interactivly?
In regular string you need to escape backslashes in your code, or use r"..." (Link to docs). If you are running python interactivly and don't assign the results from your database to a variable, it'll be printed out using it's __repr__() method.
>>> s = "\\1abc"
>>> s
'\\1abc' # <-- How it's represented in Python code
>>> print s
\1abc # <-- The actual string
Also, your re.sub is a bit weird. 1) Maybe you meant [0-9] as the pattern? (Matching a single digit). The arguments are probably switche too, if thereplacement is your input. This is the syntax:
re.sub(pattern, repl, string, count=0)
So my guess is you expect something like this:
>>> s_in = yourDbMagic() # Which returns \1abc
>>> s_out = re.sub("[0-9]", "2", s_in)
>>> print s_in, s_out
\1abc \2abc
Edit: Tried to better explain escaping/representation.
A:
Note that you can make \ stop being an escape character by setting standard_conforming_strings to on.
| regarding backslash from postgresql | i have a noob question.
I have a record in a table that looks like '\1abc'
I then use this string as a regex replacement in re.sub("([0-9])",thereplacement,"2")
I'm a little confused with the backslashes. The string i got back was "\\1abc"
| [
"Are you using python interactivly?\nIn regular string you need to escape backslashes in your code, or use r\"...\" (Link to docs). If you are running python interactivly and don't assign the results from your database to a variable, it'll be printed out using it's __repr__() method.\n>>> s = \"\\\\1abc\"\n>>> s\n'... | [
2,
2
] | [] | [] | [
"postgresql",
"python"
] | stackoverflow_0004224400_postgresql_python.txt |
Q:
Python mechanize login to website
I'm trying to log into a website using Python and Mechanize, however, I'm running into trouble when trying to get the POST data to behave as I want.
Essentially I want to replicate this using mechanize and Python:
wget --quiet --save-cookies cookiejar --keep-session-cookies --post-data "action=login&login_nick=USERNAME&login_pwd=PASSWORD" -O outfile.htm http://domain.com/index.php
The form looks like this:
<login POST http://domain.com/index.php application/x-www-form-urlencoded
<TextControl(login_nick=USERNAME)>
<PasswordControl(login_pwd=PASSWORD)>
<CheckboxControl(login_auto=[1])>
<SubmitButtonControl(<None>=) (readonly)>>
Setting the appropriate values and submitting the form isn't a problem, but that leaves out the "action=login"-part.
response = self.browser.open(self.url+"/index.php")
self.browser.select_form(name="login")
self.browser["login_nick"] = self.encoded_username
self.browser["login_pwd"] = self.encoded_password
self.browser.method = "POST"
response = self.browser.open(self.browser.submit())
print (response.read())
Now the question is, how do I add the action=login part?
Edit: Okay, so I added a hidden field named action and set the value to login. Analyzing the TCP stream with Wireshark, the POST data is indeed structured the way it should. However, it seems that mechanize is messing with my urlencoding (I have already urlencoded the values specifically for the charset that the website uses). For example, my username contains an Å - which I have urlencoded to %C5. However, when it's sent with mechanize, it's displayed as %25C5.
How do I stop mechanize from changing the strings?
EDIT: I realized that rather than fighting mechanize, I could just not urlencode my strings before sending them. Case closed.
A:
Mechanize seems to urlencode the strings anyway, so there's no point in fighting it. This is the final solution (obviously not syntactically valid, but hopefully you get the idea).
import mechanize
self.browser = mechanize.Browser()
self.browser.open(self.url)
self.browser.select_form(name="login")
self.browser["login_nick"] = self.username
self.browser["login_pwd"] = self.password
self.browser.new_control("HIDDEN", "action", {})
control = self.browser.form.find_control("action")
control.readonly = False
self.browser["action"] = "login"
self.browser.method = "POST"
self.browser.action = self.url
response = self.browser.submit()
| Python mechanize login to website | I'm trying to log into a website using Python and Mechanize, however, I'm running into trouble when trying to get the POST data to behave as I want.
Essentially I want to replicate this using mechanize and Python:
wget --quiet --save-cookies cookiejar --keep-session-cookies --post-data "action=login&login_nick=USERNAME&login_pwd=PASSWORD" -O outfile.htm http://domain.com/index.php
The form looks like this:
<login POST http://domain.com/index.php application/x-www-form-urlencoded
<TextControl(login_nick=USERNAME)>
<PasswordControl(login_pwd=PASSWORD)>
<CheckboxControl(login_auto=[1])>
<SubmitButtonControl(<None>=) (readonly)>>
Setting the appropriate values and submitting the form isn't a problem, but that leaves out the "action=login"-part.
response = self.browser.open(self.url+"/index.php")
self.browser.select_form(name="login")
self.browser["login_nick"] = self.encoded_username
self.browser["login_pwd"] = self.encoded_password
self.browser.method = "POST"
response = self.browser.open(self.browser.submit())
print (response.read())
Now the question is, how do I add the action=login part?
Edit: Okay, so I added a hidden field named action and set the value to login. Analyzing the TCP stream with Wireshark, the POST data is indeed structured the way it should. However, it seems that mechanize is messing with my urlencoding (I have already urlencoded the values specifically for the charset that the website uses). For example, my username contains an Å - which I have urlencoded to %C5. However, when it's sent with mechanize, it's displayed as %25C5.
How do I stop mechanize from changing the strings?
EDIT: I realized that rather than fighting mechanize, I could just not urlencode my strings before sending them. Case closed.
| [
"Mechanize seems to urlencode the strings anyway, so there's no point in fighting it. This is the final solution (obviously not syntactically valid, but hopefully you get the idea).\nimport mechanize\n\nself.browser = mechanize.Browser()\nself.browser.open(self.url)\nself.browser.select_form(name=\"login\")\n\nself... | [
9
] | [] | [] | [
"mechanize",
"python",
"webforms"
] | stackoverflow_0004225721_mechanize_python_webforms.txt |
Q:
Scan for secured pdf documents
I've currently run into the need to find which pdfs within a directory are "Secured Documents".
All of the pdfs should be unsecured, and convertible via xpdf, however, this is not the case. How could I scan through all the pdfs in a directory to find out whether or not they are secured?
A:
pyPdf supports decrypting PDFs. Its PdfFileReader class has an isEncrypted attribute.
import pyPdf
if pyPdf.PdfFileReader(open("file_name.pdf", 'rb')).isEncrypted:
print "Rut ro, it's encrypted."
# skip file? Write to a log?
else:
print "We're clear."
# Do stuff with the file.
| Scan for secured pdf documents | I've currently run into the need to find which pdfs within a directory are "Secured Documents".
All of the pdfs should be unsecured, and convertible via xpdf, however, this is not the case. How could I scan through all the pdfs in a directory to find out whether or not they are secured?
| [
"pyPdf supports decrypting PDFs. Its PdfFileReader class has an isEncrypted attribute.\nimport pyPdf\nif pyPdf.PdfFileReader(open(\"file_name.pdf\", 'rb')).isEncrypted:\n print \"Rut ro, it's encrypted.\"\n # skip file? Write to a log?\nelse:\n print \"We're clear.\"\n # Do stuff with the file.\n\n"
] | [
1
] | [] | [] | [
"python",
"xpdf"
] | stackoverflow_0004226479_python_xpdf.txt |
Q:
for-if without list comprehension in one line
can this be written in one line without List Comprehensions?
for x in vec:
if x > 3:
...
...
A:
No, you can't. The Python language reference states:
Compound statements consist of one or
more ‘clauses.’ A clause consists of a
header and a ‘suite.’ The clause
headers of a particular compound
statement are all at the same
indentation level. Each clause header
begins with a uniquely identifying
keyword and ends with a colon. A suite
is a group of statements controlled by
a clause. A suite can be one or more
semicolon-separated simple statements
on the same line as the header,
following the header’s colon, or it
can be one or more indented statements
on subsequent lines. Only the latter
form of suite can contain nested
compound statements; the following is
illegal, mostly because it wouldn’t be
clear to which if clause a following
else clause would belong:
if test1: if test2: print x
Indeed, Python generates a SyntaxError for the nested ifs above. More formally regarding for, this is its grammar in Python:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]
Note that when for is followed by a statement without an indentation, that statement must be a stmt_list, which only allows simple_stmt instances. simple_stmt is this:
simple_stmt ::= expression_stmt
| assert_stmt
| assignment_stmt
| augmented_assignment_stmt
| pass_stmt
| del_stmt
| print_stmt
| return_stmt
| yield_stmt
| raise_stmt
| break_stmt
| continue_stmt
| import_stmt
| global_stmt
| exec_stmt
Which doesn't include compound statements like if and for.
That said, keep in mind that Python's syntax is aimed at clarity. Therefore it's better not to nest such statements, this is what generators/list comprehensions were made for. If you deem your computation to be simple enough for a single line, then comprehensions are for you. Otherwise, you really don't want to clutter the code by having everything on a single line - break it up nicely with indentation. A few extra lines don't cost much these days.
A:
See @KennyTM... no reason to compress that much.
What being said, for x in (i in vec if i > 3) does the job, as well as itertools.ifilter (or just the builtin filter in Python 3) with a lambda x: x > 3 predicate. They work with all iterables as well, and are lazy (e.g. if you break during the loop, you didn't check a single item too much).
A:
It can, but list comprehensions/generator expressions are the exact sort of thing that should be used here. Depending on what you want to do in your if block, you could use some form of map or reduce, but list comprehensions and generator expressions are likely the best way to do it.
A:
Yes
for x in filter(lambda i:i>3,vec):
| for-if without list comprehension in one line | can this be written in one line without List Comprehensions?
for x in vec:
if x > 3:
...
...
| [
"No, you can't. The Python language reference states:\n\nCompound statements consist of one or\n more ‘clauses.’ A clause consists of a\n header and a ‘suite.’ The clause\n headers of a particular compound\n statement are all at the same\n indentation level. Each clause header\n begins with a uniquely identif... | [
3,
3,
0,
0
] | [
"You can imagine somethings like this : \ndef do_something(value):\n ...\n\ndef do_otherthing(value):\n ...\n\n\nfor x in t: do_something(x) if x>3 else do_otherthing(x)\n\n"
] | [
-1
] | [
"list_comprehension",
"python"
] | stackoverflow_0004226523_list_comprehension_python.txt |
Q:
Prevent python shelve corruption
How should I prevent corruption in a shelve file? Should the shelve be closed most of the time and then opened only when I need to read or edit a value?
A:
If safety of your persistent objects is of high importance in your project, using shelve is not a good idea. Neither is pickling objects and manually writing them into files.
Consider that real databases invest huge resources (brainpower and code) to be safe in case of failures. So keep your data in a real DB. The simplest would be sqlite, as it comes bundled with Python. sqlite is quite safe and has a lot of smarts in it about keeping your data in some valid state even in case of system failures (like when someone trips on your PC's power cable).
| Prevent python shelve corruption | How should I prevent corruption in a shelve file? Should the shelve be closed most of the time and then opened only when I need to read or edit a value?
| [
"If safety of your persistent objects is of high importance in your project, using shelve is not a good idea. Neither is pickling objects and manually writing them into files.\nConsider that real databases invest huge resources (brainpower and code) to be safe in case of failures. So keep your data in a real DB. Th... | [
6
] | [] | [] | [
"python",
"shelve"
] | stackoverflow_0004226580_python_shelve.txt |
Q:
Is it possible to edit doc files with Python?
I have a set of .doc files which I want to perform some simple changes to (e.g. set the font of all the text in each file to be arial).
I don't want to do all the operations manually. I thought I'll try to automate it with a Python script. Is it a complicated task? How is it done?
I use Python 3.
A:
The Python docx module should be helpful.
(2nd time this question was asked today!)
| Is it possible to edit doc files with Python? | I have a set of .doc files which I want to perform some simple changes to (e.g. set the font of all the text in each file to be arial).
I don't want to do all the operations manually. I thought I'll try to automate it with a Python script. Is it a complicated task? How is it done?
I use Python 3.
| [
"The Python docx module should be helpful. \n(2nd time this question was asked today!)\n"
] | [
5
] | [] | [] | [
"ms_word",
"python"
] | stackoverflow_0004226824_ms_word_python.txt |
Q:
ImportError when trying to run a python unittest with pydev
I am getting the following error when trying to run a module as a python unittest with PyDev.
Finding files...
['C:\\Projectos\\spa\\sensor\\src\\test\\test_sensor.py'] ... done
Importing test modules ... Traceback (most recent call last):
File "C:\eclipse\plugins\org.python.pydev.debug_1.6.3.2010100513\pysrc\runfiles.py", line 342, in __get_module_from_str
mod = __import__(modname)
ImportError: No module named :\Projectos\spa\sensor\src\test\test_sensor
ERROR: Module: :\Projectos\spa\sensor\src\test\test_sensor could not be imported.
done.
I noticed the path in the ERROR: Module: line starts with ":\" but I don't know what's causing it.
Any ideas?
Thank you.
A:
Turns out pydev does not play well with cygwin's python.
Installed python 2.7 for windows and it works.
| ImportError when trying to run a python unittest with pydev | I am getting the following error when trying to run a module as a python unittest with PyDev.
Finding files...
['C:\\Projectos\\spa\\sensor\\src\\test\\test_sensor.py'] ... done
Importing test modules ... Traceback (most recent call last):
File "C:\eclipse\plugins\org.python.pydev.debug_1.6.3.2010100513\pysrc\runfiles.py", line 342, in __get_module_from_str
mod = __import__(modname)
ImportError: No module named :\Projectos\spa\sensor\src\test\test_sensor
ERROR: Module: :\Projectos\spa\sensor\src\test\test_sensor could not be imported.
done.
I noticed the path in the ERROR: Module: line starts with ":\" but I don't know what's causing it.
Any ideas?
Thank you.
| [
"Turns out pydev does not play well with cygwin's python.\nInstalled python 2.7 for windows and it works.\n"
] | [
0
] | [] | [] | [
"eclipse",
"pydev",
"python",
"unit_testing"
] | stackoverflow_0004225927_eclipse_pydev_python_unit_testing.txt |
Q:
Resizing and stretching a NumPy array
I am working in Python and I have a NumPy array like this:
[1,5,9]
[2,7,3]
[8,4,6]
How do I stretch it to something like the following?
[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]
These are just some example arrays, I will actually be resizing several sizes of arrays, not just these.
I'm new at this, and I just can't seem to wrap my head around what I need to do.
A:
@KennyTM's answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try np.repeat:
>>> a = np.array([[1, 5, 9],
[2, 7, 3],
[8, 4, 6]])
>>> np.repeat(a,2, axis=1)
array([[1, 1, 5, 5, 9, 9],
[2, 2, 7, 7, 3, 3],
[8, 8, 4, 4, 6, 6]])
So, this accomplishes repeating along one axis, to get it along multiple axes (as you might want), simply nest the np.repeat calls:
>>> np.repeat(np.repeat(a,2, axis=0), 2, axis=1)
array([[1, 1, 5, 5, 9, 9],
[1, 1, 5, 5, 9, 9],
[2, 2, 7, 7, 3, 3],
[2, 2, 7, 7, 3, 3],
[8, 8, 4, 4, 6, 6],
[8, 8, 4, 4, 6, 6]])
You can also vary the number of repeats for any initial row or column. For example, if you wanted two repeats of each row aside from the last row:
>>> np.repeat(a, [2,2,1], axis=0)
array([[1, 5, 9],
[1, 5, 9],
[2, 7, 3],
[2, 7, 3],
[8, 4, 6]])
Here when the second argument is a list it specifies a row-wise (rows in this case because axis=0) repeats for each row.
A:
>>> a = numpy.array([[1,5,9],[2,7,3],[8,4,6]])
>>> numpy.kron(a, [[1,1],[1,1]])
array([[1, 1, 5, 5, 9, 9],
[1, 1, 5, 5, 9, 9],
[2, 2, 7, 7, 3, 3],
[2, 2, 7, 7, 3, 3],
[8, 8, 4, 4, 6, 6],
[8, 8, 4, 4, 6, 6]])
A:
Unfortunately numpy does not allow fractional steps (as far as I am aware). Here is a workaround. It's not as clever as Kenny's solution, but it makes use of traditional indexing:
>>> a = numpy.array([[1,5,9],[2,7,3],[8,4,6]])
>>> step = .5
>>> xstop, ystop = a.shape
>>> x = numpy.arange(0,xstop,step).astype(int)
>>> y = numpy.arange(0,ystop,step).astype(int)
>>> mg = numpy.meshgrid(x,y)
>>> b = a[mg].T
>>> b
array([[1, 1, 5, 5, 9, 9],
[1, 1, 5, 5, 9, 9],
[2, 2, 7, 7, 3, 3],
[2, 2, 7, 7, 3, 3],
[8, 8, 4, 4, 6, 6],
[8, 8, 4, 4, 6, 6]])
(dtlussier's solution is better)
| Resizing and stretching a NumPy array | I am working in Python and I have a NumPy array like this:
[1,5,9]
[2,7,3]
[8,4,6]
How do I stretch it to something like the following?
[1,1,5,5,9,9]
[1,1,5,5,9,9]
[2,2,7,7,3,3]
[2,2,7,7,3,3]
[8,8,4,4,6,6]
[8,8,4,4,6,6]
These are just some example arrays, I will actually be resizing several sizes of arrays, not just these.
I'm new at this, and I just can't seem to wrap my head around what I need to do.
| [
"@KennyTM's answer is very slick, and really works for your case but as an alternative that might offer a bit more flexibility for expanding arrays try np.repeat:\n>>> a = np.array([[1, 5, 9],\n [2, 7, 3],\n [8, 4, 6]])\n\n>>> np.repeat(a,2, axis=1)\narray([[1, 1, 5, 5, 9, 9],\n [2, ... | [
42,
19,
2
] | [] | [] | [
"arrays",
"numpy",
"python",
"resize",
"stretch"
] | stackoverflow_0004226386_arrays_numpy_python_resize_stretch.txt |
Q:
Language choices for writing very fast abstractions interfacing with Python?
I have a system currently written in Python that can be separated into backend and frontend layers. Python is too slow, so I want to rewrite the backend in a fast compiled language while keeping the frontend in Python, in a way that lets the backend functionality be called from Python. What are the best choices to do so?
I've considered cython but it's very limited and cumbersome to write, and not that much faster. From what I remember of Boost Python for C++, it's very annoying to maintain the bridge between languages. Are there better choices?
My main factors are:
speed of execution
speed of compilation
language is declarative
A:
C++ with SWIG can generate all of the glue code you need. So long as you avoid excessive jumps between C++ and python it'll be as fast as your C++. SWIG interfaces are usually fairly straightforward to generate unless you're doing something "odd".
A:
If you used Jython you could call into Java back-end routines easily (trivially). Java's about twice as slow as c and 10x faster than python last time I checked.
A:
I would disagree about Boost::Python. It can get cumbersome when wrapping an existing c++-centric library and trying not to change the interface. But that is not what you are looking to do.
You are looking to push the heavy lifting of an existing python solution in to a faster language. That means that you can control the interface.
If you are in control of the interface, you can keep it python-friendly, and bp-friendly (IE: avoid problematic things like pointers and immutable types as l-values)
In that case, Boost::Python can be as simple as telling it which functions you want to call from python.
| Language choices for writing very fast abstractions interfacing with Python? | I have a system currently written in Python that can be separated into backend and frontend layers. Python is too slow, so I want to rewrite the backend in a fast compiled language while keeping the frontend in Python, in a way that lets the backend functionality be called from Python. What are the best choices to do so?
I've considered cython but it's very limited and cumbersome to write, and not that much faster. From what I remember of Boost Python for C++, it's very annoying to maintain the bridge between languages. Are there better choices?
My main factors are:
speed of execution
speed of compilation
language is declarative
| [
"C++ with SWIG can generate all of the glue code you need. So long as you avoid excessive jumps between C++ and python it'll be as fast as your C++. SWIG interfaces are usually fairly straightforward to generate unless you're doing something \"odd\". \n",
"If you used Jython you could call into Java back-end rout... | [
7,
2,
1
] | [] | [] | [
"boost_python",
"c++",
"java",
"python"
] | stackoverflow_0004188273_boost_python_c++_java_python.txt |
Q:
CLI Piano Synthesizer?
I've been working on a music improvisation program for a class I'm taking, and I need to be able to show what it can do to a class. Currently, the program outputs notes in scientific format and chords in brackets (I use Python). Here's an example of the output:
C5 D4 [D#5, D#4]
Is there any CLI software that I can use to play those notes? I will be presenting this on a Mac, and I develop on Linux, so it would be nice to have a CLI utility that I can just pipe the output of my program into.
Thanks!
A:
There are a whole bunch of resources that might be useful to you here. If it does't need to run in real time, you might be happiest just writing a standard midi file and using some other software to actually render the playback.
A:
I don't know of a program that does that. Though I have written a program that plays Nokia ringtone format through the PC 'beep' speaker. But you can't beep two tones at once so my program can't handle chords.
Instead, why not use one of the libraries mentioned here: Simple, Cross Platform MIDI Library for Python and output a MIDI file which can be then played using any standard audio player.
| CLI Piano Synthesizer? | I've been working on a music improvisation program for a class I'm taking, and I need to be able to show what it can do to a class. Currently, the program outputs notes in scientific format and chords in brackets (I use Python). Here's an example of the output:
C5 D4 [D#5, D#4]
Is there any CLI software that I can use to play those notes? I will be presenting this on a Mac, and I develop on Linux, so it would be nice to have a CLI utility that I can just pipe the output of my program into.
Thanks!
| [
"There are a whole bunch of resources that might be useful to you here. If it does't need to run in real time, you might be happiest just writing a standard midi file and using some other software to actually render the playback.\n",
"I don't know of a program that does that. Though I have written a program that ... | [
1,
0
] | [] | [] | [
"command_line",
"linux",
"macos",
"piano",
"python"
] | stackoverflow_0004227408_command_line_linux_macos_piano_python.txt |
Q:
Forward slash in Python replace()
I have been working on an anagram solver in Python 2.7 and came across a curiosity that I haven't been able to find an explanation for. The program reads from a file which contains a list of anagrams in a format like so:
# anagram
# anagram
# anagram
.
.
.
etc
Reading this directly into a string, Python obviously comments everything out, so I was playing with replace() trying to find a way to strip out the hash characters. Trying...
string = file.read().replace('#', '')
...would produce an empty string. I tried to use a backslash in front of the hash but goofed and typo'd a forward slash, which gave me the result:
string = file.read().replace('/#', '')
string = '#\tanagram\n#\tanagram\n#\tanagram'
Stripping out unnecessary characters was a no-brainer at that point and the program works perfectly. However, I'm not content using a line of code that I don't fully understand. I haven't had much luck finding any documentation or code that explains/makes us of something like this, so I'm either looking in the wrong places or looking for the wrong thing.
Could anyone offer an explanation to why it behaves like this?
A:
Try this:
[s.lstrip('#\t') for s in file.read().split('\n')]
Python does not treat a # specially in any way whatsoever inside a string, you don't need to escape it.
A:
Did you change anything else when you replaced your '#' with '/#'? Try running your program again, exactly as it is, but removing the /. # isn't a special character in Python strings.
The code you've shown us has a do-nothing in the replace, since there aren't any instances of '/#' in your string.
Sample interactive session:
>>> "#foo bar\n\t#blah".replace("#", "")
'foo bar\n\tblah'
| Forward slash in Python replace() | I have been working on an anagram solver in Python 2.7 and came across a curiosity that I haven't been able to find an explanation for. The program reads from a file which contains a list of anagrams in a format like so:
# anagram
# anagram
# anagram
.
.
.
etc
Reading this directly into a string, Python obviously comments everything out, so I was playing with replace() trying to find a way to strip out the hash characters. Trying...
string = file.read().replace('#', '')
...would produce an empty string. I tried to use a backslash in front of the hash but goofed and typo'd a forward slash, which gave me the result:
string = file.read().replace('/#', '')
string = '#\tanagram\n#\tanagram\n#\tanagram'
Stripping out unnecessary characters was a no-brainer at that point and the program works perfectly. However, I'm not content using a line of code that I don't fully understand. I haven't had much luck finding any documentation or code that explains/makes us of something like this, so I'm either looking in the wrong places or looking for the wrong thing.
Could anyone offer an explanation to why it behaves like this?
| [
"Try this:\n[s.lstrip('#\\t') for s in file.read().split('\\n')]\n\nPython does not treat a # specially in any way whatsoever inside a string, you don't need to escape it.\n",
"Did you change anything else when you replaced your '#' with '/#'? Try running your program again, exactly as it is, but removing the /. ... | [
3,
0
] | [] | [] | [
"python",
"replace",
"string"
] | stackoverflow_0004227373_python_replace_string.txt |
Q:
override method of class in python
I'd like to override a class method, not creating subclass/extending from a class.
An example:
from django.contrib import admin
class NewModelAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
# some custom stuff
Now I don't want to change all the classes (aka Models) which extend from admin.ModelAdmin to NewModelAdmin. But I don't want to modify the original django code either.
Is there some way to accomplish this?
A:
I'm not 100% clear with what you want to do, and why you don't want to create a new subclass or have a method of a different name.
But in general in python you can do something like:
class MyClass(object):
def print_hello(self):
print "not hello"
def real_print_hello():
print "hello"
x = MyClass()
x.print_hello() # "not hello"
setattr(x, "print_hello", real_print_hello)
x.print_hello() # "hello"
A:
Are you trying to do 'monkey patching'?
http://mail.python.org/pipermail/python-dev/2008-January/076194.html
A:
In order to keep your code maintainable, it's best to go ahead and have your individual ModelAdmin classes inherit from NewModelAdmin. This way, other developers who look at your code (and you, perhaps a year or two later) can clearly see where the custom formfield_for_dbfield behavior originates from so that it can be updated if needed. If you monkey-patch admin.ModelAdmin, it will make it much more difficult to track down issues or change the behavior if needed later.
A:
Chances are good that your problem is solvable without monkey-patching, which often can have unintended consequences.
How are you registering models with the django admin?
If you are using this approach:
admin.site.register(FooModel) #uses generic ModelAdmin
You have the problem of needing to change this to many boilerplate instances of subclasses of NewModelAdmin, which would look like this:
class FooModelAdmin(NewModelAdmin):
pass #does nothing except set up inheritance
admin.site.register(FooModel, FooModelAdmin)
This is really wordy and might take a lot of time to implement if you have a lot of models, so do it programmatically by writing a wrapper function:
def my_admin_register(model):
class _newmodeladmin(ModelAdmin):
def your_overridden_method(*args, **kwargs):
#do whatever here
admin.site.register(model, _newmodeladmin)
Then, you can use this like this:
my_admin_register(FooModel)
A:
You can change a class method using setattr() on the class - aka monkey patching.
A:
If you modify a method in a class you modify behavior for:
all instances which resolve their method to that class
all derived classes which resolve their method to that class
Your requirements are mutually exclusive. You cannot modify the behavior of a class without impacting those object which resolve their methods to the class.
In order to not modify the behaviors of these other objects you would want to create the method in your instance so that it doesn't resolve it's method in the class.
Another alternative is to rely on Python's duck-typing. You don't need the object to be directly related to the one currently used. You could reimplement the interface and in the code swap out the calls to the old class for your new one.
These techniques have tradeoffs in maintainability and design. In other words don't use them unless you have no other options.
A:
I'm not 100% sure what you are trying to achieve, but I suppose you want to behave all admins that inherit from models.ModelAdmin without having to change their declaration. The only solution to achieve this will be monkey-patching the original ModelAdmin class, eg. something like:
setattr(admin.ModelAdmin, 'form_field_for_dbfield', mymethod)
This for sure not the most recommendable way, because the code will be hard to maintain and other things.
| override method of class in python | I'd like to override a class method, not creating subclass/extending from a class.
An example:
from django.contrib import admin
class NewModelAdmin(admin.ModelAdmin):
def formfield_for_dbfield(self, db_field, **kwargs):
# some custom stuff
Now I don't want to change all the classes (aka Models) which extend from admin.ModelAdmin to NewModelAdmin. But I don't want to modify the original django code either.
Is there some way to accomplish this?
| [
"I'm not 100% clear with what you want to do, and why you don't want to create a new subclass or have a method of a different name.\nBut in general in python you can do something like:\nclass MyClass(object):\n def print_hello(self):\n print \"not hello\"\n\ndef real_print_hello():\n print \"hello\"\n\... | [
4,
3,
3,
2,
1,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004226864_django_python.txt |
Q:
How to automatically Import all subclasses of a root class in Python?
I'd like to know if it is possible to automatically import all subclasses of a class in python without writing import subclassxy for every subclass.
A:
You cannot, in general. The interpreter has no way of knowing whether or not a specific package defines a subclass of your class of interest. In principle, you can write a new package or module tomorrow defining a new subclass. It will now need to get imported. For the interpreter to keep track of all of this would be very burdensome.
You can construct a package that imports all subclasses of interest.
A:
Here is a draft example that can give you idea about what you want to do:
my_module.py
class RootClass(object):
pass
class ChildClass(RootClass):
pass
in another file.py
import sys
from my_module import RootClass
# Loop over all subclasses of RootClass.
for class_ in RootClass.__subclasses__():
# from module import subclass.
__import__(class_.__module__, globals(), locals(), [class_.__name__,])
# Update the global namespace with the new class
globals().update({class_.__name__:
getattr(sys.modules[class_.__module__],
class_.__name__)})
print ChildClass
# OutPut : <class 'my_module.ChildClass'>
PS: i don't advice you to do this !!!!
A:
You can make a module that does the import subclassxy for every subclass (perhaps auto-generated) and from module import * it.
A:
This simply isn't possible, because Python has no way of knowing what subclasses exist until it has already seen them (at which point they'll be in the base class's subclasses attribute).
Why don't you tell us what you really want to achieve? That way, we can help you find a solution.
| How to automatically Import all subclasses of a root class in Python? | I'd like to know if it is possible to automatically import all subclasses of a class in python without writing import subclassxy for every subclass.
| [
"You cannot, in general. The interpreter has no way of knowing whether or not a specific package defines a subclass of your class of interest. In principle, you can write a new package or module tomorrow defining a new subclass. It will now need to get imported. For the interpreter to keep track of all of this woul... | [
3,
3,
1,
1
] | [] | [] | [
"class",
"import",
"python"
] | stackoverflow_0004227418_class_import_python.txt |
Q:
Python scientific: interrupt differential equation solving with a condition
I am currently solving a system of differential equation under python using odeint to simulate charged particles in a field (the source comes from this package):
time = np.linspace(0, 5, 1000)
def sm(x, t):
return np.array([x[1], eta*Ez0(x[0])])
traj = odeint(sm,[0,1.], time)
It works fine but I would like to stop the calculation as soon as x[0] < 0. For the moment I just block the evolution of the sytem:
def sm1(x, t):
if x[0] < 0:
return np.array([0, 0])
else:
return np.array([x[1], eta*Ez0(x[0])])
traj = odeint(sm1,[0,1.],time)
but I gess there are better solutions. I've found this but is seems to me that it fixes the number of steps, which is regrettable.
Any suggestion appreciated.
A:
If you write a custom extension of the odeint function, you could have your function raise a particular exception when it's finished. Doing it in Python might make it substantially slower, but I think you write the same thing in C or Cython. Note that I haven't tested the following.
class ThatsEnoughOfThat(Exception):
pass
def custom_odeint(func, y0, t): # + whatever parameters you need
for timestep in t:
try:
# Do stuff. Call odeint/other scipy functions?
except ThatsEnoughOfThat:
break
return completedstuff
def sm2(x, t):
if x[0] < 0:
raise ThatsEnoughOfThat
return np.array([x[1], eta*Ez0(x[0])])
| Python scientific: interrupt differential equation solving with a condition | I am currently solving a system of differential equation under python using odeint to simulate charged particles in a field (the source comes from this package):
time = np.linspace(0, 5, 1000)
def sm(x, t):
return np.array([x[1], eta*Ez0(x[0])])
traj = odeint(sm,[0,1.], time)
It works fine but I would like to stop the calculation as soon as x[0] < 0. For the moment I just block the evolution of the sytem:
def sm1(x, t):
if x[0] < 0:
return np.array([0, 0])
else:
return np.array([x[1], eta*Ez0(x[0])])
traj = odeint(sm1,[0,1.],time)
but I gess there are better solutions. I've found this but is seems to me that it fixes the number of steps, which is regrettable.
Any suggestion appreciated.
| [
"If you write a custom extension of the odeint function, you could have your function raise a particular exception when it's finished. Doing it in Python might make it substantially slower, but I think you write the same thing in C or Cython. Note that I haven't tested the following.\nclass ThatsEnoughOfThat(Except... | [
1
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0004227481_numpy_python_scipy.txt |
Q:
Python MySQL Standard
What is the "standard" way of using mysql in python. I define standard as something that won't go away for a long time.
import _mysql
db = _mysql.connect(host, user, pass, db);
db.query("sql");
vs
import MySQLdb
db = MySQLdb.connect(host, user, pass, db);
cursor = db.cursor();
cursor.execute("sql");
Obviously MySQLdb is a wrapper for _mysql, but I hate using wrappers at the risk of them not being maintained
A:
The standard way of dealing with relational database engines is defined by DB-API as described in PEP 249.
A:
I use
import MySQLdb
Which really isn't supported. On the PC, if you install the latest Python, it can be a problem to find.
| Python MySQL Standard | What is the "standard" way of using mysql in python. I define standard as something that won't go away for a long time.
import _mysql
db = _mysql.connect(host, user, pass, db);
db.query("sql");
vs
import MySQLdb
db = MySQLdb.connect(host, user, pass, db);
cursor = db.cursor();
cursor.execute("sql");
Obviously MySQLdb is a wrapper for _mysql, but I hate using wrappers at the risk of them not being maintained
| [
"The standard way of dealing with relational database engines is defined by DB-API as described in PEP 249.\n",
"I use \nimport MySQLdb\n\nWhich really isn't supported. On the PC, if you install the latest Python, it can be a problem to find. \n"
] | [
4,
0
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004227999_mysql_python.txt |
Q:
Python "IOError: [Errno 22] Invalid argument" when using cPickle to write large array to network drive
EDIT:
At the suggestion of J. F. Sebastian, I can get the same error much more simply:
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
Welcome to pylab, a matplotlib-based Python environment.
For more information, type 'help(pylab)'.
In [1]: open(r'c:\test.bin', 'wb').write('a'*67076095)
In [2]: open(r'c:\test.bin', 'wb').write('a'*67076096)
In [3]: open(r'z:\test.bin', 'wb').write('a'*67076095)
In [4]: open(r'z:\test.bin', 'wb').write('a'*67076096)
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
C:\Documents and Settings\User\<ipython console> in <module>()
IOError: [Errno 22] Invalid argument
In [5]:
Note that C: is a local drive, and Z: is a network drive.
ORIGINAL QUESTION:
Python 2.6.4 on Windows XP crashes if I use cPickle to write a file bigger than ~67 MB to our network drive (ReadyNAS Pro Pioneer edition). I'd like to be able to pickle large files. Is this a known problem? Is there a workaround?
The following script produces a crash:
import cPickle, numpy
a = numpy.zeros(8385007)
print "Writing %i bytes..."%(a.nbytes)
cPickle.dump(a, open('test_a.pkl', 'wb'), protocol=2)
print "Successfully written."
b = numpy.zeros(8385008)
print "Writing %i bytes..."%(b.nbytes)
cPickle.dump(b, open('test_b.pkl', 'wb'), protocol=2) ##Crashes on a network drive
print "Successfully written." ##Doesn't crash on a non-network drive
Here's the steps I take to produce a crash at the ipython prompt:
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
Welcome to pylab, a matplotlib-based Python environment.
For more information, type 'help(pylab)'.
In [1]: pwd
Out[1]: 'C:\\Documents and Settings\\User'
In [2]: run test
Writing 67080056 bytes...
Successfully written.
Writing 67080064 bytes...
Successfully written.
In [3]: cd Z:
Z:\
In [4]: pwd
Out[4]: 'Z:\\'
In [5]: run 'C:\\Documents and Settings\\User\\test'
Writing 67080056 bytes...
Successfully written.
Writing 67080064 bytes...
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
C:\Documents and Settings\User\test.py in <module>()
8 b = numpy.zeros(8385008)
9 print "Writing %i bytes..."%(b.nbytes)
---> 10 cPickle.dump(b, open('test_b.pkl', 'wb'), protocol=2)
11 print "Successfully written."
12
IOError: [Errno 22] Invalid argument
WARNING: Failure executing file: <C:\\Documents and Settings\\User\\test.py>
In [6]:
C: is the local hard drive on the machine. Z: is our network-attached storage.
A:
I believe the problem is related to:
http://support.microsoft.com/default.aspx?scid=kb;en-us;899149
...so, just try:
open(r'z:\test.bin','w+b').write('a'*67080064)
*Note the argument: 'w+b'
| Python "IOError: [Errno 22] Invalid argument" when using cPickle to write large array to network drive | EDIT:
At the suggestion of J. F. Sebastian, I can get the same error much more simply:
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
Welcome to pylab, a matplotlib-based Python environment.
For more information, type 'help(pylab)'.
In [1]: open(r'c:\test.bin', 'wb').write('a'*67076095)
In [2]: open(r'c:\test.bin', 'wb').write('a'*67076096)
In [3]: open(r'z:\test.bin', 'wb').write('a'*67076095)
In [4]: open(r'z:\test.bin', 'wb').write('a'*67076096)
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
C:\Documents and Settings\User\<ipython console> in <module>()
IOError: [Errno 22] Invalid argument
In [5]:
Note that C: is a local drive, and Z: is a network drive.
ORIGINAL QUESTION:
Python 2.6.4 on Windows XP crashes if I use cPickle to write a file bigger than ~67 MB to our network drive (ReadyNAS Pro Pioneer edition). I'd like to be able to pickle large files. Is this a known problem? Is there a workaround?
The following script produces a crash:
import cPickle, numpy
a = numpy.zeros(8385007)
print "Writing %i bytes..."%(a.nbytes)
cPickle.dump(a, open('test_a.pkl', 'wb'), protocol=2)
print "Successfully written."
b = numpy.zeros(8385008)
print "Writing %i bytes..."%(b.nbytes)
cPickle.dump(b, open('test_b.pkl', 'wb'), protocol=2) ##Crashes on a network drive
print "Successfully written." ##Doesn't crash on a non-network drive
Here's the steps I take to produce a crash at the ipython prompt:
Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
Welcome to pylab, a matplotlib-based Python environment.
For more information, type 'help(pylab)'.
In [1]: pwd
Out[1]: 'C:\\Documents and Settings\\User'
In [2]: run test
Writing 67080056 bytes...
Successfully written.
Writing 67080064 bytes...
Successfully written.
In [3]: cd Z:
Z:\
In [4]: pwd
Out[4]: 'Z:\\'
In [5]: run 'C:\\Documents and Settings\\User\\test'
Writing 67080056 bytes...
Successfully written.
Writing 67080064 bytes...
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
C:\Documents and Settings\User\test.py in <module>()
8 b = numpy.zeros(8385008)
9 print "Writing %i bytes..."%(b.nbytes)
---> 10 cPickle.dump(b, open('test_b.pkl', 'wb'), protocol=2)
11 print "Successfully written."
12
IOError: [Errno 22] Invalid argument
WARNING: Failure executing file: <C:\\Documents and Settings\\User\\test.py>
In [6]:
C: is the local hard drive on the machine. Z: is our network-attached storage.
| [
"I believe the problem is related to:\nhttp://support.microsoft.com/default.aspx?scid=kb;en-us;899149\n...so, just try:\nopen(r'z:\\test.bin','w+b').write('a'*67080064)\n*Note the argument: 'w+b'\n"
] | [
16
] | [] | [] | [
"ioerror",
"nas",
"pickle",
"python"
] | stackoverflow_0004226941_ioerror_nas_pickle_python.txt |
Q:
how can i select these elements from the following horrible html using xpath and lxml?
i want to select the following strings from this html using just lxml and some clever xpath. The strings will change but the surrounding html will not.
i need...
19/11/2010
AAAAAA/01
Normal
United Kingdom
This description may contains <bold>html</bold> but i still need all of it!
from...
...
<p>
<strong>Date:</strong> 19/11/2010<br>
<strong>Ref:</strong> AAAAAA/01<br>
<b>Type:</b> Normal<br>
<b>Country:</b> United Kingdom<br>
</p>
<hr>
<p>
<br>
<b>1. Title:</b> The Title<br>
<b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br>
<b>3. Date:</b> 25th October<br>
...
</p>
...
So far i've only come up with using regex expressions and re:match to try and drag it out, but even that won't work without something which enables me to get innerHTML of a the <p> nodes for exapmle.
is there any way to do this without post-processing the string through regex?
Thanks :)
A:
Very ugly! With this properly wellformed input:
<html>
<p>
<strong>Date:</strong> 19/11/2010<br/>
<strong>Ref:</strong> AAAAAA/01<br/>
<b>Type:</b> Normal<br/>
<b>Country:</b> United Kingdom<br/>
</p>
<hr/>
<p>
<br/>
<b>1. Title:</b> The Title<br/>
<b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br/>
<b>3. Date:</b> 25th October<br/>
</p>
</html>
Simplest case:
/html/p/strong[.='Date:']/following-sibling::text()[1]
Evaluate to:
19/11/2010
All of those in one:
/html/p/*[self::strong[.='Date:' or .='Ref:']|
self::b[.='Type:' or .='Country:']]
/following-sibling::text()[1]
The complex one:
/html/p/node()[preceding-sibling::b[1][.='2. Description: ']]
[following-sibling::b[1][.='3. Date:']]
[not(self::br)]
A:
This isn't so difficult.
Given this XML document:
<html>
<p>
<strong>Date:</strong> 19/11/2010<br/>
<strong>Ref:</strong> AAAAAA/01<br/>
<b>Type:</b> Normal<br/>
<b>Country:</b> United Kingdom<br/>
</p>
<hr/>
<p>
<br/>
<b>1. Title:</b> The Title<br/>
<b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br/>
<b>3. Date:</b> 25th October<br/>
</p>
</html>
i need...
19/11/2010
AAAAAA/01
Normal
United Kingdom
this XPath expression selects all of the above text nodes:
/*/p[1]/text()
This description may contains html but i still need all
of it!
Use this:
/*/p[2]/b[2]/following-sibling::node()
[count(.|/*/p[2]/b[2]/following-sibling::br[1]/preceding-sibling::node())
=
count((/*/p[2]/b[2]/following-sibling::br[1]/preceding-sibling::node()))
]
| how can i select these elements from the following horrible html using xpath and lxml? | i want to select the following strings from this html using just lxml and some clever xpath. The strings will change but the surrounding html will not.
i need...
19/11/2010
AAAAAA/01
Normal
United Kingdom
This description may contains <bold>html</bold> but i still need all of it!
from...
...
<p>
<strong>Date:</strong> 19/11/2010<br>
<strong>Ref:</strong> AAAAAA/01<br>
<b>Type:</b> Normal<br>
<b>Country:</b> United Kingdom<br>
</p>
<hr>
<p>
<br>
<b>1. Title:</b> The Title<br>
<b>2. Description: </b> This description may contains <bold>html</bold> but i still need all of it!<br>
<b>3. Date:</b> 25th October<br>
...
</p>
...
So far i've only come up with using regex expressions and re:match to try and drag it out, but even that won't work without something which enables me to get innerHTML of a the <p> nodes for exapmle.
is there any way to do this without post-processing the string through regex?
Thanks :)
| [
"Very ugly! With this properly wellformed input:\n<html>\n<p>\n <strong>Date:</strong> 19/11/2010<br/>\n <strong>Ref:</strong> AAAAAA/01<br/>\n <b>Type:</b> Normal<br/>\n <b>Country:</b> United Kingdom<br/>\n</p>\n<hr/>\n<p>\n <br/>\n <b>1. Title:</b> The Title<br/>\n <b>2. Description: </b> Th... | [
2,
0
] | [] | [] | [
"html",
"lxml",
"python",
"xpath"
] | stackoverflow_0004227303_html_lxml_python_xpath.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.