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:
Why are certain elements of this python list ignored?
I'm new to Python, and i'm struggling to understand the output of this simple program:
list = os.listdir(os.getcwd())
print(list)
print()
for element in list:
print(element)
if 'txt' not in element: list.remove(element)
Which gives me this output :
['examples_list.txt', 'generate_patterns.py', 'lehoczky_example_3.txt', 'patterns', 'test.py', 'test2.py']
examples_list.txt
generate_patterns.py
patterns
test2.py
why are certain elements (such as 'lehoczky_example_3.txt'), ignored by the "for" loop?
A:
You cannot remove elements from the list while looping through it. Try and loop over a copy of the list, or create a new one with only the elements you want to keep.
See also Python strange behavior in for loop or lists
A:
Try list comprehension. This will keep your list of files and create a new list noTxtFiles without touching the files.
files = os.listdir(os.getcwd())
noTxtFiles = [ element for element in files if 'txt' not in element ]
And don't use the reserved word list for a variable name.
| Why are certain elements of this python list ignored? | I'm new to Python, and i'm struggling to understand the output of this simple program:
list = os.listdir(os.getcwd())
print(list)
print()
for element in list:
print(element)
if 'txt' not in element: list.remove(element)
Which gives me this output :
['examples_list.txt', 'generate_patterns.py', 'lehoczky_example_3.txt', 'patterns', 'test.py', 'test2.py']
examples_list.txt
generate_patterns.py
patterns
test2.py
why are certain elements (such as 'lehoczky_example_3.txt'), ignored by the "for" loop?
| [
"You cannot remove elements from the list while looping through it. Try and loop over a copy of the list, or create a new one with only the elements you want to keep.\nSee also Python strange behavior in for loop or lists\n",
"Try list comprehension. This will keep your list of files and create a new list noTxtFi... | [
10,
5
] | [] | [] | [
"python"
] | stackoverflow_0004023739_python.txt |
Q:
since X variables are in a list, call a function with X parameters
I have mylist = [var1, var2, var3... varn].
os.path.join is called not one list, but with many vars.
I can't call os.path.join(mylist).
How to call os.path.join(var1, var2, var3... varn)?
A:
Try:
os.path.join(*mylist)
| since X variables are in a list, call a function with X parameters | I have mylist = [var1, var2, var3... varn].
os.path.join is called not one list, but with many vars.
I can't call os.path.join(mylist).
How to call os.path.join(var1, var2, var3... varn)?
| [
"Try:\nos.path.join(*mylist)\n\n"
] | [
11
] | [] | [] | [
"python"
] | stackoverflow_0004024156_python.txt |
Q:
How to get source line number from a Python generator object?
Here is an example:
def g():
yield str('123')
yield int(123)
yield str('123')
o = g()
while True:
v = o.next()
if isinstance( v, str ):
print 'Many thanks to our generator...'
else:
# Or GOD! I don't know what to do with this type
raise TypeError( '%s:%d Unknown yield value type %s.' % \
(g.__filename__(), g.__lineno__(), type(v) )
)
How do I get the source file name and the exact yield line number, when my generator returns unknown type (int in this example)?
A:
Your generator object "o" in this case has all the information you want. You can paste your example into a Python console, and inspect with dir both the function "g" and the generator "o".
The generator has the attributes "gi_code" and "gi_frame" which contain the information you want:
>>> o.gi_code.co_filename
'<stdin>'
# this is the line number inside the file:
>>> o.gi_code.co_firstlineno
1
# and this is the current line number inside the function:
>>> o.gi_frame.f_lineno
3
| How to get source line number from a Python generator object? | Here is an example:
def g():
yield str('123')
yield int(123)
yield str('123')
o = g()
while True:
v = o.next()
if isinstance( v, str ):
print 'Many thanks to our generator...'
else:
# Or GOD! I don't know what to do with this type
raise TypeError( '%s:%d Unknown yield value type %s.' % \
(g.__filename__(), g.__lineno__(), type(v) )
)
How do I get the source file name and the exact yield line number, when my generator returns unknown type (int in this example)?
| [
"Your generator object \"o\" in this case has all the information you want. You can paste your example into a Python console, and inspect with dir both the function \"g\" and the generator \"o\".\nThe generator has the attributes \"gi_code\" and \"gi_frame\" which contain the information you want:\n>>> o.gi_code.co... | [
8
] | [
"I don't think you can get the information you want. That's the sort of thing captured in exceptions, but there has been no exception here.\n"
] | [
-2
] | [
"generator",
"python"
] | stackoverflow_0004024609_generator_python.txt |
Q:
How to parse multiple XML documents from a single stream?
I've got a socket from which I'm reading XML data. However, this socket will spit out multiple different XML documents, so I can't simply parse all the output I receive.
Is there a good way, preferably using the Python standard library, for me to parse multiple XML documents? In other words, if I end up getting
<foo/>
<bar/>
then is there a way to either get multiple DOM objects or have a SAX parser simply work on such a stream?
A:
If you get separate documents, you'll need something to divide them; and if you have that, you can simply split the stream before you parse the individual documents.
Another possibility would be to wrap that into another document, so each XML document is actually a subdocument of a parent's you create (and wrap around) just for that purpose.
| How to parse multiple XML documents from a single stream? | I've got a socket from which I'm reading XML data. However, this socket will spit out multiple different XML documents, so I can't simply parse all the output I receive.
Is there a good way, preferably using the Python standard library, for me to parse multiple XML documents? In other words, if I end up getting
<foo/>
<bar/>
then is there a way to either get multiple DOM objects or have a SAX parser simply work on such a stream?
| [
"If you get separate documents, you'll need something to divide them; and if you have that, you can simply split the stream before you parse the individual documents.\nAnother possibility would be to wrap that into another document, so each XML document is actually a subdocument of a parent's you create (and wrap a... | [
4
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004024739_python_xml.txt |
Q:
Change the bpm of a song while playing it in python
i'am looking for a way to attune a song to the heart rate of someone.
I have a song in mp3 or wav format and i want to accelerate the speed of it while playing it.
Or playing it in loop and between each loop accelerate it or slow it.
Ideally it will be in python.
Do you know a way to do that ?
Regards and thanks.
Bussiere
A:
There are a few different pieces here, each of which needs to be solved. None of them are trivial and require a decent amount of signal processing knowledge, so you'll probably want to look for libraries to handle that part of the heavy lifting.
Cardiac beat detection. This is outside my area of knowledge, but let's assume that you can access this somehow.
Music beat detection There are several libraries available for this, both commercial and open source. You may want to look at http://aubio.org/ -- it already has python bindings available.
Tempo Change -- Once you know the target BPM and the current BPM, you need another library that can be used to change the tempo of your audio track to match (without changing the pitch). A few to look at are Rubber Band and SoundTouch
Googling will find other libraries for these manipulations (and other pieces that you'll need, something like PyMedia to open and playback the sounds, etc.)
A:
maybe one piece of software that can allow you to control the tempo of some ongoing audio using another input is "Puredata" --
It is a very complete, although complicated, node based software aimed to deal with various multimidia transformations from visual node connections - but it can also be programed through a Python API
http://crca.ucsd.edu/~msp/Pd_documentation/index.htm
Python bindings:
http://mccormick.cx/projects/PyPd/
| Change the bpm of a song while playing it in python | i'am looking for a way to attune a song to the heart rate of someone.
I have a song in mp3 or wav format and i want to accelerate the speed of it while playing it.
Or playing it in loop and between each loop accelerate it or slow it.
Ideally it will be in python.
Do you know a way to do that ?
Regards and thanks.
Bussiere
| [
"There are a few different pieces here, each of which needs to be solved. None of them are trivial and require a decent amount of signal processing knowledge, so you'll probably want to look for libraries to handle that part of the heavy lifting.\n\nCardiac beat detection. This is outside my area of knowledge, but ... | [
4,
2
] | [] | [] | [
"audio",
"audio_processing",
"controls",
"python"
] | stackoverflow_0004024389_audio_audio_processing_controls_python.txt |
Q:
why doesn't (list1[-1]+=list2.pop(0))+=list2 work in Python?
I have two lists of strings that, in a better world, would be one list. I need to concatenate the lists, but the last element of the first list needs to be concatenated with the first element of the second list. So these guys:
list1 = ["bob", "sal"]
list2 = ["ly", "nigel"]
needs to become
out = ["bob", "sally", "nigel"]
So this isn't hard, but I'm wondering why my one liner doesn't work?
out = (list1[-1] += list2.pop(0)) += list2
Why isn't this equivalent to
out = list1[-1]+=list2.pop(0)
out += list2
?
I have to do this a large percentage of the time through some 400K records. So if anyone has a better way to do this, then I'd be grateful!
A:
Remove all those += operators, they don't make sense here. If you want to use them as a replacement for a.extend(b), then remember, that they cannot be used as an expression. This command modifies the a list, but does not return anything. So c = a.extend(b) gives nothing to c.
Try this instead (it even does not modify original lists!):
out = list1[:-1] + [ list1[-1] + list2[0] ] + list2[1:]
returns what you want.
list1[:-1] is a list from list1 without the last element.
list1[-1] is the last element from list1.
list2[0] is the first element from list2.
list1[-1] + list2[0] is a concatenated string.
[ list1[-1] + list2[0] ] is a list with one element (concatenated string).
list2[1:] is a list from list2 without the first element.
A:
Assignments in Python are not operators that can be used within expressions. They are statement-level syntax.
A:
If you want a one-liner, here's what I'd do:
(','.join(list1)+','.join(list2)).split(',')
A:
Apart of @eumiros answer, on what is happening there, you can acomplish what you want
in a single statement with:
out = list1[:-1] + [list1[-1] + list2[0]] + list2[1:]
"There should be one-- and preferably only one --obvious way to do it."
A:
I would not normally leave broken pieces of data around but would fix in place:
>>> list1 = ["bob", "sal"]
>>> list2 = ["ly", "nigel"]
>>> fix = [list1.pop()+list2.pop(0)]
>>> list1
['bob']
>>> fix
['sally']
>>> list2
['nigel']
>>> fixed = list1 + fix + list2
>>> fixed
['bob', 'sally', 'nigel']
Same time getting rid of those obvious list1 and list2 variable names with something readable.
| why doesn't (list1[-1]+=list2.pop(0))+=list2 work in Python? | I have two lists of strings that, in a better world, would be one list. I need to concatenate the lists, but the last element of the first list needs to be concatenated with the first element of the second list. So these guys:
list1 = ["bob", "sal"]
list2 = ["ly", "nigel"]
needs to become
out = ["bob", "sally", "nigel"]
So this isn't hard, but I'm wondering why my one liner doesn't work?
out = (list1[-1] += list2.pop(0)) += list2
Why isn't this equivalent to
out = list1[-1]+=list2.pop(0)
out += list2
?
I have to do this a large percentage of the time through some 400K records. So if anyone has a better way to do this, then I'd be grateful!
| [
"Remove all those += operators, they don't make sense here. If you want to use them as a replacement for a.extend(b), then remember, that they cannot be used as an expression. This command modifies the a list, but does not return anything. So c = a.extend(b) gives nothing to c.\nTry this instead (it even does not m... | [
10,
3,
0,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004024339_list_python.txt |
Q:
PyGtk Program is not responding on Windows
I just managed to get py2exe work on a Windows Virtual Machine but stumbled on another problem which I didn't have right after I installed GTK, Pango, Gobject etc. on that machine: When I launch a Python Script the window appears but it immediately stops responding. This happens too if I open a python interpreter and type:
import gtk
w = gtk.Window()
w.show()
I'm not allowed to post any images yet, but here's the link to a screenshot: http://i.stack.imgur.com/3RJ0n.png
This is a problem for me, as if I create an executable with py2exe I get the same result when I execute the program.
Thank you for your help and for your time spent to help me! :)
Solved! It seems installing ActivePython the installing GTK runtime, PyCairo, PyObject, PyGtk as administrator with compatibility mode for Windows Xp Service Pack 2 solved the problem. Thank you adw for your help and suggestions!
A:
You need to run a main loop so GTK can process events, draw in the window, etc.
Add this to your program:
gtk.main()
See also: http://live.gnome.org/PyGTK/QuickStart
A:
Solved! It seems installing ActivePython the installing GTK runtime, PyCairo, PyObject, PyGtk as administrator with compatibility mode for Windows Xp Service Pack 2 solved the problem. Thank you adw for your help and suggestions!
| PyGtk Program is not responding on Windows | I just managed to get py2exe work on a Windows Virtual Machine but stumbled on another problem which I didn't have right after I installed GTK, Pango, Gobject etc. on that machine: When I launch a Python Script the window appears but it immediately stops responding. This happens too if I open a python interpreter and type:
import gtk
w = gtk.Window()
w.show()
I'm not allowed to post any images yet, but here's the link to a screenshot: http://i.stack.imgur.com/3RJ0n.png
This is a problem for me, as if I create an executable with py2exe I get the same result when I execute the program.
Thank you for your help and for your time spent to help me! :)
Solved! It seems installing ActivePython the installing GTK runtime, PyCairo, PyObject, PyGtk as administrator with compatibility mode for Windows Xp Service Pack 2 solved the problem. Thank you adw for your help and suggestions!
| [
"You need to run a main loop so GTK can process events, draw in the window, etc.\nAdd this to your program:\ngtk.main()\n\nSee also: http://live.gnome.org/PyGTK/QuickStart\n",
"Solved! It seems installing ActivePython the installing GTK runtime, PyCairo, PyObject, PyGtk as administrator with compatibility mode fo... | [
2,
1
] | [] | [] | [
"py2exe",
"pygtk",
"python",
"windows"
] | stackoverflow_0004009566_py2exe_pygtk_python_windows.txt |
Q:
Average the duplicated values from two paired lists in Python
in my code I obtain two different lists from different sources, but I know they are in the same order. The first list ("names") contains a list of keys strings, while the second ("result_values") is a series of floats. I need to make the pair unique, but I can't use a dictionary as only the last value inserted would be kept: instead, I need to make an average (arithmetic mean) of the values that have a duplicate key.
Example of the wanted results:
names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6] # ints here but it's the same conceptually
combined_result = average_duplicates(names, result_values)
print combined_result
{"pears": 4, "apples": 1, "bananas": 8}
My only ideas involve multiple iterations and so far have been ugly... is there an elegant solution to this problem?
A:
from collections import defaultdict
def averages(names, values):
# Group the items by name.
value_lists = defaultdict(list)
for name, value in zip(names, values):
value_lists[name].append(value)
# Take the average of each list.
result = {}
for name, values in value_lists.iteritems():
result[name] = sum(values) / float(len(values))
return result
names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6]
print averages(names, result_values)
A:
I would use a dictionary anyways
averages = {}
counts = {}
for name, value in zip(names, result_values):
if name in averages:
averages[name] += value
counts[name] += 1
else:
averages[name] = value
counts[name] = 1
for name in averages:
averages[name] = averages[name]/float(counts[name])
If you're concerned with large lists, then I would replace zip with izip from itertools.
A:
You could calculate the mean using a Cumulative moving average to only iterate through the lists once:
from collections import defaultdict
averages = defaultdict(float)
count = defaultdict(int)
for name,result in zip(names,result_values):
count[name] += 1
averages[name] += (result - averages[name]) / count[name]
A:
I think what you're looking for is itertools.groupby:
import itertools
def average_duplicates(names, values):
pairs = sorted(zip(names, values))
result = {}
for key, group in itertools.groupby(pairs, key=lambda p: p[0]):
group_values = [value for (_, value) in group]
result[key] = sum(group_values) / len(group_values)
return result
See also zip and sorted.
A:
>>> def avg_list(keys, values):
... def avg(series):
... return sum(series) / len(series)
... from collections import defaultdict
... d = defaultdict(list)
... for k, v in zip(keys, values):
... d[k].append(v)
... return dict((k, avg(v)) for k, v in d.iteritems())
...
>>> if __name__ == '__main__':
... names = ["pears", "apples", "pears", "bananas", "pears"]
... result_values = [2, 1, 4, 8, 6]
... print avg_list(names, result_values)
...
{'apples': 1, 'pears': 4, 'bananas': 8}
You can have avg() return float(len(series)) if you want a floating point average.
| Average the duplicated values from two paired lists in Python | in my code I obtain two different lists from different sources, but I know they are in the same order. The first list ("names") contains a list of keys strings, while the second ("result_values") is a series of floats. I need to make the pair unique, but I can't use a dictionary as only the last value inserted would be kept: instead, I need to make an average (arithmetic mean) of the values that have a duplicate key.
Example of the wanted results:
names = ["pears", "apples", "pears", "bananas", "pears"]
result_values = [2, 1, 4, 8, 6] # ints here but it's the same conceptually
combined_result = average_duplicates(names, result_values)
print combined_result
{"pears": 4, "apples": 1, "bananas": 8}
My only ideas involve multiple iterations and so far have been ugly... is there an elegant solution to this problem?
| [
"from collections import defaultdict\ndef averages(names, values):\n # Group the items by name.\n value_lists = defaultdict(list)\n for name, value in zip(names, values):\n value_lists[name].append(value)\n\n # Take the average of each list.\n result = {}\n for name, values in value_lists.i... | [
5,
3,
3,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004022465_list_python.txt |
Q:
Pylons FormEncode with an array of form elements
I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)
<tr>
<td>Yardage</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
</tr>
However, I can't seem to figure out how to validate these fields.
Here is the relevant entry from my Schema
yardage = formencode.ForEach(formencode.validators.Int())
I'm trying to validate that each of these fields is an Int.
However, no validation occurs for these fields.
UPDATE
As requested here is the code for the action of this controller. I know it was working as I can validate other form fields.
def submit(self):
schema = CourseForm()
try:
c.form_result = schema.to_python(dict(request.params))
except formencode.Invalid, error:
c.form_result = error.value
c.form_errors = error.error_dict or {}
c.heading = 'Add a course'
html = render('/derived/course/add.html')
return htmlfill.render(
html,
defaults = c.form_result,
errors = c.form_errors
)
else:
h.redirect_to(controler='course', action='view')
UPDATE
It was suggested on IRC that I change the name of the elements from yardage[] to yardage
No result. They should all be ints but putting in f into one of the elements doesn't cause it to be invalid. As I said before, I am able to validate other form fields. Below is my entire schema.
import formencode
class CourseForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'})
par = formencode.ForEach(formencode.validators.Int())
yardage = formencode.ForEach(formencode.validators.Int())
A:
Turns out what I wanted to do wasn't quite right.
Template:
<tr>
<td>Yardage</td>
% for hole in range(9):
<td>${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}</td>
% endfor
</tr>
(Should have made it in a loop to begin with.) You'll notice that the name of the first element will become hole-1.yardage. I will then use FormEncode.variabledecode to turn this into a dictionary. This is done in the
Schema:
import formencode
class HoleSchema(formencode.Schema):
allow_extra_fields = False
yardage = formencode.validators.Int(not_empty=True)
par = formencode.validators.Int(not_empty=True)
class CourseForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'})
hole = formencode.ForEach(HoleSchema())
The HoleSchema will validate that hole-#.par and hole-#.yardage are both ints and are not empty. formencode.ForEach allows me to apply HoleSchema to the dictionary that I get from passing variable_decode=True to the @validate decorator.
Here is the submit action from my
Controller:
@validate(schema=CourseForm(), form='add', post_only=False, on_get=True,
auto_error_formatter=custom_formatter,
variable_decode=True)
def submit(self):
# Do whatever here.
return 'Submitted!'
Using the @validate decorator allows for a much cleaner way to validate and fill in the forms. The variable_decode=True is very important or the dictionary will not be properly created.
A:
c.form_result = schema.to_python(request.params) - (without dict)
It seems to works fine.
| Pylons FormEncode with an array of form elements | I have a Pylons app and am using FormEncode and HtmlFill to handle my forms. I have an array of text fields in my template (Mako)
<tr>
<td>Yardage</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
<td>${h.text('yardage[]', maxlength=3, size=3)}</td>
</tr>
However, I can't seem to figure out how to validate these fields.
Here is the relevant entry from my Schema
yardage = formencode.ForEach(formencode.validators.Int())
I'm trying to validate that each of these fields is an Int.
However, no validation occurs for these fields.
UPDATE
As requested here is the code for the action of this controller. I know it was working as I can validate other form fields.
def submit(self):
schema = CourseForm()
try:
c.form_result = schema.to_python(dict(request.params))
except formencode.Invalid, error:
c.form_result = error.value
c.form_errors = error.error_dict or {}
c.heading = 'Add a course'
html = render('/derived/course/add.html')
return htmlfill.render(
html,
defaults = c.form_result,
errors = c.form_errors
)
else:
h.redirect_to(controler='course', action='view')
UPDATE
It was suggested on IRC that I change the name of the elements from yardage[] to yardage
No result. They should all be ints but putting in f into one of the elements doesn't cause it to be invalid. As I said before, I am able to validate other form fields. Below is my entire schema.
import formencode
class CourseForm(formencode.Schema):
allow_extra_fields = True
filter_extra_fields = True
name = formencode.validators.NotEmpty(messages={'empty': 'Name must not be empty'})
par = formencode.ForEach(formencode.validators.Int())
yardage = formencode.ForEach(formencode.validators.Int())
| [
"Turns out what I wanted to do wasn't quite right. \nTemplate:\n<tr>\n <td>Yardage</td>\n % for hole in range(9):\n <td>${h.text('hole-%s.yardage'%(hole), maxlength=3, size=3)}</td>\n % endfor\n</tr>\n\n(Should have made it in a loop to begin with.) You'll notice that the name of the first element will become h... | [
5,
1
] | [] | [] | [
"formencode",
"htmlfill",
"pylons",
"python"
] | stackoverflow_0000994460_formencode_htmlfill_pylons_python.txt |
Q:
Selecting only text within a div tag
I'm working on a web parser using urllib. I need to be able to only save lines that lie within a certain div tag. for instance: I'm saving all text in the div "body." This means all text within the div tags will be returned. It also means if there are other divs inside of it thats fine, but as soon as I hit the parent it stops. Any ideas?
My Idea
search for the div you're looking
for.
Record the position.
Keep track of any divs in the
future. +1 for new div -1 for end
div.
when back to 0, your at your parent
div? Save location.
Then save data from beginnning
number to end number?
A:
If you're not really excited at the idea of parsing the HTML code yourself, there are two good options:
Beautiful Soup
Lxml
You'll probably find that lxml runs faster than BeautifulSoup, but in my uses, Beautiful Soup was very easy to learn and use, and handled typical crappy HTML as found in the wild well enough that I don't have need for anything else.
YMMV.
A:
Using lxml:
import lxml.html as lh
content='''\
<body>
<div>AAAA
<div>BBBB
<div>CCCC
</div>DDDD
</div>EEEE
</div>FFFF
</body>
'''
doc=lh.document_fromstring(content)
div=doc.xpath('./body/div')[0]
print(div.text_content())
# AAAA
# BBBB
# CCCC
# DDDD
# EEEE
div=doc.xpath('./body/div/div')[0]
print(div.text_content())
# BBBB
# CCCC
# DDDD
A:
Personally I prefer lxml in general, but there are times where it's HTML handling is a bit off... Here's a BeautifulSoup recipe if it helps.
from BeautifulSoup import BeautifulSoup, NavigableString
def printText(tags):
s = []
for tag in tags :
if tag.__class__ == NavigableString :
s.append(tag)
else :
s.append(printText(tag))
return "".join(s)
html = "<html><p>Para 1<div class='stuff'>Div Lead<p>Para 2<blockquote>Quote 1</div><blockquote>Quote 2"
soup = BeautifulSoup(html)
v = soup.find('div', attrs={ 'class': 'stuff'})
print v.text_content
| Selecting only text within a div tag | I'm working on a web parser using urllib. I need to be able to only save lines that lie within a certain div tag. for instance: I'm saving all text in the div "body." This means all text within the div tags will be returned. It also means if there are other divs inside of it thats fine, but as soon as I hit the parent it stops. Any ideas?
My Idea
search for the div you're looking
for.
Record the position.
Keep track of any divs in the
future. +1 for new div -1 for end
div.
when back to 0, your at your parent
div? Save location.
Then save data from beginnning
number to end number?
| [
"If you're not really excited at the idea of parsing the HTML code yourself, there are two good options:\nBeautiful Soup \nLxml\nYou'll probably find that lxml runs faster than BeautifulSoup, but in my uses, Beautiful Soup was very easy to learn and use, and handled typical crappy HTML as found in the wild well eno... | [
3,
3,
0
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0004025181_python_urllib.txt |
Q:
Show pdf only to authenticated users
I'm building a web site from the old one and i need to show a lot of .pdf files.
I need users to get authenficated before the can't see any of my .pdf but i don't know how (and i can't put my pdf in my database).
I'm using Pylons with Python.
Thank for you help.
If you have any question, ask me! :)
A:
Here's my stab at how to do it in Pylons. I haven't tested this but there should be enough links to get you going.
Enable X-SendFile on your HTTP server (as Paul said, the implementation depends on the server): Apache mod_xsendfile, Nginx equivalent
Put the PDFs outside the /public directory in your Pylons install (I'd suggest a directory at the same level as your Pylons directory)
Add some kind of Authentication and Authorization to your site. Here is a good article on how you use repoze.who (Authentication) and repoze.what (Authorization)
Create a route and controller to handle the request for your PDF, this is like any other route and controller. (ie a route of /pdfs/{filename}.pdf)
If everything is authorized and authenticated properly you can create the right headers for the x-sendfile (or equivalent) you are using.
A:
You want to use the X-Sendfile header to send those files. Precise details will depend on which Http server you're using.
A:
Paul's suggestion of X-Sendfile is excellent - this is truly a great way to deal with actually getting the document back to the user. (+1 for Paul :)
As for the front end, do something like this:
Store your pdfs somewhere not accessible by the web (say /secure)
Offer a URL that looks like /unsecure/filename.pdf
Have your HTTP server (if it's Apache, see Mod Rewrite) convert that link into /normal/php/path/authenticator.php?file=filename.pdf
authenticator.php confirms that the file exists, that the user is legit (i.e. via a cookie), and then uses X-Sendfile to return the PDF.
A:
Maybe filename with md5 key will be enough?
48cd84ab06b0a18f3b6e024703cfd246-myfilename.pdf
You can use filename and datetime.now to generate md5 key.
| Show pdf only to authenticated users | I'm building a web site from the old one and i need to show a lot of .pdf files.
I need users to get authenficated before the can't see any of my .pdf but i don't know how (and i can't put my pdf in my database).
I'm using Pylons with Python.
Thank for you help.
If you have any question, ask me! :)
| [
"Here's my stab at how to do it in Pylons. I haven't tested this but there should be enough links to get you going.\n\nEnable X-SendFile on your HTTP server (as Paul said, the implementation depends on the server): Apache mod_xsendfile, Nginx equivalent\nPut the PDFs outside the /public directory in your Pylons ins... | [
4,
2,
2,
0
] | [] | [] | [
"html",
"pdf",
"permissions",
"pylons",
"python"
] | stackoverflow_0003980878_html_pdf_permissions_pylons_python.txt |
Q:
Django MultiWidget Phone Number Field
I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common "(" ")" "-" delimiters. Below is my code for the field and the widget, I'm getting the following error when trying to iterate the fields in my form during initial rendering (it happens when the for loop gets to my phone number field):
Caught an exception while rendering: 'NoneType' object is unsubscriptable
class PhoneNumberWidget(forms.MultiWidget):
def __init__(self,attrs=None):
wigs = (forms.TextInput(attrs={'size':'3','maxlength':'3'}),\
forms.TextInput(attrs={'size':'3','maxlength':'3'}),\
forms.TextInput(attrs={'size':'4','maxlength':'4'}))
super(PhoneNumberWidget, self).__init__(wigs, attrs)
def decompress(self, value):
return value or None
def format_output(self, rendered_widgets):
return '('+rendered_widgets[0]+')'+rendered_widgets[1]+'-'+rendered_widgets[2]
class PhoneNumberField(forms.MultiValueField):
widget = PhoneNumberWidget
def __init__(self, *args, **kwargs):
fields=(forms.CharField(max_length=3), forms.CharField(max_length=3), forms.CharField(max_length=4))
super(PhoneNumberField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
if data_list[0] in fields.EMPTY_VALUES or data_list[1] in fields.EMPTY_VALUES or data_list[2] in fields.EMPTY_VALUES:
raise fields.ValidateError(u'Enter valid phone number')
return data_list[0]+data_list[1]+data_list[2]
class AdvertiserSumbissionForm(ModelForm):
business_phone_number = PhoneNumberField(required=True)
A:
This uses widget.value_from_datadict() to format the data so no need to subclass a field, just use the existing USPhoneNumberField. Data is stored in db like XXX-XXX-XXXX.
from django import forms
class USPhoneNumberMultiWidget(forms.MultiWidget):
"""
A Widget that splits US Phone number input into three <input type='text'> boxes.
"""
def __init__(self,attrs=None):
widgets = (
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'4','maxlength':'4', 'class':'phone'}),
)
super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return value.split('-')
return (None,None,None)
def value_from_datadict(self, data, files, name):
value = [u'',u'',u'']
# look for keys like name_1, get the index from the end
# and make a new list for the string replacement values
for d in filter(lambda x: x.startswith(name), data):
index = int(d[len(name)+1:])
value[index] = data[d]
if value[0] == value[1] == value[2] == u'':
return None
return u'%s-%s-%s' % tuple(value)
use in a form like so:
from django.contrib.localflavor.us.forms import USPhoneNumberField
class MyForm(forms.Form):
phone = USPhoneNumberField(label="Phone", widget=USPhoneNumberMultiWidget())
A:
I think the value_from_datadict() code can be simplified to:
class USPhoneNumberMultiWidget(forms.MultiWidget):
"""
A Widget that splits US Phone number input into three boxes.
"""
def __init__(self,attrs=None):
widgets = (
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'3','maxlength':'3', 'class':'phone'}),
forms.TextInput(attrs={'size':'4','maxlength':'4', 'class':'phone'}),
)
super(USPhoneNumberMultiWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return value.split('-')
return [None,None,None]
def value_from_datadict(self, data, files, name):
values = super(USPhoneNumberMultiWidget, self).value_from_datadict(data, files, name)
return u'%s-%s-%s' % values
The value_from_datadict() method for MultiValueWidget already does the following:
def value_from_datadict(self, data, files, name):
return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)]
A:
I took hughdbrown's advise and modified USPhoneNumberField to do what I need. The reason I didn't use it initially was that it stores phone numbers as XXX-XXX-XXXX in the DB, I store them as XXXXXXXXXX. So I over-rode the clean method:
class PhoneNumberField(USPhoneNumberField):
def clean(self, value):
super(USPhoneNumberField, self).clean(value)
if value in EMPTY_VALUES:
return u''
value = re.sub('(\(|\)|\s+)', '', smart_unicode(value))
m = phone_digits_re.search(value)
if m:
return u'%s%s%s' % (m.group(1), m.group(2), m.group(3))
raise ValidationError(self.error_messages['invalid'])
A:
Sometimes it is useful to fix the original problem rather than redoing everything. The error you got, "Caught an exception while rendering: 'NoneType' object is unsubscriptable" has a clue. There is a value returned as None(unsubscriptable) when a subscriptable value is expected. The decompress function in PhoneNumberWidget class is a likely culprit. I would suggest returning [] instead of None.
| Django MultiWidget Phone Number Field | I want to create a field for phone number input that has 2 text fields (size 3, 3, and 4 respectively) with the common "(" ")" "-" delimiters. Below is my code for the field and the widget, I'm getting the following error when trying to iterate the fields in my form during initial rendering (it happens when the for loop gets to my phone number field):
Caught an exception while rendering: 'NoneType' object is unsubscriptable
class PhoneNumberWidget(forms.MultiWidget):
def __init__(self,attrs=None):
wigs = (forms.TextInput(attrs={'size':'3','maxlength':'3'}),\
forms.TextInput(attrs={'size':'3','maxlength':'3'}),\
forms.TextInput(attrs={'size':'4','maxlength':'4'}))
super(PhoneNumberWidget, self).__init__(wigs, attrs)
def decompress(self, value):
return value or None
def format_output(self, rendered_widgets):
return '('+rendered_widgets[0]+')'+rendered_widgets[1]+'-'+rendered_widgets[2]
class PhoneNumberField(forms.MultiValueField):
widget = PhoneNumberWidget
def __init__(self, *args, **kwargs):
fields=(forms.CharField(max_length=3), forms.CharField(max_length=3), forms.CharField(max_length=4))
super(PhoneNumberField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
if data_list[0] in fields.EMPTY_VALUES or data_list[1] in fields.EMPTY_VALUES or data_list[2] in fields.EMPTY_VALUES:
raise fields.ValidateError(u'Enter valid phone number')
return data_list[0]+data_list[1]+data_list[2]
class AdvertiserSumbissionForm(ModelForm):
business_phone_number = PhoneNumberField(required=True)
| [
"This uses widget.value_from_datadict() to format the data so no need to subclass a field, just use the existing USPhoneNumberField. Data is stored in db like XXX-XXX-XXXX.\nfrom django import forms\n\nclass USPhoneNumberMultiWidget(forms.MultiWidget):\n \"\"\"\n A Widget that splits US Phone number input int... | [
6,
4,
1,
0
] | [] | [] | [
"django_forms",
"django_models",
"django_templates",
"django_widget",
"python"
] | stackoverflow_0001777435_django_forms_django_models_django_templates_django_widget_python.txt |
Q:
(Python) How can I print a variable to a Tweepy "API.update_status()" command?
I am trying to add some information to a python script that posts the information to twitter. Here is the code so far:
#!/usr/bin/python
import os
import subprocess
import psutil
import sys
import tweepy
#----------------------------------------
# Gives a human-readable uptime string
def uptime():
try:
f = open( "/proc/uptime" )
contents = f.read().split()
f.close()
except:
return "Cannot open uptime file: /proc/uptime"
total_seconds = float(contents[0])
# Helper vars:
MINUTE = 60
HOUR = MINUTE * 60
DAY = HOUR * 24
# Get the days, hours, etc:
days = int( total_seconds / DAY )
hours = int( ( total_seconds % DAY ) / HOUR )
minutes = int( ( total_seconds % HOUR ) / MINUTE )
seconds = int( total_seconds % MINUTE )
# Build up the pretty string (like this: "N days, N hours, N minutes, N seconds")
string = ""
if days> 0:
string += str(days) + " " + (days == 1 and "day" or "days" ) + ", "
if len(string)> 0 or hours> 0:
string += str(hours) + " " + (hours == 1 and "hour" or "hours" ) + ", "
if len(string)> 0 or minutes> 0:
string += str(minutes) + " " + (minutes == 1 and "minute" or "minutes" ) + ", "
string += str(seconds) + " " + (seconds == 1 and "second" or "seconds" )
return string;
uptime() = time
psutil.Process(2360).get_memory_percent() = Mem
##Twitter Auth Stuff##
CONSUMER_KEY = 'blahblah'
CONSUMER_SECRET = 'edited because'
ACCESS_KEY = 'this is'
ACCESS_SECRET = 'private'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.update_status()
I am trying to have time and mem variables post their outputs to the api.update_status()
Any clue or alternative ways to do this?
Thanks!
A:
So what's the problem? The tweepy docs say you can pass a string to update_status():
api.update_status('uptime: %s / mem: %i%%' % (time, mem))
Also, I'm guessing you meant
time = uptime()
mem = psutil.Process(2360).get_memory_percent()
| (Python) How can I print a variable to a Tweepy "API.update_status()" command? | I am trying to add some information to a python script that posts the information to twitter. Here is the code so far:
#!/usr/bin/python
import os
import subprocess
import psutil
import sys
import tweepy
#----------------------------------------
# Gives a human-readable uptime string
def uptime():
try:
f = open( "/proc/uptime" )
contents = f.read().split()
f.close()
except:
return "Cannot open uptime file: /proc/uptime"
total_seconds = float(contents[0])
# Helper vars:
MINUTE = 60
HOUR = MINUTE * 60
DAY = HOUR * 24
# Get the days, hours, etc:
days = int( total_seconds / DAY )
hours = int( ( total_seconds % DAY ) / HOUR )
minutes = int( ( total_seconds % HOUR ) / MINUTE )
seconds = int( total_seconds % MINUTE )
# Build up the pretty string (like this: "N days, N hours, N minutes, N seconds")
string = ""
if days> 0:
string += str(days) + " " + (days == 1 and "day" or "days" ) + ", "
if len(string)> 0 or hours> 0:
string += str(hours) + " " + (hours == 1 and "hour" or "hours" ) + ", "
if len(string)> 0 or minutes> 0:
string += str(minutes) + " " + (minutes == 1 and "minute" or "minutes" ) + ", "
string += str(seconds) + " " + (seconds == 1 and "second" or "seconds" )
return string;
uptime() = time
psutil.Process(2360).get_memory_percent() = Mem
##Twitter Auth Stuff##
CONSUMER_KEY = 'blahblah'
CONSUMER_SECRET = 'edited because'
ACCESS_KEY = 'this is'
ACCESS_SECRET = 'private'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.update_status()
I am trying to have time and mem variables post their outputs to the api.update_status()
Any clue or alternative ways to do this?
Thanks!
| [
"So what's the problem? The tweepy docs say you can pass a string to update_status():\napi.update_status('uptime: %s / mem: %i%%' % (time, mem))\n\nAlso, I'm guessing you meant\ntime = uptime()\nmem = psutil.Process(2360).get_memory_percent()\n\n"
] | [
1
] | [] | [] | [
"python",
"tweepy",
"twitter"
] | stackoverflow_0004020781_python_tweepy_twitter.txt |
Q:
Problem Writing Image file in Python with PIL
I'm writing a small Python script using the PIL module to change the size of some textures used on a 3D Model in MultiGen Creator. I'm also using the openflight API so that's what the mg* functions are.
Here's the script
import PIL
from PIL import Image
db = mgGetCurrentDb()
ret,index,name = mgGetFirstTexture (db)
while (ret):
myAttr = mgReadImageAttributes (name)
existingattrs = mgGetAttList (myAttr,fltImgHeight,fltImgWidth)
print existingattrs[2]
print existingattrs[4]
if existingattrs[2] != 0 and existingattrs[4] != 0:
Height = existingattrs[2]/4
Width = existingattrs[4]/4
print name
print Width
print Height
imageFile = (name)
im1 = Image.open(imageFile)
im2 = im1.resize((Width,Height),PIL.Image.BILINEAR)
ImgOut = "C:\DB\PLW\out.jpg"
im2.save(ImgOut)
ret,index,name = mgGetNextTexture (db)
Anyway all seems to work but when I try and write the file I get the following error
E: Traceback (most recent call last):
E: File "<string>", line 24, in <module>
E: File "C:\Python25\lib\site-packages\PIL\Image.py", line 1439, in save
E: save_handler(self, fp, filename)
E: File "C:\Python25\Lib\site-packages\PIL\JpegImagePlugin.py", line 471, in _save
E: ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
E: File "C:\Python25\Lib\site-packages\PIL\ImageFile.py", line 499, in _save
E: s = e.encode_to_file(fh, bufsize)
E: IOError: [Errno 0] Error
A:
You need to double up the \ characters in your file name or use a raw string:
ImgOut = "C:\\DB\\PLW\\out.jpg"
ImgOut = r"C:\DB\PLW\out.jpg"
The error message is basically saying it couldn't open the file.
| Problem Writing Image file in Python with PIL | I'm writing a small Python script using the PIL module to change the size of some textures used on a 3D Model in MultiGen Creator. I'm also using the openflight API so that's what the mg* functions are.
Here's the script
import PIL
from PIL import Image
db = mgGetCurrentDb()
ret,index,name = mgGetFirstTexture (db)
while (ret):
myAttr = mgReadImageAttributes (name)
existingattrs = mgGetAttList (myAttr,fltImgHeight,fltImgWidth)
print existingattrs[2]
print existingattrs[4]
if existingattrs[2] != 0 and existingattrs[4] != 0:
Height = existingattrs[2]/4
Width = existingattrs[4]/4
print name
print Width
print Height
imageFile = (name)
im1 = Image.open(imageFile)
im2 = im1.resize((Width,Height),PIL.Image.BILINEAR)
ImgOut = "C:\DB\PLW\out.jpg"
im2.save(ImgOut)
ret,index,name = mgGetNextTexture (db)
Anyway all seems to work but when I try and write the file I get the following error
E: Traceback (most recent call last):
E: File "<string>", line 24, in <module>
E: File "C:\Python25\lib\site-packages\PIL\Image.py", line 1439, in save
E: save_handler(self, fp, filename)
E: File "C:\Python25\Lib\site-packages\PIL\JpegImagePlugin.py", line 471, in _save
E: ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
E: File "C:\Python25\Lib\site-packages\PIL\ImageFile.py", line 499, in _save
E: s = e.encode_to_file(fh, bufsize)
E: IOError: [Errno 0] Error
| [
"You need to double up the \\ characters in your file name or use a raw string:\n ImgOut = \"C:\\\\DB\\\\PLW\\\\out.jpg\" \n ImgOut = r\"C:\\DB\\PLW\\out.jpg\" \n\nThe error message is basically saying it couldn't open the file.\n"
] | [
2
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0004025545_python_python_imaging_library.txt |
Q:
How to save a temporarily jpg file by using python?
Hey I need to save a temporarily jpg file and then remove it, is there any better way to do?
I tested the tempfile, but looks that doesn't work.
A:
tempfile does work. What did you try?
>>> with tempfile.NamedTemporaryFile(mode="wb") as jpg:
... jpg.write(b"Hello World!")
... print jpg.name
...
c:\users\<...>\appdata\local\temp\tmpv7hy__
jpg will be closed as soon as the with block is left. If you pass in the optional argument delete, it will be deleted on close.
| How to save a temporarily jpg file by using python? | Hey I need to save a temporarily jpg file and then remove it, is there any better way to do?
I tested the tempfile, but looks that doesn't work.
| [
"tempfile does work. What did you try?\n>>> with tempfile.NamedTemporaryFile(mode=\"wb\") as jpg:\n... jpg.write(b\"Hello World!\")\n... print jpg.name\n...\nc:\\users\\<...>\\appdata\\local\\temp\\tmpv7hy__\n\njpg will be closed as soon as the with block is left. If you pass in the optional argument delete... | [
5
] | [] | [] | [
"python",
"temporary_files"
] | stackoverflow_0004025726_python_temporary_files.txt |
Q:
Accessing private variables when there's a getter/setter for them
I have a question about righteous way of programming in Python... Maybe there can be several different opinions, but here it goes:
Let's say I have a class with a couple of private attributes and that I have implemented two getters/setters (not overloading __getattr__ and __setattr__, but in a more “Java-tistic” style):
class MyClass:
def __init__(self):
self.__private1 = "Whatever1"
def setPrivate1(self, private1):
if isinstance(private1, str) and (private1.startswith("private")):
self.__private1 = private1
else:
raise AttributeError("Kaputt")
def getPrivate1(self):
return self.__private1
Now let's say a few lines below, in another method of the same class, I need to re-set the value of that “__private1”. Since it's the same class, I still have direct access to the private attribute self.__private1.
My question is: Should I use:
self.setPrivate1("privateBlaBlaBla")
or should I access directly as:
self.__private1 ="privateBlaBlaBla"
since I am the one setting the new value, I know that said value (“privateBlaBlaBla”) is correct (an str() that starts with “private”), so it is not going to leave the system inconsistent. On the other hand, if another programmer takes my code, and needs to change the functionality for the self.__private1 attribute, he will need to go through all the code, and see if the value of __private1 has been manually set somewhere else.
My guess is that the right thing to do is to always using the setPrivate1 method, and only access directly the __private1 variable in the get/set, but I'd like to know the opinion of more experienced Python programmers.
A:
You can't present a classic example of bad Python and then expect people to have opinions on what do to about it. Use getters and setters.
class MyClass:
def __init__(self):
self._private1 = "Whatever1"
@property
def private1(self):
return self._private1
@private1.setter
def private1(self, value):
self._private1 = value
A side comment -- using double underscore names can be confusing, because Python actually mangles the name to stop you accessing them from outside the class. This provides no real security, but causes no end of headaches. The easiest way to avoid the headaches is to use single-underscore names, which is basically a universal convention for private. (Ish.)
If you want an opinion -- use properties =). If you want an opinion on your JavaPython monstrosity, I would use the setter -- after all, you've written it, that's what it's there for! There's no obvious benefit to setting the variable by hand, but there are several drawbacks.
A:
Neither. In Python, use properties, not getters and setters.
class MyClass:
def __init__(self):
self._private1 = "Whatever1"
@property
def private1(self):
return self._private1
@private1.setter
def private1(self, private1):
if isinstance(private1, str) and (private1.startswith("private")):
self._private1 = private1
else:
raise AttributeError("Kaputt")
Then later on in your code, set the _private1 attribute with
self.private1="privateBlaBlaBla"
| Accessing private variables when there's a getter/setter for them | I have a question about righteous way of programming in Python... Maybe there can be several different opinions, but here it goes:
Let's say I have a class with a couple of private attributes and that I have implemented two getters/setters (not overloading __getattr__ and __setattr__, but in a more “Java-tistic” style):
class MyClass:
def __init__(self):
self.__private1 = "Whatever1"
def setPrivate1(self, private1):
if isinstance(private1, str) and (private1.startswith("private")):
self.__private1 = private1
else:
raise AttributeError("Kaputt")
def getPrivate1(self):
return self.__private1
Now let's say a few lines below, in another method of the same class, I need to re-set the value of that “__private1”. Since it's the same class, I still have direct access to the private attribute self.__private1.
My question is: Should I use:
self.setPrivate1("privateBlaBlaBla")
or should I access directly as:
self.__private1 ="privateBlaBlaBla"
since I am the one setting the new value, I know that said value (“privateBlaBlaBla”) is correct (an str() that starts with “private”), so it is not going to leave the system inconsistent. On the other hand, if another programmer takes my code, and needs to change the functionality for the self.__private1 attribute, he will need to go through all the code, and see if the value of __private1 has been manually set somewhere else.
My guess is that the right thing to do is to always using the setPrivate1 method, and only access directly the __private1 variable in the get/set, but I'd like to know the opinion of more experienced Python programmers.
| [
"You can't present a classic example of bad Python and then expect people to have opinions on what do to about it. Use getters and setters.\nclass MyClass:\n def __init__(self): \n self._private1 = \"Whatever1\"\n\n @property\n def private1(self):\n return self._private1\n\n @private1.se... | [
9,
2
] | [] | [] | [
"oop",
"private_members",
"python"
] | stackoverflow_0004025888_oop_private_members_python.txt |
Q:
Python Swig wrapper: how access underlying PyObject
I've got class A wrapped with method foo implemented using %extend:
class A {
...
%extend {
void foo()
{
self->foo_impl();
}
}
Now I want to increase ref count to an A inside foo_impl, but I only got A* (as self).
Question: how can I write/wrap function foo, so that I have an access both to A* and underlying PyObject*?
Thank you
A:
I think it's not possible. If you need to increase the refcount, it's because you don't want the C++ object to be destroyed when it goes out of scope because there is a pointer to that object elsewhere. In that case, look at using the DISOWN typemap to ensure the target language doesn't think it "owns" the C++ object, so it won't get destroyed.
| Python Swig wrapper: how access underlying PyObject | I've got class A wrapped with method foo implemented using %extend:
class A {
...
%extend {
void foo()
{
self->foo_impl();
}
}
Now I want to increase ref count to an A inside foo_impl, but I only got A* (as self).
Question: how can I write/wrap function foo, so that I have an access both to A* and underlying PyObject*?
Thank you
| [
"I think it's not possible. If you need to increase the refcount, it's because you don't want the C++ object to be destroyed when it goes out of scope because there is a pointer to that object elsewhere. In that case, look at using the DISOWN typemap to ensure the target language doesn't think it \"owns\" the C++... | [
1
] | [] | [] | [
"c++",
"python",
"swig"
] | stackoverflow_0004005355_c++_python_swig.txt |
Q:
How can I move my Python2.6 site-packages into Python2.7?
I just ran an update on ArchLinux which gave me Python3 and Python2.7.
Before this update, I was using Python2.6. The modules I have installed reside in /usr/lib/python2.6/site-package. I now want to use Python2.7 and remove Python2.6.
How can I move my Python2.6 modules into Python2.7 ?
Is it as simple as doing mv /usr/lib/python2.6/site-packages/* /usr/lib/python2.7/site-packages ?
A:
Your question is really, "How can I get the packages I have in python 2.6 into my [new] python 2.7 configuration? Would copying the files work?"
I would recommend installing the packages into 2.7 the same way you did your 2.6 packages. I would not recommend you copy the files.
Reasonable ways to install the files are:
easy_install
Get easy_install like this: wget http://python-distribute.org/distribute_setup.py && sudo python ./distribute_setup.py
pip install
Get pip like this: sudo easy_install pip
apt-get install
wget and untar
A:
Not a complete answer: It is not as simple as a mv. The files are byte compiled into .pyc files which are specific to python versions. So at the very least you'd have to regenerate the .pyc files. (Removing them should be sufficient, too.) Regenerating can be done using compileall.py.
Most distributions offer a saner way to upgrade Python modules than manual fiddling like this, so maybe someone can else can give the Arch specific part of the answer?
A:
The clean way would be re-installing. However, for many if not most of pure python packages the mv approach would work
A:
You might want to 'easy_install yolk', which can be invoked as 'yolk -l' to give you an easy-to-read list of all the installed packages.
A:
Try something like this:
#!/usr/bin/env python
import os
import os.path
import subprocess
import sys
import tempfile
def distributions(path):
# Extrapolate from paths which distributions presently exist.
(parent, child) = os.path.split(path)
while child is not '' and not child.startswith('python'):
(parent, child) = os.path.split(parent)
if len(child) > 0:
rel = os.path.relpath(path, os.path.join(parent, child))
ret = []
for distro in os.listdir(parent):
if distro.startswith('python'):
dir = os.path.join(os.path.join(parent, distro), rel)
if os.path.isdir(dir):
ret.append((distro, dir))
ret.sort()
return ret
return []
def packages(dir):
return [pkg.split('-')[0] for pkg in os.listdir(dir)]
def migrate(old, new):
print 'moving all packages found in ' + old[0] + ' (' + old[1] + ') to ' + new[0] + ' (' + new[1] + ')'
f = tempfile.TemporaryFile(mode = 'w+')
result = subprocess.call(
['which', 'easy_install'], stdout = f, stderr = subprocess.PIPE)
f.seek(0)
easy_install = f.readline().strip()
f.close()
if os.path.isfile(easy_install):
pkgs = packages(old[1])
success = []
failure = []
for pkg in pkgs:
# Invoke easy_install on the package
print 'installing "' + pkg + '" for ' + new[0]
result = subprocess.call(
[new[0], easy_install, pkg])
if result != 0:
failure.append(pkg)
print 'failed'
else:
success.append(pkg)
print 'success'
print str(len(success)) + ' of ' + str(len(pkgs)) + ' succeeded'
else:
print 'Unable to locate easy_install script'
if __name__ == '__main__':
package_path = sys.path[-1]
distros = distributions(package_path)
migrate(distros[0], distros[1])
list(package_path)
| How can I move my Python2.6 site-packages into Python2.7? | I just ran an update on ArchLinux which gave me Python3 and Python2.7.
Before this update, I was using Python2.6. The modules I have installed reside in /usr/lib/python2.6/site-package. I now want to use Python2.7 and remove Python2.6.
How can I move my Python2.6 modules into Python2.7 ?
Is it as simple as doing mv /usr/lib/python2.6/site-packages/* /usr/lib/python2.7/site-packages ?
| [
"Your question is really, \"How can I get the packages I have in python 2.6 into my [new] python 2.7 configuration? Would copying the files work?\"\nI would recommend installing the packages into 2.7 the same way you did your 2.6 packages. I would not recommend you copy the files.\nReasonable ways to install the fi... | [
1,
0,
0,
0,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0003968339_module_python.txt |
Q:
quick question: how to associate a file with an ImageField in django?
i have an image saved on my HDD and i want to assign it to an ImageField, but i don't know how.
i've tried something like this:
object.imagefield.save(path,File(open(path)))
But this makes an additional (invalid) copy of the image.
Can someone help me please?
thanks!
A:
I usually simply assign to the image field a string with the image's path, like this:
MyObject.image="/photo_path/photo_name.jpg"
MyObject.save()
I don't know if there is something wrong in doing that, but it always works.
A:
There might be a better way, but I do something like:
from django.core.files.base import ContentFile
srcFile = ContentFile( srcData ) # srcData is the contents of the local file
srcFile.open()
myObject.image.save(name=filename, content=srcFile)
| quick question: how to associate a file with an ImageField in django? | i have an image saved on my HDD and i want to assign it to an ImageField, but i don't know how.
i've tried something like this:
object.imagefield.save(path,File(open(path)))
But this makes an additional (invalid) copy of the image.
Can someone help me please?
thanks!
| [
"I usually simply assign to the image field a string with the image's path, like this:\nMyObject.image=\"/photo_path/photo_name.jpg\"\nMyObject.save()\n\nI don't know if there is something wrong in doing that, but it always works.\n",
"There might be a better way, but I do something like:\nfrom django.core.files.... | [
7,
2
] | [] | [] | [
"django",
"filefield",
"imagefield",
"python"
] | stackoverflow_0004025676_django_filefield_imagefield_python.txt |
Q:
operating over strings, python
How to define a function that takes a string (sentence) and inserts an extra space after a period if the period is directly followed by a letter.
sent = "This is a test.Start testing!"
def normal(sent):
list_of_words = sent.split()
...
This should print out
"This is a test. Start testing!"
I suppose I should use split() to brake a string into a list, but what next?
P.S. The solution has to be as simple as possible.
A:
Use re.sub. Your regular expression will match a period (\.) followed by a letter ([a-zA-Z]). Your replacement string will contain a reference to the second group (\2), which was the letter matched in the regular expression.
>>> import re
>>> re.sub(r'\.([a-zA-Z])', r'. \1', 'This is a test.This is a test. 4.5 balloons.')
'This is a test. This is a test. 4.5 balloons'
Note the choice of [a-zA-Z] for the regular expression. This matches just letters. We do not use \w because it would insert spaces into a decimal number.
A:
One-liner non-regex answer:
def normal(sent):
return ".".join(" " + s if i > 0 and s[0].isalpha() else s for i, s in enumerate(sent.split(".")))
Here is a multi-line version using a similar approach. You may find it more readable.
def normal(sent):
sent = sent.split(".")
result = sent[:1]
for item in sent[1:]:
if item[0].isalpha():
item = " " + item
result.append(item)
return ".".join(result)
Using a regex is probably the better way, though.
A:
Brute force without any checks:
>>> sent = "This is a test.Start testing!"
>>> k = sent.split('.')
>>> ". ".join(l)
'This is a test. Start testing!'
>>>
For removing spaces:
>>> sent = "This is a test. Start testing!"
>>> k = sent.split('.')
>>> l = [x.lstrip(' ') for x in k]
>>> ". ".join(l)
'This is a test. Start testing!'
>>>
A:
Another regex-based solution, might be a tiny bit faster than Steven's (only one pattern match, and a blacklist instead of a whitelist):
import re
re.sub(r'\.([^\s])', r'. \1', some_string)
A:
Improving pyfunc's answer:
sent="This is a test.Start testing!"
k=sent.split('.')
k='. '.join(k)
k.replace('. ','. ')
'This is a test. Start testing!'
| operating over strings, python | How to define a function that takes a string (sentence) and inserts an extra space after a period if the period is directly followed by a letter.
sent = "This is a test.Start testing!"
def normal(sent):
list_of_words = sent.split()
...
This should print out
"This is a test. Start testing!"
I suppose I should use split() to brake a string into a list, but what next?
P.S. The solution has to be as simple as possible.
| [
"Use re.sub. Your regular expression will match a period (\\.) followed by a letter ([a-zA-Z]). Your replacement string will contain a reference to the second group (\\2), which was the letter matched in the regular expression. \n>>> import re\n>>> re.sub(r'\\.([a-zA-Z])', r'. \\1', 'This is a test.This is a tes... | [
8,
3,
1,
1,
0
] | [] | [] | [
"python",
"split",
"tokenize"
] | stackoverflow_0004026287_python_split_tokenize.txt |
Q:
How can I calculate the latitude and longitude of each pixel of an image in a kml file using Python?
I am using .kml file which points to an overlay image (presumably in UTM projection?).
The KML file provides the latitudes and longitudes of the bounding box using the "LatLonBox" tag.
I need to calculate the latitudes and longitudes of each pixel in this image.
Are there any pre-existing libraries in Python that would do this for me?
A:
The overlay image referenced by the kml file was in standard geographic projection.
This means that the latitudes and longitudes vary linearly within the image.
Calculating the latitude and longitude of each pixel became a trivial case of interpolation given that we already known the lat/lon bounds of the image provided by the LatLonBox tag attributes.
| How can I calculate the latitude and longitude of each pixel of an image in a kml file using Python? | I am using .kml file which points to an overlay image (presumably in UTM projection?).
The KML file provides the latitudes and longitudes of the bounding box using the "LatLonBox" tag.
I need to calculate the latitudes and longitudes of each pixel in this image.
Are there any pre-existing libraries in Python that would do this for me?
| [
"The overlay image referenced by the kml file was in standard geographic projection.\nThis means that the latitudes and longitudes vary linearly within the image. \nCalculating the latitude and longitude of each pixel became a trivial case of interpolation given that we already known the lat/lon bounds of the image... | [
0
] | [] | [] | [
"geospatial",
"kml",
"latitude_longitude",
"python"
] | stackoverflow_0004019611_geospatial_kml_latitude_longitude_python.txt |
Q:
Buildout, psycopg2, postgresql
I'm trying to make buildout config that installs psycopg2 egg and postgres from source if needed:
parts =
...
postgre
psycopg2
...
[postgre]
recipe = hexagonit.recipe.cmmi
url = ftp://ftp3.ua.postgresql.org/pub/mirrors/postgresql/source/v9.0.0/postgresql-9.0.0.tar.gz
configure-options =
--without-readline
[psycopg2]
recipe = zc.recipe.egg:custom
egg = psycopg2
include-dirs =
${postgre:location}/include
library-dirs =
${postgre:location}/lib
rpath =
${postgre:location}/lib
The problem is that it always builds postgresql from source, even if the user already has postgresql installed.
How can I tell buildout to check if user already have all necessary to build psycopg2?
A:
You can do it, but you'll have to make your own recipe to do that check. There's no existing recipe that does what you want.
An alternative is to have two buildout configs. The main buildout.cfg assumes postgresql is available and doesn't attempt to build it.
A second withpostgres.cfg could look like this:
[buildout]
parts +=
postgre
psycopg2
[postgres]
... your existing one ...
[psycopg2]
... your existing one ...
Users that need to build it from source can use the second configuration by calling bin/buildout -c withpostres.cfg.
Would that solve your issue?
| Buildout, psycopg2, postgresql | I'm trying to make buildout config that installs psycopg2 egg and postgres from source if needed:
parts =
...
postgre
psycopg2
...
[postgre]
recipe = hexagonit.recipe.cmmi
url = ftp://ftp3.ua.postgresql.org/pub/mirrors/postgresql/source/v9.0.0/postgresql-9.0.0.tar.gz
configure-options =
--without-readline
[psycopg2]
recipe = zc.recipe.egg:custom
egg = psycopg2
include-dirs =
${postgre:location}/include
library-dirs =
${postgre:location}/lib
rpath =
${postgre:location}/lib
The problem is that it always builds postgresql from source, even if the user already has postgresql installed.
How can I tell buildout to check if user already have all necessary to build psycopg2?
| [
"You can do it, but you'll have to make your own recipe to do that check. There's no existing recipe that does what you want.\nAn alternative is to have two buildout configs. The main buildout.cfg assumes postgresql is available and doesn't attempt to build it.\nA second withpostgres.cfg could look like this:\n[b... | [
2
] | [] | [] | [
"buildout",
"django",
"python"
] | stackoverflow_0003999081_buildout_django_python.txt |
Q:
how can i limit my django foreign key selection by a property stored in the django session
i have a small application i am implementing with django and i'm having a slight challenge. I'm trying to limit the queryset for my relationships within my application by a particular property. Now the catch is, the exact value of the property isn't known until the user logs into the application. an example is limiting a set of comments by a user's particular company, and the company is only determined when the user logs in. I don't know how to find my current session outside a django view. Any help is appreciated. Thanks
Here is a sample of a model from my application
class Tax(commons.models.EntityBase):
name = models.CharField(blank=False, max_length=150)
percentage_value = models.DecimalField(max_digits=4, decimal_places=2)
notes = models.TextField(blank=True, null=True)
auto_apply = models.NullBooleanField()
aggregated_tax = models.NullBooleanField()
def __unicode__(self):
return self.name
Every entity inherits from the abstract class EntityBase, which holds the property company. I want to filter every query from the query manager such that they only return entities who's company are equal to the company in the session.
A:
It is perfectly ok to pass your session property, user or company or whatnot, to other functions in different parts of your system.
For example:
def view(request):
user = request.user
filtered_stuff = my_filter_function(..., user = user)
The my_filter_function may filter on the argument or may pass on the argument to other functions.
A:
The best way that I've found to do this is using a custom QuerySet and Manager for your model. The accepted answer to this question, should get you started with this part. In your QuerySet, you can set up a method (I prefer to call it for_user), which filters your objects for you:
class Foo(models.Model):
ts = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, blank=True, null=True)
due_date = models.DateField(auto_now=False)
objects = CustomQuerySetManager()
class QuerySet(QuerySet):
def for_user(self, user):
return self.filter(user=user)
From there, your view is fairly simple:
def view(request):
user = request.user
mylist = Foo.objects.for_user(user).filter(due_date__lte=datetime.date.today())
A:
To add to Jack's answer,
your CustomQuerySetManager would be something like:
class CustomQuerySetManager(models.Manager):
def get_query_set(self):
return self.model.QuerySet(self.model)
def __getattr__(self, attr, *args):
return getattr(self.get_query_set(), attr, *args)
I prefer this method over writing manager methods because it allows you to have chainable functions, therefore you could do:
Foo.objects.for_user(user).filter(...)
| how can i limit my django foreign key selection by a property stored in the django session | i have a small application i am implementing with django and i'm having a slight challenge. I'm trying to limit the queryset for my relationships within my application by a particular property. Now the catch is, the exact value of the property isn't known until the user logs into the application. an example is limiting a set of comments by a user's particular company, and the company is only determined when the user logs in. I don't know how to find my current session outside a django view. Any help is appreciated. Thanks
Here is a sample of a model from my application
class Tax(commons.models.EntityBase):
name = models.CharField(blank=False, max_length=150)
percentage_value = models.DecimalField(max_digits=4, decimal_places=2)
notes = models.TextField(blank=True, null=True)
auto_apply = models.NullBooleanField()
aggregated_tax = models.NullBooleanField()
def __unicode__(self):
return self.name
Every entity inherits from the abstract class EntityBase, which holds the property company. I want to filter every query from the query manager such that they only return entities who's company are equal to the company in the session.
| [
"It is perfectly ok to pass your session property, user or company or whatnot, to other functions in different parts of your system.\nFor example:\ndef view(request):\n user = request.user\n filtered_stuff = my_filter_function(..., user = user)\n\nThe my_filter_function may filter on the argument or may pass ... | [
1,
0,
0
] | [] | [] | [
"django",
"python",
"session_variables"
] | stackoverflow_0004016227_django_python_session_variables.txt |
Q:
Django - Replicating the admin list_display
What's the easiest method to get list_display functionality in my main website (outside of the admin pages).
I have a group of elements I'd like to select and perform an action. Any ideas?
A:
An application called django-filter is by far the best and easiest way to implement this.
A:
Try the Object List from generic views.
| Django - Replicating the admin list_display | What's the easiest method to get list_display functionality in my main website (outside of the admin pages).
I have a group of elements I'd like to select and perform an action. Any ideas?
| [
"An application called django-filter is by far the best and easiest way to implement this. \n",
"Try the Object List from generic views.\n"
] | [
2,
1
] | [] | [] | [
"css",
"django",
"html",
"javascript",
"python"
] | stackoverflow_0004012361_css_django_html_javascript_python.txt |
Q:
Django: saving a ModelForm with custom many-to-many models
I have Publications and Authors. Since the ordering of Authors matters (the professor doesn't want to be listed after the intern that contributed some trivial data), I defined a custom many-to-many model:
class Authorship(models.Model):
author = models.ForeignKey("Author")
publication = models.ForeignKey("Publication")
ordering = models.IntegerField(default=0)
class Author(models.Model):
name = models.CharField(max_length=100)
class Publication(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, through=Authorship)
I've got aModelForm for publications and use it in a view. Problem is, when I call form.save(), the authors are obviously added with the default ordering of 0. I've written a OrderedModelMultipleChoiceField with a clean method that returns the objects to be saved in the correct order, but I didn't find the hook where the m2m data is actually saved, so that I could add/edit/remove the Authorship instances myself.
Any ideas?
A:
If you are using a custom M2M table using the through parameter, I believe you must do the saves manually in order to save the additional fields. So in your view you would add:
...
publication = form.save()
#assuming that these records are in order! They may not be
order_idx = 0
for author in request.POST.getlist('authors'):
authorship = Authorship(author=author, publication=publication, ordering=order_idx)
authorship.save()
order_idx += 1
You may also be able to place this in your ModelForm's save function.
A:
I'm not sure if there's a hook for this, but you could save it manually with something like:
form = PublicationForm(...)
pub = form.save(commit=False)
pub.save()
form.save_m2m()
So you can handle any custom actions in between as required. See the examples in the docs for the save method.
| Django: saving a ModelForm with custom many-to-many models | I have Publications and Authors. Since the ordering of Authors matters (the professor doesn't want to be listed after the intern that contributed some trivial data), I defined a custom many-to-many model:
class Authorship(models.Model):
author = models.ForeignKey("Author")
publication = models.ForeignKey("Publication")
ordering = models.IntegerField(default=0)
class Author(models.Model):
name = models.CharField(max_length=100)
class Publication(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, through=Authorship)
I've got aModelForm for publications and use it in a view. Problem is, when I call form.save(), the authors are obviously added with the default ordering of 0. I've written a OrderedModelMultipleChoiceField with a clean method that returns the objects to be saved in the correct order, but I didn't find the hook where the m2m data is actually saved, so that I could add/edit/remove the Authorship instances myself.
Any ideas?
| [
"If you are using a custom M2M table using the through parameter, I believe you must do the saves manually in order to save the additional fields. So in your view you would add:\n...\npublication = form.save()\n#assuming that these records are in order! They may not be\norder_idx = 0\nfor author in request.POST.get... | [
2,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0004026137_django_django_forms_python.txt |
Q:
provider cannot be found error in python connecting to SQL Server
I'm attempting to connect to a SQL Server database within a Python script. I'm using SQLNCLI as provider on my connection string.
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd)
dbConn = Dispatch("ADODB.Connection")
dbConn.Open( connection_string )
When executing the script I get this error:
provider cannot be found. It may not be properly installed.
Any ideas on how to fix this?
A:
install SQLNCLI. if it still not working change :
"Provider=SQLNCLI;server=%...
to
"Provider=SQLNCLI10;server=%...
A:
...It is so simple just install this: SQLNCLI.msi
you can find it here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en
| provider cannot be found error in python connecting to SQL Server | I'm attempting to connect to a SQL Server database within a Python script. I'm using SQLNCLI as provider on my connection string.
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd)
dbConn = Dispatch("ADODB.Connection")
dbConn.Open( connection_string )
When executing the script I get this error:
provider cannot be found. It may not be properly installed.
Any ideas on how to fix this?
| [
"install SQLNCLI. if it still not working change :\n\"Provider=SQLNCLI;server=%...\n\nto\n\"Provider=SQLNCLI10;server=%...\n\n",
"...It is so simple just install this: SQLNCLI.msi\nyou can find it here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=d09c1d60-a13c-4479-9b91-9e8b9d835cdc&displaylang=en... | [
1,
-1
] | [] | [] | [
"adodb",
"python",
"sql_server",
"win32com"
] | stackoverflow_0004026776_adodb_python_sql_server_win32com.txt |
Q:
How to connect to a DB on windows
I have a SQL server 2005 server database on a server and need to conect to it from a client on the same server network, any ideas?
A:
The pymssql library is one option.
A:
see here for the ensemble of database connector:
http://wiki.python.org/moin/DatabaseInterfaces
for sql server see here:
http://wiki.python.org/moin/SQL%20Server
A:
from win32com.client import Dispatch
connection_string = "Provider=SQLNCLI;server=%s;initial catalog=%s;user id=%s;password=%s"%(server,db_name,user,pwd)
dbConn = Dispatch("ADODB.Connection")
dbConn.Open( connection_string )
| How to connect to a DB on windows | I have a SQL server 2005 server database on a server and need to conect to it from a client on the same server network, any ideas?
| [
"The pymssql library is one option.\n",
"see here for the ensemble of database connector:\nhttp://wiki.python.org/moin/DatabaseInterfaces\nfor sql server see here:\nhttp://wiki.python.org/moin/SQL%20Server\n",
"from win32com.client import Dispatch \n\nconnection_string = \"Provider=SQLNCLI;server=%s;initial cat... | [
2,
0,
0
] | [] | [] | [
"python",
"sql_server",
"windows"
] | stackoverflow_0004026428_python_sql_server_windows.txt |
Q:
django ModelMultipleChoiceField (default values)
I've been searching and trying to get this to work for the past few hours and I can't
I have a list of skills that I take from the database:
forms.ModelMultipleChoiceField(
skills.objects.all(),
required=True,
widget=forms.CheckboxSelectMultiple(),
label='Check your skills.',
initial=skill_list.objects.filter(user='void'),
)
but this isn't working as I would expect it to work. I basically want to display the list of skills (all of them) and the ones that the user has checked to be checked ... pff I cant even explain right.
After the user checks the checkbox and hits submit in another page I want to display all skills and the one the user checked to be checked.
Lets say I have a b c and the user checks b and hits submit when in w/e page I want to display a uncheked b checked c unchecked.
PS: If I use skills.objects.all(), I get in the HTML value 1 and a how can I make it like this:
skills = (
('a', 'a'),
('b', 'b'),
)
Instead of ('1', 'a'), ('2', 'b').
A:
Your question(s) are a little unclear, but il still try my best.
Firstly,
I wanna display all skills and the one
the user checked to be checked ...
The form doesnot have access to the user, so you need to pass it the user. You could do this by overloading the __init__ method like so:
def __init__(self, **kwargs):
current_user = kwargs.pop ('user')
super(FormName, self).__init__(attrs)
then for setting the initially chosen values,
self.fields['skills'].initial = skill_list.objects.filter(user='void')
Remember you must do this after calling the constructor of the base class.
Finally,
PS: if i use skills.objects.all() I
get in the html value 1 and a how can
I make this as
skills = (
('a', 'a'),
('b', 'b'),
)
instead of ('1', 'a'), ('2', 'b')
Why would you want to do that? The numbers are the primary keys of the rows from you 'skills' table. Django uses this to setup the appropriate relationships.
| django ModelMultipleChoiceField (default values) | I've been searching and trying to get this to work for the past few hours and I can't
I have a list of skills that I take from the database:
forms.ModelMultipleChoiceField(
skills.objects.all(),
required=True,
widget=forms.CheckboxSelectMultiple(),
label='Check your skills.',
initial=skill_list.objects.filter(user='void'),
)
but this isn't working as I would expect it to work. I basically want to display the list of skills (all of them) and the ones that the user has checked to be checked ... pff I cant even explain right.
After the user checks the checkbox and hits submit in another page I want to display all skills and the one the user checked to be checked.
Lets say I have a b c and the user checks b and hits submit when in w/e page I want to display a uncheked b checked c unchecked.
PS: If I use skills.objects.all(), I get in the HTML value 1 and a how can I make it like this:
skills = (
('a', 'a'),
('b', 'b'),
)
Instead of ('1', 'a'), ('2', 'b').
| [
"Your question(s) are a little unclear, but il still try my best.\nFirstly, \n\nI wanna display all skills and the one\n the user checked to be checked ...\n\nThe form doesnot have access to the user, so you need to pass it the user. You could do this by overloading the __init__ method like so:\n def __init__(s... | [
2
] | [] | [] | [
"django",
"forms",
"python"
] | stackoverflow_0004010878_django_forms_python.txt |
Q:
What is C#'s version of the GIL?
In the current implementation of CPython, there is an object known as the "GIL" or "Global Interpreter Lock". It is essentially a mutex that prevents two Python threads from executing Python code at the same time. This prevents two threads from being able to corrupt the state of the Python interpreter, but also prevents multiple threads from really executing together. Essentially, if I do this:
# Thread A
some_list.append(3)
# Thread B
some_list.append(4)
I can't corrupt the list, because at any given time, only one of those threads are executing, since they must hold the GIL to do so. Now, the items in the list might be added in some indeterminate order, but the point is that the list isn't corrupted, and two things will always get added.
So, now to C#. C# essentially faces the same problem as Python, so, how does C# prevent this? I'd also be interested in hearing Java's story, if anyone knows it.
Clarification: I'm interested in what happens without explicit locking statements, especially to the VM. I am aware that locking primitives exist for both Java & C# - they exist in Python as well: The GIL is not used for multi-threaded code, other than to keep the interpreter sane. I am interested in the direct equivalent of the above, so, in C#, if I can remember enough... :-)
List<String> s;
// Reference to s is shared by two threads, which both execute this:
s.Add("hello");
// State of s?
// State of the VM? (And if sane, how so?)
Here's another example:
class A
{
public String s;
}
// Thread A & B
some_A.s = some_other_value;
// some_A's state must change: how does it change?
// Is the VM still in good shape afterwards?
I'm not looking to write bad C# code, I understand the lock statements. Even in Python, the GIL doesn't give you magic-multi-threaded code: you must still lock shared resources. But the GIL prevents Python's "VM" from being corrupted - it is this behavior that I'm interested in.
A:
Most other languages that support threading don't have an equivalent of the Python GIL; they require you to use mutexes, either implicitly or explicitly.
A:
Using lock, you would do this:
lock(some_list)
{
some_list.Add(3);
}
and in thread 2:
lock(some_list)
{
some_list.Add(4);
}
The lock statement ensures that the object inside the lock statement, some_list in this case, can only be accessed by a single thread at a time. See http://msdn.microsoft.com/en-us/library/c5kehkcz(VS.80).aspx for more information.
A:
C# does not have an equivalent of GIL to Python.
Though they face the same issue, their design goals make them
different.
With GIL, CPython ensures that suche operations as appending a list
from two threads is simple. Which also
means that it would allow only one
thread to run at any time. This
makes lists and dictionaries thread safe. Though this makes the job
simpler and intuitive, it makes it
harder to exploit the multithreading
advantage on multicores.
With no GIL, C# does the opposite. It ensures that the burden of integrity is on the developer of the
program but allows you to take
advantage of running multiple threads
simultaneously.
As per one of the discussion -
The GIL in CPython is purely a design choice of having
a big lock vs a lock per object
and synchronisation to make sure that objects are kept in a coherent state.
This consist of a trade off - Giving up the full power of
multithreading.
It has been that most problems do not suffer from this disadvantage
and there are libraries which help you exclusively solve this issue when
required.
That means for a certain class of problems, the burden to utilize the
multicore is
passed to developer so that rest can enjoy the more simpler, intuitive
approach.
Note: Other implementation like IronPython do not have GIL.
A:
It may be instructive to look at the documentation for the Java equivalent of the class you're discussing:
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be "wrapped" using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:
List list = Collections.synchronizedList(new ArrayList(...));
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
A:
Most complex datastructures(for example lists) can be corrupted when used without locking in multiple threads.
Since changes of references are atomic, a reference always stays a valid reference.
But there is a problem when interacting with security critical code. So any datastructures used by critical code most be one of the following:
Inaccessible from untrusted code, and locked/used correctly by trusted code
Immutable (String class)
Copied before use (valuetype parameters)
Written in trusted code and uses internal locking to guarantee a safe state
For example critical code cannot trust a list accessible from untrusted code. If it gets passed in a List, it has to create a private copy, do it's precondition checks on the copy, and then operate on the copy.
A:
I'm going to take a wild guess at what the question really means...
In Python data structures in the interpreter get corrupted because Python is using a form of reference counting.
Both C# and Java use garbage collection and in fact they do use a global lock when doing a full heap collection.
Data can be marked and moved between "generations" without a lock. But to actually clean it up everything must come to a stop. Hopefully a very short stop, but a full stop.
Here is an interesting link on CLR garbage collection as of 2007:
http://vineetgupta.spaces.live.com/blog/cns!8DE4BDC896BEE1AD!1104.entry
| What is C#'s version of the GIL? | In the current implementation of CPython, there is an object known as the "GIL" or "Global Interpreter Lock". It is essentially a mutex that prevents two Python threads from executing Python code at the same time. This prevents two threads from being able to corrupt the state of the Python interpreter, but also prevents multiple threads from really executing together. Essentially, if I do this:
# Thread A
some_list.append(3)
# Thread B
some_list.append(4)
I can't corrupt the list, because at any given time, only one of those threads are executing, since they must hold the GIL to do so. Now, the items in the list might be added in some indeterminate order, but the point is that the list isn't corrupted, and two things will always get added.
So, now to C#. C# essentially faces the same problem as Python, so, how does C# prevent this? I'd also be interested in hearing Java's story, if anyone knows it.
Clarification: I'm interested in what happens without explicit locking statements, especially to the VM. I am aware that locking primitives exist for both Java & C# - they exist in Python as well: The GIL is not used for multi-threaded code, other than to keep the interpreter sane. I am interested in the direct equivalent of the above, so, in C#, if I can remember enough... :-)
List<String> s;
// Reference to s is shared by two threads, which both execute this:
s.Add("hello");
// State of s?
// State of the VM? (And if sane, how so?)
Here's another example:
class A
{
public String s;
}
// Thread A & B
some_A.s = some_other_value;
// some_A's state must change: how does it change?
// Is the VM still in good shape afterwards?
I'm not looking to write bad C# code, I understand the lock statements. Even in Python, the GIL doesn't give you magic-multi-threaded code: you must still lock shared resources. But the GIL prevents Python's "VM" from being corrupted - it is this behavior that I'm interested in.
| [
"Most other languages that support threading don't have an equivalent of the Python GIL; they require you to use mutexes, either implicitly or explicitly.\n",
"Using lock, you would do this:\nlock(some_list)\n{\n some_list.Add(3);\n}\n\nand in thread 2:\nlock(some_list)\n{\n some_list.Add(4);\n}\n\nThe lock... | [
12,
4,
3,
1,
0,
0
] | [] | [] | [
"c#",
"gil",
"java",
"python"
] | stackoverflow_0004026238_c#_gil_java_python.txt |
Q:
Fade in/out the background color of wxpython grid cell
I've got a wxpython grid, and I'm changing the background color of a cell to show that something has happened to it.
I'd like to fade the color change in/out (like JavaScript in the browser) for a smoother look. Is this possible to do?
Right now, I'm just changing the background color, and then changing it back after a 1.5-second interval.
def do_stuf(self):
# ... stuff ...
wx.CallAfter(self.HighlightCell, row, col)
def HighlightCell(self, row, col):
self.grid.Table.highlight = (row, col)
self.grid.ForceRefresh()
wx.CallLater(1500, self.ClearCellHighlight)
def ClearCellHighlight(self):
self.grid.Table.highlight = None
self.grid.ForceRefresh()
Then in the virtual table, I check if the cell needs highlighting:
def GetAttr(self, row, col, kind):
"""
Use this callback to set the cell's background color
"""
attr = wx.grid.GridCellAttr()
if (row, col) == self.highlight:
attr.SetBackgroundColour("green")
elif row % 2:
attr.SetBackgroundColour("white")
else:
attr.SetBackgroundColour("#e7ffff")
return attr
Alternatively, is there another pretty way to indicate that a cell's contents have changed?
A:
This is something I did a while ago to get a ListCtrl with items that fade out when deleted. Save the code to fade.py and run it to see the demo. Shouldn't be too hard to adapt it to a Grid.
import wx
class FadeMixin(object):
''' FadeMixin provides one public method: DeleteItem. It is meant to
be mixed in with a ListCtrl to 'fade out' items before they are
really deleted. Mixin like this:
Assumption: the background colour of the control is wx.WHITE
class MyListCtrl(FadeMixin, wx.ListCtrl):
...
'''
def __init__(self, *args, **kwargs):
self.__bgColour = wx.WHITE
super(FadeMixin, self).__init__(*args, **kwargs)
def DeleteItem(self, index, fadeStep=10, fadeSpeed=50):
if self.IsEnabled():
self.__startDeleteItem(index)
fgColour, bgColour, transparentColour = self.__getColours(index)
if fgColour == bgColour == transparentColour:
self.__finishDeleteItem(index)
else:
for colour, setColour in [(fgColour, self.SetItemTextColour),
(bgColour, self.SetItemBackgroundColour)]:
fadedColour = self.__fadeColour(colour, transparentColour,
fadeStep)
setColour(index, fadedColour)
wx.FutureCall(50, self.DeleteItem, index, fadeStep, fadeSpeed)
def SetBackgroundColour(self, colour):
self.__bgColour = colour
super(FadeMixin, self).SetBackgroundColour(colour)
def GetBackgroundColour(self):
return self.__bgColour
def __startDeleteItem(self, index):
# Prevent user input during deletion. Things could get messy if
# the user deletes another item when we're still busy fading out the
# first one:
self.Disable()
# Unselect the item that is to be deleted to make the fading visible:
currentState = self.GetItemState(index, wx.LIST_STATE_SELECTED)
self.SetItemState(index, ~currentState, wx.LIST_STATE_SELECTED)
def __finishDeleteItem(self, index):
super(FadeMixin, self).DeleteItem(index)
self.Enable()
def __getColours(self, index):
fgColour = self.GetItemTextColour(index)
bgColour = self.GetItemBackgroundColour(index)
transparentColour = self.GetBackgroundColour()
if not bgColour:
bgColour = transparentColour
return fgColour, bgColour, transparentColour
def __fadeColour(self, colour, transparentColour, fadeStep):
newColour = []
for GetIntensity in wx.Colour.Red, wx.Colour.Green, wx.Colour.Blue:
currentIntensity = GetIntensity(colour)
transparentIntensity = GetIntensity(transparentColour)
if currentIntensity < transparentIntensity:
newIntensity = min(transparentIntensity,
currentIntensity + fadeStep)
elif currentIntensity > transparentIntensity:
newIntensity = max(transparentIntensity,
currentIntensity - fadeStep)
else:
newIntensity = transparentIntensity
newColour.append(newIntensity)
return wx.Colour(*newColour)
class ListCtrl(FadeMixin, wx.ListCtrl):
pass
class Frame(wx.Frame):
def __init__(self, *args, **kwargs):
super(Frame, self).__init__(*args, **kwargs)
self.list = ListCtrl(self, style=wx.LC_REPORT)
self.list.InsertColumn(0, 'Column 0')
self.list.InsertColumn(1, 'Column 1')
self.fillList()
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onSelected)
self.Bind(wx.EVT_LIST_DELETE_ITEM, self.onDeleted)
def onSelected(self, event):
self.list.DeleteItem(event.GetIndex())
def onDeleted(self, event):
if self.list.GetItemCount() == 1:
wx.CallAfter(self.fillList, False)
def fillList(self, firstTime=True):
for row in range(10):
self.list.InsertStringItem(row, 'Item %d, Column 0'%row)
self.list.SetStringItem(row, 1, 'Item %d, Column 1'%row)
self.list.SetItemBackgroundColour(1, wx.BLUE)
self.list.SetItemTextColour(2, wx.BLUE)
self.list.SetItemBackgroundColour(3, wx.GREEN)
self.list.SetItemTextColour(4, wx.GREEN)
self.list.SetItemBackgroundColour(5, wx.RED)
self.list.SetItemTextColour(6, wx.RED)
self.list.SetItemBackgroundColour(7, wx.BLACK)
self.list.SetItemTextColour(7, wx.WHITE)
self.list.SetItemBackgroundColour(8, wx.WHITE)
self.list.SetItemTextColour(8, wx.BLACK)
if not firstTime:
self.list.SetBackgroundColour(wx.BLUE)
app = wx.App(False)
frame = Frame(None, title='Select an item to fade it out')
frame.Show()
app.MainLoop()
A:
To my knowledge, you can only set the transparency on the frame widget and see its affect on all the children. I don't recall why setting transparency on individual widgets doesn't work. Anyway, a decent way to simulate something like this would be to use a wx.Timer that cycles through a list of different shades of one color and then when the iteration is done, reset it back to the normal color. That should simulate the look well enough.
| Fade in/out the background color of wxpython grid cell | I've got a wxpython grid, and I'm changing the background color of a cell to show that something has happened to it.
I'd like to fade the color change in/out (like JavaScript in the browser) for a smoother look. Is this possible to do?
Right now, I'm just changing the background color, and then changing it back after a 1.5-second interval.
def do_stuf(self):
# ... stuff ...
wx.CallAfter(self.HighlightCell, row, col)
def HighlightCell(self, row, col):
self.grid.Table.highlight = (row, col)
self.grid.ForceRefresh()
wx.CallLater(1500, self.ClearCellHighlight)
def ClearCellHighlight(self):
self.grid.Table.highlight = None
self.grid.ForceRefresh()
Then in the virtual table, I check if the cell needs highlighting:
def GetAttr(self, row, col, kind):
"""
Use this callback to set the cell's background color
"""
attr = wx.grid.GridCellAttr()
if (row, col) == self.highlight:
attr.SetBackgroundColour("green")
elif row % 2:
attr.SetBackgroundColour("white")
else:
attr.SetBackgroundColour("#e7ffff")
return attr
Alternatively, is there another pretty way to indicate that a cell's contents have changed?
| [
"This is something I did a while ago to get a ListCtrl with items that fade out when deleted. Save the code to fade.py and run it to see the demo. Shouldn't be too hard to adapt it to a Grid.\nimport wx\n\nclass FadeMixin(object):\n ''' FadeMixin provides one public method: DeleteItem. It is meant to\n be mix... | [
4,
1
] | [] | [] | [
"grid",
"python",
"wxpython"
] | stackoverflow_0003985305_grid_python_wxpython.txt |
Q:
Confusing expression in python
If I have the list:
lista=[99, True, "Una Lista", [1,3]]
What does the following expression mean?
mi_var = lista[0:4:2]
A:
The syntax lista[0:4:2] is called extended slice syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), but only including the even indexes (step = 2).
In your example it will give [99, "Una Lista"]. More generally you can get a slice consisting of every element at an even index by writing lista[::2]. This works regardless of the length of the list because the start and end parameters default to 0 and the length of the list respectively.
One interesting feature with slices is that you can also assign to them to modify the original list, or delete a slice to remove the elements from the original list.
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x[::2] = ['a', 'b', 'c', 'd', 'e'] # Assign to index 0, 2, 4, 6, 8
>>> x
['a', 1, 'b', 3, 'c', 5, 'd', 7, 'e', 9]
>>> del x[:5] # Remove the first 5 elements
>>> x
[5, 'd', 7, 'e', 9]
A:
Iterate through the list from 0 to 3 (since 4 is excluded, [start, end)) stepping over two elements. The result of this is [99, 'Una Lista'] as expected and that is stored in the list, mi_var
A:
One way just to run and see:
>>> lista=[99, True, "Una Lista", [1,3]]
>>> lista[0:4:2]
[99, 'Una Lista']
It's a slice notation, that creates a new list consisting of every second element of lista starting at index 0 and up to but not including index 4
| Confusing expression in python | If I have the list:
lista=[99, True, "Una Lista", [1,3]]
What does the following expression mean?
mi_var = lista[0:4:2]
| [
"The syntax lista[0:4:2] is called extended slice syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), but only including the even indexes (step = 2).\nIn your example it will give [99, \"Una Lista\"]. More generally you can get a slice consisting of every ele... | [
8,
0,
0
] | [] | [] | [
"list",
"python",
"slice"
] | stackoverflow_0004027103_list_python_slice.txt |
Q:
Python differences between running as script and running via interactive shell
I am attempting to debug a problem with a ctypes wrapper of a windows DLL and have noticed differences when I run tests via an interactive shell (python or ipython) and when I run the scripts non-interactively.
I was wondering if there is any explanation for the differences I am seeing here?
Specifically, when I interactively run a simple test, a DLL call will hang and never return, where as exactly the same code run as a script will not exhibit this problem.
To be more explicit with what I mean here, imagine you had the following code
from foobar import bar, foo
bar(foo(1,2,3))
When put in a file, say "myfoo.py", and excecuted via "python myfoo.py", the above code executes as expected. However, if you type in the above into a python/ipython shell, the code behaves differently (in my case, hangs when calling a ctypes.WinDLL function)
Some additional details:
I am using the same interpreter and the same PYTHONPATH in both cases.
The DLL being wrapped is the Canon EDSDKv2.9, a SDK to remotely control cameras.
It is always hangs in the DLL, not in python code.
When initialised, my EDSDK wrapper launches a thread whose run method looks like this:
def run(self):
sys.coinit_flags = 0 #use multithreaded mode
from pythoncom import PumpWaitingMessages
#^^ done here so this thread is correctly initialised
error(EDSDK.EdsInitializeSDK())
self.EDSDK_initialised = True
while self.active:
PumpWaitingMessages()
sleep(self.msg_sleep_time)
error(EDSDK.EdsTerminateSDK())
This threads purpose is basically to initialise the SDK, pump messages, and allow other threads to call wrapped methods.
Note: this has worked, both interactively and non-interactively, in previous EDSDK versions. My current problem only happens in the latest version of EDSDK.
I suspect it may be something to do with threads (hence the snippet), but can't find any information online to back up my suspicion.
So, is anyone aware of any differences when running python interactively and non-interactively? Possibly related to windows threads? Any help, even wild guesses, would be appreciated at this point, because I am completely stumped! :)
A:
The Python interactive interpreter is not thread safe. So, if you try to send a blocking command, the whole interpreter will hang.
See this article as to why this happens (tl; dr is that the IDLE and threads don't mix). As for how to fix this, use the console rather than the IDLE GUI. Or, you can just use a script.
A:
This is something to keep in mind in the context of asynchronous or concurrent operations (e.g. multithreading, multiprocessing). For all intents and purposes when you're running Python interactively you do not have a main loop. Even though __name__ is set to __main__, anything assigned or executed there might not be available. This is especially the case with multiprocessing and in some cases multithreading, where the state of objects may not shared between processes/threads.
This behavior can be confusing at best and dangerous at worst. A good habit to get into when debugging is to always name your threads and pair that with the use of Python's logging module to track what is going on behind the scenes.
| Python differences between running as script and running via interactive shell | I am attempting to debug a problem with a ctypes wrapper of a windows DLL and have noticed differences when I run tests via an interactive shell (python or ipython) and when I run the scripts non-interactively.
I was wondering if there is any explanation for the differences I am seeing here?
Specifically, when I interactively run a simple test, a DLL call will hang and never return, where as exactly the same code run as a script will not exhibit this problem.
To be more explicit with what I mean here, imagine you had the following code
from foobar import bar, foo
bar(foo(1,2,3))
When put in a file, say "myfoo.py", and excecuted via "python myfoo.py", the above code executes as expected. However, if you type in the above into a python/ipython shell, the code behaves differently (in my case, hangs when calling a ctypes.WinDLL function)
Some additional details:
I am using the same interpreter and the same PYTHONPATH in both cases.
The DLL being wrapped is the Canon EDSDKv2.9, a SDK to remotely control cameras.
It is always hangs in the DLL, not in python code.
When initialised, my EDSDK wrapper launches a thread whose run method looks like this:
def run(self):
sys.coinit_flags = 0 #use multithreaded mode
from pythoncom import PumpWaitingMessages
#^^ done here so this thread is correctly initialised
error(EDSDK.EdsInitializeSDK())
self.EDSDK_initialised = True
while self.active:
PumpWaitingMessages()
sleep(self.msg_sleep_time)
error(EDSDK.EdsTerminateSDK())
This threads purpose is basically to initialise the SDK, pump messages, and allow other threads to call wrapped methods.
Note: this has worked, both interactively and non-interactively, in previous EDSDK versions. My current problem only happens in the latest version of EDSDK.
I suspect it may be something to do with threads (hence the snippet), but can't find any information online to back up my suspicion.
So, is anyone aware of any differences when running python interactively and non-interactively? Possibly related to windows threads? Any help, even wild guesses, would be appreciated at this point, because I am completely stumped! :)
| [
"The Python interactive interpreter is not thread safe. So, if you try to send a blocking command, the whole interpreter will hang.\nSee this article as to why this happens (tl; dr is that the IDLE and threads don't mix). As for how to fix this, use the console rather than the IDLE GUI. Or, you can just use a scrip... | [
1,
1
] | [] | [] | [
"com",
"ctypes",
"multithreading",
"python"
] | stackoverflow_0004026820_com_ctypes_multithreading_python.txt |
Q:
Python 2.7/Windows resizable ttk progressbar?
I'm experimenting with Python 2.7's new Tkinter Tile support (ttk). Is there a way to make the ttk.Progressbar() control auto-resize in proportion to its parent container? In reading the documentation on this control, it appears that one must explicitly set this widget's height or width?
I'm looking for a way to place the ttk.Progressbar widget in a horizontally resizable Tkinter dialog and have this widget resize as a user resize's the parent dialog.
Is there a window or frame resize event that I can trap, a ttk.Progressbar setting I can .config(), or .pack() option I can use to achieve my goal?
Any suggestions appreciated.
A:
Try using the fill option of pack (or grid) to have the widget fill its container.
import Tkinter as tk
import ttk
root=tk.Tk()
pb = ttk.Progressbar(mode="indeterminate")
pb.pack(side="bottom", fill="x")
pb.start()
root.wm_geometry("300x300")
root.mainloop()
| Python 2.7/Windows resizable ttk progressbar? | I'm experimenting with Python 2.7's new Tkinter Tile support (ttk). Is there a way to make the ttk.Progressbar() control auto-resize in proportion to its parent container? In reading the documentation on this control, it appears that one must explicitly set this widget's height or width?
I'm looking for a way to place the ttk.Progressbar widget in a horizontally resizable Tkinter dialog and have this widget resize as a user resize's the parent dialog.
Is there a window or frame resize event that I can trap, a ttk.Progressbar setting I can .config(), or .pack() option I can use to achieve my goal?
Any suggestions appreciated.
| [
"Try using the fill option of pack (or grid) to have the widget fill its container.\nimport Tkinter as tk\nimport ttk\n\nroot=tk.Tk()\npb = ttk.Progressbar(mode=\"indeterminate\")\npb.pack(side=\"bottom\", fill=\"x\")\npb.start()\nroot.wm_geometry(\"300x300\")\nroot.mainloop()\n\n"
] | [
1
] | [] | [] | [
"progress_bar",
"python",
"tkinter",
"ttk",
"user_interface"
] | stackoverflow_0004027120_progress_bar_python_tkinter_ttk_user_interface.txt |
Q:
single list to dictionary
I have this list:
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
What's the best way to create a dictionary from this?
Thanks.
A:
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(single[::2], single[1::2]))
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
A:
Similar to SilentGhost's solution, without building temporary lists:
>>> from itertools import izip
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> si = iter(single)
>>> dict(izip(si, si))
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
A:
This is the simplest I guess. You will see more wizardry in solution here using list comprehension etc
dictObj = {}
for x in range(0, len(single), 2):
dictObj[single[x]] = single[x+1]
Output:
>>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
>>> dictObj = {}
>>> for x in range(0, len(single), 2):
... dictObj[single[x]] = single[x+1]
...
>>>
>>> dictObj
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
>>>
A:
L = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
d = dict(L[n:n+2] for n in xrange(0, len(L), 2))
A:
>>> single = ['key', 'value', 'key2', 'value2', 'key3', 'value3']
>>> dict(zip(*[iter(single)]*2))
{'key3': 'value3', 'key2': 'value2', 'key': 'value'}
Probably not the most readable version though ;)
A:
You haven't specified any criteria for "best". If you want understandability, simplicity, easily modified to check for duplicates and odd number of inputs, works with any iterable (in case you can't find out the length in advance), NO EXTRA MEMORY USED, ... try this:
def load_dict(iterable):
d = {}
pair = False
for item in iterable:
if pair:
# insert duplicate check here
d[key] = item
else:
key = item
pair = not pair
if pair:
grumble_about_odd_length(key)
return d
| single list to dictionary | I have this list:
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
What's the best way to create a dictionary from this?
Thanks.
| [
">>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']\n>>> dict(zip(single[::2], single[1::2]))\n{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}\n\n",
"Similar to SilentGhost's solution, without building temporary lists:\n>>> from itertools import izip\n>>> single = ['key1', 'value1', 'key2'... | [
11,
8,
2,
0,
0,
0
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004026080_dictionary_list_python.txt |
Q:
How to import protocol buffer definitions from another Python package?
I have my directory structure like this:
root/
sift/
__init__.py
sift_descriptors.proto
sift_descriptors_pb2.py
project/
__init__.py
filtered_descriptors.proto
filtered_descriptors_pb2.py
filtered_descriptors_test.py
The root directory is in my $PYTHONPATH.
I build root/sift/sift_descriptors_pb2.py using protoc --python_out=./ sift_descriptors.proto
I build root/project/filtered_descriptors_pb2.py using /cs/public/lib/pkg/protobuf/bin/protoc --proto_path=../sift --proto_path=./ --python_out=./ filtered_descriptors.proto
In filtered_descriptors.proto, I use import "sift_descriptors.proto"
The problem is that in filtered_descriptors_pb2.py (produced by protoc), there's a statement that just does this bare import: import sift_descriptors_pb2, without reference via the module name as would be needed: from sift import sift_descriptors_pb2.
What am I doing wrong?
A:
You don't add .py to the import statement: "from sift import sift_descriptors_pb2"
A:
I fixed it!
The solution was to use import "sift/sift_descriptors.proto" in filtered_descriptors.proto, and then point protoc to --proto_path=../ instead of --proto_path=../sift.
Then, protoc generates python code that does the import as import sift.sift_descriptors_pb2.
| How to import protocol buffer definitions from another Python package? | I have my directory structure like this:
root/
sift/
__init__.py
sift_descriptors.proto
sift_descriptors_pb2.py
project/
__init__.py
filtered_descriptors.proto
filtered_descriptors_pb2.py
filtered_descriptors_test.py
The root directory is in my $PYTHONPATH.
I build root/sift/sift_descriptors_pb2.py using protoc --python_out=./ sift_descriptors.proto
I build root/project/filtered_descriptors_pb2.py using /cs/public/lib/pkg/protobuf/bin/protoc --proto_path=../sift --proto_path=./ --python_out=./ filtered_descriptors.proto
In filtered_descriptors.proto, I use import "sift_descriptors.proto"
The problem is that in filtered_descriptors_pb2.py (produced by protoc), there's a statement that just does this bare import: import sift_descriptors_pb2, without reference via the module name as would be needed: from sift import sift_descriptors_pb2.
What am I doing wrong?
| [
"You don't add .py to the import statement: \"from sift import sift_descriptors_pb2\"\n",
"I fixed it!\nThe solution was to use import \"sift/sift_descriptors.proto\" in filtered_descriptors.proto, and then point protoc to --proto_path=../ instead of --proto_path=../sift.\nThen, protoc generates python code that... | [
1,
1
] | [] | [] | [
"protocol_buffers",
"python"
] | stackoverflow_0004027414_protocol_buffers_python.txt |
Q:
Python version mismatch, but there's just the one app
I have a C/C++ application in which I define a Python module. I set up Python like this:
PyImport_AppendInittab("myModule", initmymodule);
Py_Initialize();
PyObject *module = PyImport_ImportModule("myModule");
On the ImportModule call, I get this warning:
sys:1: RuntimeWarning: Python C API version mismatch for module myModule: This Python has API version 1012, module myModule has version 1013.
I'm building this app in Xcode, linking against the Python framework in /System/Library/Frameworks (which contains versions 2.3, 2.5 and 2.6). I always include the Python headers with #include <Python/Python.h>. How can my module have a different version if it's part of the same binary that does the initialization?
A:
Are there any other Pythons installed in /Library/Frameworks/, like ones from a python.org installer?
| Python version mismatch, but there's just the one app | I have a C/C++ application in which I define a Python module. I set up Python like this:
PyImport_AppendInittab("myModule", initmymodule);
Py_Initialize();
PyObject *module = PyImport_ImportModule("myModule");
On the ImportModule call, I get this warning:
sys:1: RuntimeWarning: Python C API version mismatch for module myModule: This Python has API version 1012, module myModule has version 1013.
I'm building this app in Xcode, linking against the Python framework in /System/Library/Frameworks (which contains versions 2.3, 2.5 and 2.6). I always include the Python headers with #include <Python/Python.h>. How can my module have a different version if it's part of the same binary that does the initialization?
| [
"Are there any other Pythons installed in /Library/Frameworks/, like ones from a python.org installer?\n"
] | [
0
] | [] | [] | [
"macos",
"python"
] | stackoverflow_0004027670_macos_python.txt |
Q:
Optional parameters in OpenERP field definitions
I couldn't find any documentation of the optional parameters that are available to all field types in OpenERP models, so I added what I knew to the fields documentation page.
There are a bunch of parameters that I don't understand, so I'd appreciate help fleshing out the documentation. You can post answers here, and I'll update the docs, or you can edit the docs yourself. Either one is appreciated.
The specific fields I had questions on are:
change_default
context
priority
select
The states parameter could also use more details.
A:
Are you sure that they are still in use this fields ? because i just did a find /openerp | grep "field" and i didn't find much code that use them ? and because in my experience with openerp the core code is such a mess it's not the first time that i found such a thing (unused code, unused function ...)
but here is what i find until know maybe it can help you :
change_default: in documentation that
you linked change_default is like
on_change but are you sure, because
change_default can be set to (True or
False ) rather on_change is a string
where you specify a function that get
launched when the value is changed in
the view but here is the only thing i
found in the code is this :
#one2many can't be used as condition for defaults
assert(self.change_default != True)
...
take a look on this too :
http://openobject.com/wiki/index.php/Developers:Developper%27s_Book/Objects/ObjectsDefine/ObjectsFields
N.B:
i have openerp version 5.0.14
i will try to add more info as soon as i found more
good luck with the documentation is been a long time that i was waiting a good doc for openerp and up to date
| Optional parameters in OpenERP field definitions | I couldn't find any documentation of the optional parameters that are available to all field types in OpenERP models, so I added what I knew to the fields documentation page.
There are a bunch of parameters that I don't understand, so I'd appreciate help fleshing out the documentation. You can post answers here, and I'll update the docs, or you can edit the docs yourself. Either one is appreciated.
The specific fields I had questions on are:
change_default
context
priority
select
The states parameter could also use more details.
| [
"Are you sure that they are still in use this fields ? because i just did a find /openerp | grep \"field\" and i didn't find much code that use them ? and because in my experience with openerp the core code is such a mess it's not the first time that i found such a thing (unused code, unused function ...) \nbut her... | [
2
] | [] | [] | [
"odoo",
"python"
] | stackoverflow_0004027231_odoo_python.txt |
Q:
Python exit code in SciTE -1073741819
A small piece of python code breaks/exits with -1073741819 within SciTE.
Is there a way to attach a system sound or anything to alert me on exit.
So far, its a silent break.
A:
Scite has way of configuring various aspects of the editor via properties file.
Some of the properties of interest to you configuring following events for system sound:
warning.findwrapped
warning.notfound
warning.wrongfile
warning.executeok
warning.executeko
warning.nootherbookmark
See Scite doc: http://www.scintilla.org/SciTEDoc.html
| Python exit code in SciTE -1073741819 | A small piece of python code breaks/exits with -1073741819 within SciTE.
Is there a way to attach a system sound or anything to alert me on exit.
So far, its a silent break.
| [
"Scite has way of configuring various aspects of the editor via properties file.\nSome of the properties of interest to you configuring following events for system sound:\nwarning.findwrapped\nwarning.notfound\nwarning.wrongfile\nwarning.executeok\nwarning.executeko\nwarning.nootherbookmark\n\nSee Scite doc: http:/... | [
1
] | [] | [] | [
"audio",
"python",
"scite",
"system"
] | stackoverflow_0004027709_audio_python_scite_system.txt |
Q:
Pythonic Boolean Conversion
I'm writing a module to act on data being sent to a database from Python. Since boolean is not a SQL datatype, those values have to be converted to some pre-defined value. I decided while defining the tables that I would use 'T' and 'F' in a varchar(1) field as my Boolean stand in.
In attempting to make this conversion while being properly Pythonic, I did a direct comparison and acted on the results, as so:
if SQLParameters[i] == True:
SQLParameters[i] = 'T'
elif SQLParameters[i] == False:
SQLParameters[i] = 'F'
This is on code that runs regardless of type, so if SQLParameters[i] is 1 or "Blarg" or 123, I just want to leave it alone, whereas when it's a Boolean, I need to perform the conversion.
This worked just fine until I tried to insert the actual value 1 (one), at which point I learned that 1 == True = True. I can plainly see two possible solutions for this issue:
change the data dictionary to use 0 and 1 in a number(1) field as the Boolean stand-in, making the conversion simpler
add a condition to the code above to check the actual type of the parameter to be converted (which strikes me as unpythonic).
Does anyone have an idea about how to accomplish this without either changing the data dictionary or explicitly checking the type?
A:
You can use is:
if SQLParameters[i] is True:
SQLParameters[i] = 'T'
elif SQLParameters[i] is False:
SQLParameters[i] = 'F'
A:
if isinstance(SQLParameters[i], bool):
SQLParameters[i] = 'T' if SQLParameters[i] else 'F'
or
if isinstance(SQLParameters[i], bool):
SQLParameters[i] = 'FT'[SQLParameters[i]]
A:
Try using
if SQLParameters[i] is True:
SQLParameters[i] = 'T'
elif SQLParameters[i] is False:
SQLParameters[i] = 'F'
"is" captures identities. http://docs.python.org/reference/expressions.html
True Pythonic (weak datatyping and abbreviated code) would be
SQLParameters[i] = 'T' if SQLParameters[i] else 'F'
A:
There is no need to explicitly test against the identity or value of SQLParameters[i] being True or False. In Python anything that is unset (such as empty sequences), None, 0, or False evaluates to False; everything else evaluates to True.
So with that in mind you could simply do this:
if SQLParameters[i]:
SQLParameters[i] = 'T'
else:
SQLParameters[i] = 'F'
A:
You could check the type of the object:
In [8]: isinstance(True, bool)
Out[8]: True
In [9]: isinstance(1, bool)
Out[9]: False
A:
I do recommend that you use 0 and 1. The SQLite libary does it that way. I would explicitly set the new value to False and then change it to true (or vice versa).
convertedvalue = 0
if SQLParameters[i] is True:
convertedvalue = 1
SQLParameters[i] = convertedvalue
| Pythonic Boolean Conversion | I'm writing a module to act on data being sent to a database from Python. Since boolean is not a SQL datatype, those values have to be converted to some pre-defined value. I decided while defining the tables that I would use 'T' and 'F' in a varchar(1) field as my Boolean stand in.
In attempting to make this conversion while being properly Pythonic, I did a direct comparison and acted on the results, as so:
if SQLParameters[i] == True:
SQLParameters[i] = 'T'
elif SQLParameters[i] == False:
SQLParameters[i] = 'F'
This is on code that runs regardless of type, so if SQLParameters[i] is 1 or "Blarg" or 123, I just want to leave it alone, whereas when it's a Boolean, I need to perform the conversion.
This worked just fine until I tried to insert the actual value 1 (one), at which point I learned that 1 == True = True. I can plainly see two possible solutions for this issue:
change the data dictionary to use 0 and 1 in a number(1) field as the Boolean stand-in, making the conversion simpler
add a condition to the code above to check the actual type of the parameter to be converted (which strikes me as unpythonic).
Does anyone have an idea about how to accomplish this without either changing the data dictionary or explicitly checking the type?
| [
"You can use is:\nif SQLParameters[i] is True:\n SQLParameters[i] = 'T' \nelif SQLParameters[i] is False:\n SQLParameters[i] = 'F'\n\n",
"if isinstance(SQLParameters[i], bool):\n SQLParameters[i] = 'T' if SQLParameters[i] else 'F'\n\nor\nif isinstance(SQLParameters[i], bool):\n SQLParam... | [
9,
3,
1,
1,
0,
0
] | [] | [] | [
"boolean",
"database",
"python"
] | stackoverflow_0004027773_boolean_database_python.txt |
Q:
Return minimum X (that can contain Y items) for arbitrary number of items
Feeling pretty brain-dead right now. I can, of course, brute-force this, but I feel like there has to be a simple function to return this number. Concerning native functions, I'm using PHP and/or Python.
For example: there exists containers that hold X (5) breadsticks each, and
I need to feed Y (25) people Z (3) breadsticks each.
I need to return the number of containers I have to acquire to feed these people. (There may or may not be remainder breadsticks).
EDIT: Clarified some intention.
A:
It sounds like you want arithmetic:
min_containers = y*z/x
If you have situations that may give a remainder:
min_full_containers = floor(y*z/x)
remaining_items = y*z%x
A:
def f(X, Y, Z):
d, r = divmod(Y * Z, X)
return d + bool(r)
A:
#python
import math
int(math.ceil(float(Y) * Z / X))
A:
Ned's answer is correct. It is also common to avoid the function call overhead to math.ceil() by doing the following:
minContainers = int((y*z+(x-1))/x);
A:
In Python, use // (integer floor division, introduced in Python 2.2) and force it to round up:
number_required = y * z
container_holds = x
reqd_containers = (number_required + container_holds - 1) // container_holds
or if you require the so-called "professional programmer" version instead of the explanatory version:
n=(y*z+(x-1))//x;
or if you are really afraid of carpal tunnel syndrome, chop the two redundant parentheses and the semicolon:
n=(y*z+x-1)//x
Note: this solution works on both Python 2 (where 10 / 3 -> 3) and Python 3 (where 10 / 3 -> 3.3333333333333335)
Other "solutions" not only use unnecessary function calls but also fail with large numbers:
# wrong in Python 3; works with Python 2.3 to 2.7
# int overflow with Pythons up to 2.2
>>> int((100000000000000000 + 2)/3)
33333333333333332 # last digit should be 4
# wrong with Python 2.3 onwards; int overflow with earlier versions
>>> import math
>>> int(math.ceil(float(100000000000000000) / 3))
33333333333333332L
| Return minimum X (that can contain Y items) for arbitrary number of items | Feeling pretty brain-dead right now. I can, of course, brute-force this, but I feel like there has to be a simple function to return this number. Concerning native functions, I'm using PHP and/or Python.
For example: there exists containers that hold X (5) breadsticks each, and
I need to feed Y (25) people Z (3) breadsticks each.
I need to return the number of containers I have to acquire to feed these people. (There may or may not be remainder breadsticks).
EDIT: Clarified some intention.
| [
"It sounds like you want arithmetic:\nmin_containers = y*z/x\n\nIf you have situations that may give a remainder:\nmin_full_containers = floor(y*z/x)\nremaining_items = y*z%x\n\n",
"def f(X, Y, Z):\n d, r = divmod(Y * Z, X)\n return d + bool(r)\n\n",
"#python\nimport math\n\nint(math.ceil(float(Y) * Z / X))\n... | [
3,
2,
1,
1,
1
] | [
"($people * $breadSticksPerPerson) / $holders isn't correct?\nEDIT: Sorry, misread your question, posted the correct solution in comments\n"
] | [
-1
] | [
"math",
"php",
"python"
] | stackoverflow_0004027975_math_php_python.txt |
Q:
Numpy array broadcasting with vector parameters
Is it possible to do array broadcasting in numpy with parameters that are vectors?
For example, I know that I can do this
def bernoulli_fraction_to_logodds(fraction):
if fraction == 1.0:
return inf
return log(fraction / (1 - fraction))
bernoulli_fraction_to_logodds = numpy.frompyfunc(bernoulli_fraction_to_logodds, 1, 1)
and have it work with the whole array. What if I have a function that take a 2-element vector and returns a 2-element vector. Can I pass it an array of 2-element vectors? E.g.,
def beta_ml_fraction(beta):
a = beta[0]
b = beta[1]
return a / (a + b)
beta_ml_fraction = numpy.frompyfunc(beta_ml_fraction, 1, 1)
Unfortunately, this doesn't work. Is there a similar function to from_py_func that works. I can hack around this when they are 2-element vectors, but what about when they are n-element vectors?
Thus, input of (2,3) should give 0.4, but input of [[2,3], [3,3]] should give [0.4, 0.5].
A:
I don't think frompyfunc can do this, though I could be wrong.
Regarding np.vectorize A. M. Archibald wrote:
In fact, anything that goes through
python code for the "combine two
scalars" will be slow. The slowness of
looping in python is not because
python's looping constructs are slow,
it's because executing python code is
slow. So vectorize is kind of a cheat
- it doesn't actually run fast, but it is convenient.
So np.frompyfunc (and np.vectorize) are just syntactic sugar -- they don't make Python functions run any faster.
After realizing that, my interest in frompyfunc flagged (to near zero).
There is nothing unreadable about a Python loop, so either use one explicitly,
or rewrite the function to truly leverage numpy (by writing truly vectorized equations).
import numpy as np
def beta_ml_fraction(beta):
a = beta[:,0]
b = beta[:,1]
return a / (a + b)
arr=np.array([(2,3)],dtype=np.float)
print(beta_ml_fraction(arr))
# [ 0.4]
arr=np.array([(2,3),(3,3)],dtype=np.float)
print(beta_ml_fraction(arr))
# [ 0.4 0.5]
A:
When dealing with bidimensional vector array I like to keep the x and y components as the first index. For this I make heavy use of the transpose()
def beta_ml_fraction(beta):
a = beta[0]
b = beta[1]
return a / (a + b)
arr=np.array([(2,3),(3,3)],dtype=np.float)
print(beta_ml_fraction(arr.transpose()))
# [ 0.4 0.5]
the advantage of this approach is that handling multidimensional array of bi-dimensional vector becomes easiear.
x = np.arange(18,dtype=np.float).reshape(2,3,3)
print(x)
#array([[[ 0., 1., 2.],
# [ 3., 4., 5.],
# [ 6., 7., 8.]],
#
# [[ 9., 10., 11.],
# [ 12., 13., 14.],
# [ 15., 16., 17.]]])
print(beta_ml_fraction(x))
#array([[ 0. , 0.09090909, 0.15384615],
# [ 0.2 , 0.23529412, 0.26315789],
# [ 0.28571429, 0.30434783, 0.32 ]])
| Numpy array broadcasting with vector parameters | Is it possible to do array broadcasting in numpy with parameters that are vectors?
For example, I know that I can do this
def bernoulli_fraction_to_logodds(fraction):
if fraction == 1.0:
return inf
return log(fraction / (1 - fraction))
bernoulli_fraction_to_logodds = numpy.frompyfunc(bernoulli_fraction_to_logodds, 1, 1)
and have it work with the whole array. What if I have a function that take a 2-element vector and returns a 2-element vector. Can I pass it an array of 2-element vectors? E.g.,
def beta_ml_fraction(beta):
a = beta[0]
b = beta[1]
return a / (a + b)
beta_ml_fraction = numpy.frompyfunc(beta_ml_fraction, 1, 1)
Unfortunately, this doesn't work. Is there a similar function to from_py_func that works. I can hack around this when they are 2-element vectors, but what about when they are n-element vectors?
Thus, input of (2,3) should give 0.4, but input of [[2,3], [3,3]] should give [0.4, 0.5].
| [
"I don't think frompyfunc can do this, though I could be wrong.\nRegarding np.vectorize A. M. Archibald wrote:\n\nIn fact, anything that goes through\n python code for the \"combine two\n scalars\" will be slow. The slowness of\n looping in python is not because\n python's looping constructs are slow,\n it's b... | [
4,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004024350_numpy_python.txt |
Q:
extract a sentence using python
I would like to extract the exact sentence if a particular word is present in that sentence. Could anyone let me know how to do it with python. I used concordance() but it only prints lines where the word matches.
A:
Just a quick reminder: Sentence breaking is actually a pretty complex thing, there's exceptions to the period rule, such as "Mr." or "Dr." There's also a variety of sentence ending punctuation marks. But there's also exceptions to the exception (if the next word is Capitalized and is not a proper noun, then Dr. can end a sentence, for example).
If you're interested in this (it's a natural language processing topic) you could check out:
the natural language tool kit's (nltk) punkt module.
A:
If you have each sentence in a string you can use find() on your word and if found return the sentence. Otherwise you could use a regex, something like this
pattern = "\.?(?P<sentence>.*?good.*?)\."
match = re.search(pattern, yourwholetext)
if match != None:
sentence = match.group("sentence")
I havent tested this but something along those lines.
My test:
import re
text = "muffins are good, cookies are bad. sauce is awesome, veggies too. fmooo mfasss, fdssaaaa."
pattern = "\.?(?P<sentence>.*?good.*?)\."
match = re.search(pattern, text)
if match != None:
print match.group("sentence")
A:
dutt did a good job answering this. just wanted to add a couple things
import re
text = "go directly to jail. do not cross go. do not collect $200."
pattern = "\.(?P<sentence>.*?(go).*?)\."
match = re.search(pattern, text)
if match != None:
sentence = match.group("sentence")
obviously, you'll need to import the regex library (import re) before you begin. here is a teardown of what the regular expression actually does (more info can be found at the Python re library page)
\. # looks for a period preceding sentence.
(?P<sentence>...) # sets the regex captured to variable "sentence".
.*? # selects all text (non-greedy) until the word "go".
again, the link to the library ref page is key.
| extract a sentence using python | I would like to extract the exact sentence if a particular word is present in that sentence. Could anyone let me know how to do it with python. I used concordance() but it only prints lines where the word matches.
| [
"Just a quick reminder: Sentence breaking is actually a pretty complex thing, there's exceptions to the period rule, such as \"Mr.\" or \"Dr.\" There's also a variety of sentence ending punctuation marks. But there's also exceptions to the exception (if the next word is Capitalized and is not a proper noun, then ... | [
4,
1,
0
] | [] | [] | [
"python",
"text_segmentation"
] | stackoverflow_0004001800_python_text_segmentation.txt |
Q:
OSS implementation of Google app engine?
After Google pioneered map-reduce the community came out with Hadoop, is there a OSS Google AppEngine project? Or, put another way: What is the best off the shelf python or java cloud software?
Specifically I'm looking for something that I could host on my own and have some sort of auto-scale feature (more frequently used apps would be replicated or something).
Is this a pipe dream? or is there something out there?
A:
I'm not sure what you mean by having an OSS version of Google app engine, but AppScale is an open source framework for running Google app engine apps. You'll have to provide your own cloud, however.
I think with the right technical expertise and hardware you could host this on your own. Not so sure about auto-scaling, but I'm sure there's a programmatic solution to that.
A:
Don't forget TyphoonAE, which is similar to AppScale. TyphoonAE does a better job of keeping current with GAE/Python then AppScale does.
Both can easily be deployed to Amazon EC2.
| OSS implementation of Google app engine? | After Google pioneered map-reduce the community came out with Hadoop, is there a OSS Google AppEngine project? Or, put another way: What is the best off the shelf python or java cloud software?
Specifically I'm looking for something that I could host on my own and have some sort of auto-scale feature (more frequently used apps would be replicated or something).
Is this a pipe dream? or is there something out there?
| [
"I'm not sure what you mean by having an OSS version of Google app engine, but AppScale is an open source framework for running Google app engine apps. You'll have to provide your own cloud, however.\nI think with the right technical expertise and hardware you could host this on your own. Not so sure about auto-sca... | [
9,
5
] | [] | [] | [
"cloud",
"google_app_engine",
"java",
"python"
] | stackoverflow_0004026816_cloud_google_app_engine_java_python.txt |
Q:
Python and win32 API - using a C file
With ActiveState Python comes a win32api module. I need to implement something that monitors directories recursively for file-changes. Actually there's an example in the MSDN library using C. I don't know whether the win32api bindings are sufficient for something like this.
Can I import this into a Python project? Because it may be easier to write the file-alteration monitor itself in C, and to handle the results within Python. The problem is: how do I make that interact with each other.
A:
Why not try some of the python win32 examples here. It uses pywin32 and does what you want.
http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
The "C" code that you have mentioned with link to MSDN uses FindFirstChangeNotification. Tim Golden's example uses the same through python win32 bindings. I guess this is what you want.
All windows APIs are exposed and can be utilized via pywin32.
A:
Read the documentation and try it out for yourself. win32file.FindFirstChangeNotification, etc. are there and work.
| Python and win32 API - using a C file | With ActiveState Python comes a win32api module. I need to implement something that monitors directories recursively for file-changes. Actually there's an example in the MSDN library using C. I don't know whether the win32api bindings are sufficient for something like this.
Can I import this into a Python project? Because it may be easier to write the file-alteration monitor itself in C, and to handle the results within Python. The problem is: how do I make that interact with each other.
| [
"Why not try some of the python win32 examples here. It uses pywin32 and does what you want.\n\nhttp://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html\n\nThe \"C\" code that you have mentioned with link to MSDN uses FindFirstChangeNotification. Tim Golden's example uses the same through pytho... | [
4,
2
] | [] | [] | [
"c++",
"python",
"winapi"
] | stackoverflow_0004028571_c++_python_winapi.txt |
Q:
Python ignores SIGINT in multithreaded programs - how to fix that?
I have Python 2.6 on MacOS X and a multithread operation. Following test code works fine and shuts down app on Ctrl-C:
import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
def run( self ) :
while True :
time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )
But if i change only one string, adding some real work to worker thread, the app will never terminate on Ctrl-C:
import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
def run( self ) :
while True :
os.system( "svn up" ) # This is really slow and can fail.
time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )
Is it possible to fix it, or python is not intended to be used with threading?
A:
I'm not an expert on Threads with Python but quickly reading the docs leads to a few conclusions.
1) Calling os.system() spawns a new subshell and is not encouraged. Instead the subprocess module should be used. http://docs.python.org/release/2.6.6/library/os.html?highlight=os.system#os.system
2) The threading module doesn't seem to give a whole lot of control to the threads, maybe try using the thread module, at least there is a thread.exit() function. Also from the threading docs here it says that dummy threads may be created, which are always alive and daemonic, furthermore
"… the entire Python program exits when only daemon threads are left."
So, I would imagine that the least you need to do is signal the currently running threads that they need to exit, before exiting the main thread, or joining them on ctrl-c to allow them to finish (although this would obviously be contradictory to ctrl-c), or perhaps just using the subprocess module to spawn the svn up would do the trick.
A:
A couple of things which may be causing your problem:
The Ctrl-C is perhaps being caught by svn, which is ignoring it.
You are creating a thread which is a non-daemon thread, then just exiting the process. This will cause the process to wait until the thread exits - which it never will. You need to either make the thread a daemon or give it a way to terminate it and join() it before exiting. While it always seems to stop on my Linux system, MacOS X behaviour may be different.
Python works well enough with threads :-)
Update: You could try using subprocess, setting up the child process so that file handles are not inherited, and setting the child's stdin to subprocess.PIPE.
A:
You likely do not need threads at all.
Try using Python's subprocess module, or even Twisted's process support.
| Python ignores SIGINT in multithreaded programs - how to fix that? | I have Python 2.6 on MacOS X and a multithread operation. Following test code works fine and shuts down app on Ctrl-C:
import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
def run( self ) :
while True :
time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )
But if i change only one string, adding some real work to worker thread, the app will never terminate on Ctrl-C:
import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
def run( self ) :
while True :
os.system( "svn up" ) # This is really slow and can fail.
time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )
Is it possible to fix it, or python is not intended to be used with threading?
| [
"I'm not an expert on Threads with Python but quickly reading the docs leads to a few conclusions.\n1) Calling os.system() spawns a new subshell and is not encouraged. Instead the subprocess module should be used. http://docs.python.org/release/2.6.6/library/os.html?highlight=os.system#os.system\n2) The threading m... | [
2,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0004022248_python.txt |
Q:
python regex finding all groups of words
Here is what I have so far
text = "Hello world. It is a nice day today. Don't you think so?"
re.findall('\w{3,}\s{1,}\w{3,}',text)
#['Hello world', 'nice day', 'you think']
The desired output would be ['Hello world', 'nice day', 'day today', 'today Don't', 'Don't you', 'you think']
Can this be done with a simple regex pattern?
A:
map(lambda x: x[0] + x[1], re.findall('(\w{3,}(?=(\s{1,}\w{3,})))',text))
May be you can rewrite the lambda for shorter (like just '+')
And BTW ' is not part of \w or \s
A:
Something like this with additional checks for list boundaries should do:
>>> text = "Hello world. It is a nice day today. Don't you think so?"
>>> k = text.split()
>>> k
['Hello', 'world.', 'It', 'is', 'a', 'nice', 'day', 'today.', "Don't", 'you', 'think', 'so?']
>>> z = [x for x in k if len(x) > 2]
>>> z
['Hello', 'world.', 'nice', 'day', 'today.', "Don't", 'you', 'think', 'so?']
>>> [z[n]+ " " + z[n+1] for n in range(0, len(z)-1, 2)]
['Hello world.', 'nice day', "today. Don't", 'you think']
>>>
A:
There are two problems with your approach:
Neither \w nor \s matches punctuation.
When you match a string with a regular expression using findall, that part of the string is consumed. Searching for the next match commences immediately after the end of the previous match. Because of this a word can't be included in two separate matches.
To solve the first issue you need to decide what you mean by a word. Regular expressions aren't good for this sort of parsing. You might want to look at a natural language parsing library instead.
But assuming that you can come up with a regular expression that works for your needs, to fix the second problem you can use a lookahead assertion to check the second word. This won't return the entire match as you want but you can at least find the first word in each word pair using this method.
re.findall('\w{3,}(?=\s{1,}\w{3,})',text)
^^^ ^
lookahead assertion
A:
import itertools as it
import re
three_pat=re.compile(r'\w{3}')
text = "Hello world. It is a nice day today. Don't you think so?"
for key,group in it.groupby(text.split(),lambda x: bool(three_pat.match(x))):
if key:
group=list(group)
for i in range(0,len(group)-1):
print(' '.join(group[i:i+2]))
# Hello world.
# nice day
# day today.
# today. Don't
# Don't you
# you think
It not clear to me what you want done with all punctuation. On the one hand, it looks like you want periods to be removed, but single quotation marks to be kept. It would be easy to implement the removal of periods, but before I do, would you clarify what you want to happen to all punctuation?
| python regex finding all groups of words | Here is what I have so far
text = "Hello world. It is a nice day today. Don't you think so?"
re.findall('\w{3,}\s{1,}\w{3,}',text)
#['Hello world', 'nice day', 'you think']
The desired output would be ['Hello world', 'nice day', 'day today', 'today Don't', 'Don't you', 'you think']
Can this be done with a simple regex pattern?
| [
"map(lambda x: x[0] + x[1], re.findall('(\\w{3,}(?=(\\s{1,}\\w{3,})))',text))\n\nMay be you can rewrite the lambda for shorter (like just '+')\nAnd BTW ' is not part of \\w or \\s\n",
"Something like this with additional checks for list boundaries should do:\n>>> text = \"Hello world. It is a nice day today. Don'... | [
1,
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004028480_python_regex.txt |
Q:
PyQt4: Removing a child from its parent
I've created two uis using the Qt Designer, imported them into my script and set them in the normal way using the setupUi() method. When a button is clicked, and the appropriate method is executed, the new ui is loaded, but all of the widgets and connections from the old one persist.
What is the proper way to remove the connections and then delete all of the MainWindow's current children so that only the new ui's widgets and connections remain? Below is a simplified example of what I'm doing.
from PyQt4 import QtGui, QtCore
from Models import *
from Backward import Ui_Backward
from Forward import Ui_Forward
class MainWindow( QtGui.QMainWindow ):
def __init__( self ):
QtGui.QMainWindow.__init__( self, None )
self.move_forward()
def move_forward( self ):
self.ui = Ui_Forward()
self.ui.setupUi( self )
self.connect( self.ui.Button, QtCore.SIGNAL('clicked()'), self.move_backward )
def move_backward( self ):
self.ui = Ui_Backward()
self.ui.setupUi( self )
self.connect( self.ui.Button, QtCore.SIGNAL('clicked()'), self.move_forward )
Once Ui_Forward is set and the button is pressed, Ui_Backward is set correctly, but all of the widgets from Ui_Forward are still in the MainWindow's list of children.
A:
I'm trying to imagine what your goal is here. If you are trying to implement a wizard type application where the screen presents one set of controls and then switches to another screen with forward and backward buttons then you should try using a QStackedWidget.
A QStackedWidget will allow you to define one or more "pages" and switch between them. You design each page independently without (necessarily) having to move controls from one page to the next.
| PyQt4: Removing a child from its parent | I've created two uis using the Qt Designer, imported them into my script and set them in the normal way using the setupUi() method. When a button is clicked, and the appropriate method is executed, the new ui is loaded, but all of the widgets and connections from the old one persist.
What is the proper way to remove the connections and then delete all of the MainWindow's current children so that only the new ui's widgets and connections remain? Below is a simplified example of what I'm doing.
from PyQt4 import QtGui, QtCore
from Models import *
from Backward import Ui_Backward
from Forward import Ui_Forward
class MainWindow( QtGui.QMainWindow ):
def __init__( self ):
QtGui.QMainWindow.__init__( self, None )
self.move_forward()
def move_forward( self ):
self.ui = Ui_Forward()
self.ui.setupUi( self )
self.connect( self.ui.Button, QtCore.SIGNAL('clicked()'), self.move_backward )
def move_backward( self ):
self.ui = Ui_Backward()
self.ui.setupUi( self )
self.connect( self.ui.Button, QtCore.SIGNAL('clicked()'), self.move_forward )
Once Ui_Forward is set and the button is pressed, Ui_Backward is set correctly, but all of the widgets from Ui_Forward are still in the MainWindow's list of children.
| [
"I'm trying to imagine what your goal is here. If you are trying to implement a wizard type application where the screen presents one set of controls and then switches to another screen with forward and backward buttons then you should try using a QStackedWidget.\nA QStackedWidget will allow you to define one or mo... | [
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0004028401_pyqt_pyqt4_python.txt |
Q:
Can an object's methods act on itself?
I'm not sure where to put some methods.
Let's say I want to send an email.
Which of the following options should I choose:
email = new Email("title", "adress", "body");
email.send();
or
email = new Email("title", "adress", "body");
Postman.send(email);
Because how can an email send itself? And isn't it better to have a central object that handles all emails because then he can regulate things like sending all emails at a specific time, sort mails, remove mails etc.
Also if I want to delete an user, how should I do:
user.delete();
or
administrator.delete(user);
Please share your thoughts about how to know where to put the methods.
A:
I disagree with Arseny. An email can send itself, and that's exactly where the code should live. That's what methods are: actions that can be performed on the object.
However, note that your approaches are not mutually incompatible. An email's send action could easily just contain the code to add itself to the Postman's send queue, and if you do want to regulate the actions, that might be a good idea. But that's no reason not to have a send method for the email class.
A:
All sensible methods that act on emails should be in the email class, for the convenience of users of your class. But email objects should not contain any fields except those related to the content of the email itself (single responsibility principle).
Therefore, I'd suggest this:
class Email
def email(postman)
postman.send(self)
end
end
In statically typed languages, the type of the postman argument should definitely be an interface.
A:
Use the second method to have a class manager handle the objects (emails or users). This follows the single-responsibility-principle.
A:
In Ruby I'd do this:
email = Email.deliver(recipient, subject, message)
The correspoding class would look something like this:
class Email
def self.deliver(recipient, subject, message)
# Do stuff to send mail
end
end
This is clean and easy to use.
On the delete issue: Delete the object you want to delete. So @user.delete would be best. If you want to register the administrator who deleted the user: @user.delete_by(@admin)
A:
I agree with Daniel.
Following your first example, a lot of common widgets would also have a "collections" manager like you mentioned but they don't necessarily. A Tabs widget can show/hide one of its own tabs, without necessarily specifying a new Tab class for each individual one.
I believe functionality should be encapsulated. The example of deleting a user however, is a slightly different case. Having a delete method on the User class could do stuff like clear its own internal variables, settings, etc, but it won't delete the reference to itself. I find that delete methods are better suited for collection-based classes. I wouldn't per se put the delete method on a admin class but rather on a Users "collection" class.
function Users(){
var users = [];
this.add = function(user){
// add user code
users.push(new User(user));
}
this.remove = function(user){
// remove user code and remove it from array
}
}
I don't quite see how an object can fully add/remove itself so it makes sense to me to have that functionality at the collections level. Besides that though, I would say it should be encapsulated within the class it's meant for.
| Can an object's methods act on itself? | I'm not sure where to put some methods.
Let's say I want to send an email.
Which of the following options should I choose:
email = new Email("title", "adress", "body");
email.send();
or
email = new Email("title", "adress", "body");
Postman.send(email);
Because how can an email send itself? And isn't it better to have a central object that handles all emails because then he can regulate things like sending all emails at a specific time, sort mails, remove mails etc.
Also if I want to delete an user, how should I do:
user.delete();
or
administrator.delete(user);
Please share your thoughts about how to know where to put the methods.
| [
"I disagree with Arseny. An email can send itself, and that's exactly where the code should live. That's what methods are: actions that can be performed on the object.\nHowever, note that your approaches are not mutually incompatible. An email's send action could easily just contain the code to add itself to the Po... | [
8,
3,
2,
1,
1
] | [] | [] | [
"design_patterns",
"javascript",
"oop",
"python",
"ruby"
] | stackoverflow_0004022419_design_patterns_javascript_oop_python_ruby.txt |
Q:
Vim's advance word broken in python, how do I fix this?
Vim works fine for all other languages, but word detection seems wonky in python. For example, in the following snippet, with the cursor on the 'h' in shutil, I would expect prssing the w key to advance me to the period, instead I get moved to the "'" in front of export.
shutil.copytree(os.path.join('export', 'app'), os.path.join('export', 'pacakge'))
Any idea what could cause this? How can I detect the cause? How can I fix it?
A:
Look to see what the option "iskeyword" is set to. Chances are the Python syntax file is changing it. Normally it's set to @,48-57,_,192-255.
| Vim's advance word broken in python, how do I fix this? | Vim works fine for all other languages, but word detection seems wonky in python. For example, in the following snippet, with the cursor on the 'h' in shutil, I would expect prssing the w key to advance me to the period, instead I get moved to the "'" in front of export.
shutil.copytree(os.path.join('export', 'app'), os.path.join('export', 'pacakge'))
Any idea what could cause this? How can I detect the cause? How can I fix it?
| [
"Look to see what the option \"iskeyword\" is set to. Chances are the Python syntax file is changing it. Normally it's set to @,48-57,_,192-255.\n"
] | [
1
] | [] | [] | [
"python",
"vim"
] | stackoverflow_0004028839_python_vim.txt |
Q:
How do I run a python file that is read into a std::string using PyRun
I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.
What I have done is loaded a python.py file a std::string but am now having troubles running it. PyRun_SimpleFileEx didn't seem to do the trick either so some help would be great!
std::string content;
if(!ail::read_file(python_script, content))
{
error("Failed to load Python script \"" + python_script + "\"");
return false;
}
if(prompt_mode)
initialise_console();
content = ail::replace_string(content, "\r", "");
Py_Initialize();
initialise_module();
std::string script_directory;
if(get_base_name(python_script, script_directory))
PyRun_SimpleString(("import sys\nsys.path.append('" + script_directory + "')\n").c_str());
write_line("Script dir: " + script_directory);
////-python_script H:\\CRAW\\craw\\script\\craw.py
//content.c_str()
//FILE *fp;
//fp = fopen("H:\\CRAW\\craw\\script\\craw.py", "r");
//PyRun_SimpleFileEx(fp, "craw.py", 1);
if(PyRun_SimpleString(content.c_str()) != 0)
{
write_line("The main Python script contained errors.");
return false;
}
//PyRun_SimpleString(("execfile('" + ail::replace_string(python_script, "\\", "\\\\") + "')").c_str());
return true;
A:
I solved my problem by using a string vector and reading each line of the file into the vector, then executing each one using PyRun_SimpleString.
Here's the finished code, no error checking though.
std::vector string_vector;
std::string content;
if(python_script.empty())
return true;
ail::read_lines(python_script, string_vector);
if(!ail::read_file(python_script, content))
{
error("Failed to load Python script \"" + python_script + "\"");
return false;
}
if(prompt_mode)
initialise_console();
content = ail::replace_string(content, "\r", "");
Py_Initialize();
initialise_module();
std::string script_directory;
if(get_base_name(python_script, script_directory))
PyRun_SimpleString(("import sys\nsys.path.append('" + script_directory + "')\n").c_str());
for(int i = 0; i < string_vector.size(); i++)
{
string_vector[i] = ail::replace_string(string_vector[i], "\r", "");
PyRun_SimpleString(string_vector[i].c_str());
}
return true;
| How do I run a python file that is read into a std::string using PyRun | I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.
What I have done is loaded a python.py file a std::string but am now having troubles running it. PyRun_SimpleFileEx didn't seem to do the trick either so some help would be great!
std::string content;
if(!ail::read_file(python_script, content))
{
error("Failed to load Python script \"" + python_script + "\"");
return false;
}
if(prompt_mode)
initialise_console();
content = ail::replace_string(content, "\r", "");
Py_Initialize();
initialise_module();
std::string script_directory;
if(get_base_name(python_script, script_directory))
PyRun_SimpleString(("import sys\nsys.path.append('" + script_directory + "')\n").c_str());
write_line("Script dir: " + script_directory);
////-python_script H:\\CRAW\\craw\\script\\craw.py
//content.c_str()
//FILE *fp;
//fp = fopen("H:\\CRAW\\craw\\script\\craw.py", "r");
//PyRun_SimpleFileEx(fp, "craw.py", 1);
if(PyRun_SimpleString(content.c_str()) != 0)
{
write_line("The main Python script contained errors.");
return false;
}
//PyRun_SimpleString(("execfile('" + ail::replace_string(python_script, "\\", "\\\\") + "')").c_str());
return true;
| [
"I solved my problem by using a string vector and reading each line of the file into the vector, then executing each one using PyRun_SimpleString.\nHere's the finished code, no error checking though.\n std::vector string_vector;\n std::string content;\n if(python_script.empty())\n re... | [
0
] | [] | [] | [
"c++",
"python"
] | stackoverflow_0004028681_c++_python.txt |
Q:
How do I download a zip file in python using urllib2?
Two part question. I am trying to download multiple archived Cory Doctorow podcasts from the internet archive. The old one's that do not come into my iTunes feed. I have written the script but the downloaded files are not properly formatted.
Q1 - What do I change to download the zip mp3 files?
Q2 - What is a better way to pass the variables into URL?
# and the base url.
def dlfile(file_name,file_mode,base_url):
from urllib2 import Request, urlopen, URLError, HTTPError
#create the url and the request
url = base_url + file_name + mid_url + file_name + end_url
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + url
# Open our local file for writing
local_file = open(file_name, "wb" + file_mode)
#Write to our local file
local_file.write(f.read())
local_file.close()
#handle errors
except HTTPError, e:
print "HTTP Error:",e.code , url
except URLError, e:
print "URL Error:",e.reason , url
# Set the range
var_range = range(150,153)
# Iterate over image ranges
for index in var_range:
base_url = 'http://www.archive.org/download/Cory_Doctorow_Podcast_'
mid_url = '/Cory_Doctorow_Podcast_'
end_url = '_64kb_mp3.zip'
#create file name based on known pattern
file_name = str(index)
dlfile(file_name,"wb",base_url
This script was adapted from here
A:
Here's how I'd deal with the url building and downloading. I'm making sure to name the file as the basename of the url (the last bit after the trailing slash) and I'm also using the with clause for opening the file to write to. This uses a ContextManager which is nice because it will close that file when the block exits. In addition, I use a template to build the string for the url. urlopen doesn't need a request object, just a string.
import os
from urllib2 import urlopen, URLError, HTTPError
def dlfile(url):
# Open the url
try:
f = urlopen(url)
print "downloading " + url
# Open our local file for writing
with open(os.path.basename(url), "wb") as local_file:
local_file.write(f.read())
#handle errors
except HTTPError, e:
print "HTTP Error:", e.code, url
except URLError, e:
print "URL Error:", e.reason, url
def main():
# Iterate over image ranges
for index in range(150, 151):
url = ("http://www.archive.org/download/"
"Cory_Doctorow_Podcast_%d/"
"Cory_Doctorow_Podcast_%d_64kb_mp3.zip" %
(index, index))
dlfile(url)
if __name__ == '__main__':
main()
A:
An older solution on SO along the lines of what you want:
download a zip file to a local drive and extract all files to a destination folder using python 2.5
Python and urllib
| How do I download a zip file in python using urllib2? | Two part question. I am trying to download multiple archived Cory Doctorow podcasts from the internet archive. The old one's that do not come into my iTunes feed. I have written the script but the downloaded files are not properly formatted.
Q1 - What do I change to download the zip mp3 files?
Q2 - What is a better way to pass the variables into URL?
# and the base url.
def dlfile(file_name,file_mode,base_url):
from urllib2 import Request, urlopen, URLError, HTTPError
#create the url and the request
url = base_url + file_name + mid_url + file_name + end_url
req = Request(url)
# Open the url
try:
f = urlopen(req)
print "downloading " + url
# Open our local file for writing
local_file = open(file_name, "wb" + file_mode)
#Write to our local file
local_file.write(f.read())
local_file.close()
#handle errors
except HTTPError, e:
print "HTTP Error:",e.code , url
except URLError, e:
print "URL Error:",e.reason , url
# Set the range
var_range = range(150,153)
# Iterate over image ranges
for index in var_range:
base_url = 'http://www.archive.org/download/Cory_Doctorow_Podcast_'
mid_url = '/Cory_Doctorow_Podcast_'
end_url = '_64kb_mp3.zip'
#create file name based on known pattern
file_name = str(index)
dlfile(file_name,"wb",base_url
This script was adapted from here
| [
"Here's how I'd deal with the url building and downloading. I'm making sure to name the file as the basename of the url (the last bit after the trailing slash) and I'm also using the with clause for opening the file to write to. This uses a ContextManager which is nice because it will close that file when the block... | [
54,
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0004028697_python_urllib2.txt |
Q:
Any ideas about the best work around for __new__ losing its arguments?
So, I only realised today that __new__ is deprecated for receiving arguments, as of python 2.6 (it isn't mentioned in the documentation, which is also not true in terms of the behavior of __new__ calling __init__ as far as I can see). This means my functional code has started raising warnings, and I want to rid myself of them. But I can't see an elegant way to work around.
I have a bunch of classes that perform optimizations when they are constructed. So I have
class Conjunction(Base):
def __new__(cls, a, b):
if a == True:
return b
elif b == True
return a
else:
return super(Conjunction,cls).__new__(cls, a, b)
And so on (real versions cover lots more cases). So unlike what Guido says in this response (the only reference to it I can find), my __new__ method does use its arguments, and cannot be replaced by an overridden __init__ function.
The best I can do is to split this in two:
def Conjunction(a, b):
if a == True:
return b
elif b == True
return a
else:
return ConjunctionImpl(a, b)
class ConjunctionImpl(Base):
# ...
But that is plain ugly and stinks to high heaven. Am I missing an elegant way to have a class constructor return some arbitrary object based on the constructor parameters it is given?
A:
__new__ is not "deprecated for receiving arguments". What changed in Python 2.6 is that object.__new__, the __new__ method of the object class, no longer ignores any arguments it's passed. (object.__init__ also doesn't ignore the arguments anymore, but that's just a warning in 2.6.) You can't use object as the terminating class for your inheritance if you want to pass arguments to __new__ or __init__.
In order for any code to rely on that behaviour to work in 2.6, you just have to replace object as the baseclass, using a baseclass that properly accepts the extra arguments and does not pass them along in the calls it makes (using super().)
A:
Thomas put me right in his answer, but I should add that the solution in my case was trivial: add a __new__ method to my base class with the lines:
class Base(object):
def __new__(cls, *args, **kws):
instance = super(Base, cls).__new__(cls)
instance.__init__(*args, **kws)
return instance
A:
Well this made me curious because I did not see the deprecation in the documentation so I gave it a try myself.
class Foo(object):
def __new__(cls, a, b):
if a:
return a
elif b:
return b
else:
return super(Foo, cls).__new__(cls, a, b)
def __init__(self, a, b):
self.a = a
self.b = b
class Bar(Foo):
def __new__(cls, x, y):
if x:
return x
if y:
return y
else:
return super(Bar, cls).__new__(cls, x, y)
foo = Bar(False, False)
As you can see in this example I overrode the init in Foo because any args passed to new will be forwarded to the cls instance that __new__ attempts to create. The instance of foo with be of a Bar class but it will have members a and b. I caused the super class's __init__ to be called by not overriding it. The method __new__ always passes its args on to __init__. If you don't override the __init__ for object it will fail since that method takes no args.
That's my take on the usage of new in Python 2.7. According to the docs 2.6 is similar.
| Any ideas about the best work around for __new__ losing its arguments? | So, I only realised today that __new__ is deprecated for receiving arguments, as of python 2.6 (it isn't mentioned in the documentation, which is also not true in terms of the behavior of __new__ calling __init__ as far as I can see). This means my functional code has started raising warnings, and I want to rid myself of them. But I can't see an elegant way to work around.
I have a bunch of classes that perform optimizations when they are constructed. So I have
class Conjunction(Base):
def __new__(cls, a, b):
if a == True:
return b
elif b == True
return a
else:
return super(Conjunction,cls).__new__(cls, a, b)
And so on (real versions cover lots more cases). So unlike what Guido says in this response (the only reference to it I can find), my __new__ method does use its arguments, and cannot be replaced by an overridden __init__ function.
The best I can do is to split this in two:
def Conjunction(a, b):
if a == True:
return b
elif b == True
return a
else:
return ConjunctionImpl(a, b)
class ConjunctionImpl(Base):
# ...
But that is plain ugly and stinks to high heaven. Am I missing an elegant way to have a class constructor return some arbitrary object based on the constructor parameters it is given?
| [
"__new__ is not \"deprecated for receiving arguments\". What changed in Python 2.6 is that object.__new__, the __new__ method of the object class, no longer ignores any arguments it's passed. (object.__init__ also doesn't ignore the arguments anymore, but that's just a warning in 2.6.) You can't use object as the t... | [
12,
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004028321_python.txt |
Q:
Loading New Content with Ajax
This is a situation I've run into several times, not sure what the best approach is.
Let's say I have some kind of dynamic content that users can add to via Ajax. For example, take Stack Overflow's comments - people can add comments directly on to the page using Ajax.
The question is, how do I implement the addition itself of the new content. For example, it looks like the ajax call which Stack Overflow uses to add a comment, simply returns html which replaces all of the comments (not just the new one). This way saves redundant logic in the Javascript code which has to "know" what the html looks like.
Is this the best approach? If so, how best to implement it in Django so that there is no redundancy (i.e., so that the view doesn't have to know what the html looks like?)
Thanks!
EDIT: In my specific case, there is no danger of other comments being added in the meantime - this is purely a question of the best implementation.
A:
If the content is simple, I would get JSON and build the HTML in jQuery. If it's complex, I would create a template and call render() on it on the server and return the HTML (which jQuery could either append to other content or replace existing content).
A:
The reason to update all of the comments is to take in account other comments that other people may have also submitted in the meantime. to keep the site truly dynamic, you can do either that, or even, when the page is loaded, load up a variable with the newest submitted comment ID, and set a timer that goes back to check if there are more comments since then. if there are, return them as a JSON object and append them onto the current page a DIV at a time. That would be my preferred way to handle it, because you can then target actions based on each DIV's id or rel, which directly relates back to the comment's ID in the database...
A:
I am not proficient neither with Django nor Python but I suppose the basic logic is similar for all server-side languages.
When weighing the pros and cons of either approach things depend on what you want to optimize. If bandwidth is important then obviously using pure JSON in communication reduces latency when compared to transmitting ready-made HTML.
However, duplicating the server-side view functionality to Javascript is a tedious and error-prone process. It simply takes a lot of time.
I personally feel that in most cases (for small and medium traffic sites) it's perfectly fine to put the HTML fragment together on server side and simply replace the contents of a container (e.g. contents of a div) inside an AJAX callback function. Of course, replacing the whole page would be silly, hence your Django application needs to support outputting specific regions of the document.
| Loading New Content with Ajax | This is a situation I've run into several times, not sure what the best approach is.
Let's say I have some kind of dynamic content that users can add to via Ajax. For example, take Stack Overflow's comments - people can add comments directly on to the page using Ajax.
The question is, how do I implement the addition itself of the new content. For example, it looks like the ajax call which Stack Overflow uses to add a comment, simply returns html which replaces all of the comments (not just the new one). This way saves redundant logic in the Javascript code which has to "know" what the html looks like.
Is this the best approach? If so, how best to implement it in Django so that there is no redundancy (i.e., so that the view doesn't have to know what the html looks like?)
Thanks!
EDIT: In my specific case, there is no danger of other comments being added in the meantime - this is purely a question of the best implementation.
| [
"If the content is simple, I would get JSON and build the HTML in jQuery. If it's complex, I would create a template and call render() on it on the server and return the HTML (which jQuery could either append to other content or replace existing content).\n",
"The reason to update all of the comments is to take i... | [
4,
1,
1
] | [] | [] | [
"ajax",
"django",
"javascript",
"python"
] | stackoverflow_0004027508_ajax_django_javascript_python.txt |
Q:
Getting a Python function to cleanly return a scalar or list, depending on number of arguments
Disclaimer: I'm looking for a Python 2.6 solution, if there is one.
I'm looking for a function that returns a single value when passed a single value, or that returns a sequence when passed multiple values:
>>> a = foo(1)
2
>>> b, c = foo(2, 5)
>>> b
3
>>> c
6
To be clear, this is in an effort to make some function calls simply look nicer than:
a, = foo(1)
or
a = foo(1)[0]
Right now, the inelegant solution is something along these lines:
def foo(*args):
results = [a + 1 for a in args]
return results if len(results) > 1 else results[0]
Is there any syntactic sugar (or functions) that would make this feel cleaner? anything like the following?
def foo(*args):
return *[a + 1 for a in args]
A:
You can always write a decorator to elide that if statement if that is nicer to you:
import functools
def unpacked(method):
@functools.wraps(method)
def _decorator(*args):
result = method(*args)
return results if len(results) != 1 else results[0]
return _decorator
Usage:
@unpacked
def foo(*args):
return [arg + 1 for arg in args]
A:
You can easily write a function scalify that returns the element from the list if the list has only one element, i.e. it tries to make it a scalar (hence the name).
def scalify(l):
return l if len(l) > 1 else l[0]
Then you can use it in your functions like so:
def foo(*args):
return scalify([a + 1 for a in args])
This will do the trick, but I'm with those who suggest you don't do it. For one reason, it rules out iterating over the result unless you know you passed in at least two items. Also, if you have a list, you have to unpack the list when calling the function, losing its "listness," and you know you may not get a list back. These drawbacks seem to me to overshadow any benefit you may see to the technique.
A:
Do you mean you want a tuple with the same number of arguments? Is this not a solution?
return tuple([a + 1 for a in args])
A:
def foo(*args):
return (None, args[0]+1 if args else None, map(lambda a: a + 1, args))[len(args) if len(args) < 3 else 2]
:-) it is hell
A:
This will handle 0 or more args, I think that's what you're looking for.
def foo(*args):
return map(lambda x: x + 1, args) or [None]
edit: I revised to add a None list incase of unpacking 0 args
| Getting a Python function to cleanly return a scalar or list, depending on number of arguments | Disclaimer: I'm looking for a Python 2.6 solution, if there is one.
I'm looking for a function that returns a single value when passed a single value, or that returns a sequence when passed multiple values:
>>> a = foo(1)
2
>>> b, c = foo(2, 5)
>>> b
3
>>> c
6
To be clear, this is in an effort to make some function calls simply look nicer than:
a, = foo(1)
or
a = foo(1)[0]
Right now, the inelegant solution is something along these lines:
def foo(*args):
results = [a + 1 for a in args]
return results if len(results) > 1 else results[0]
Is there any syntactic sugar (or functions) that would make this feel cleaner? anything like the following?
def foo(*args):
return *[a + 1 for a in args]
| [
"You can always write a decorator to elide that if statement if that is nicer to you:\nimport functools\ndef unpacked(method):\n @functools.wraps(method)\n def _decorator(*args):\n result = method(*args)\n return results if len(results) != 1 else results[0]\n return _decorator\n\nUsage:\n@unp... | [
7,
6,
0,
0,
0
] | [] | [] | [
"iterable_unpacking",
"python",
"python_2.6",
"python_2.x"
] | stackoverflow_0004029001_iterable_unpacking_python_python_2.6_python_2.x.txt |
Q:
Can't tell if a file exists on a samba share
I know that the file name is file001.txt or FILE001.TXT, but I don't know which. The file is located on a Windows machine that I'm accessing via samba mount point.
The functions in os.path seem to be acting as though they were case-insensitive, but the open function seems to be case-sensitive:
>>> from os.path import exists, isfile
>>> exists('FILE001.TXT')
True
>>> isfile('FILE001.TXT')
True
>>> open('FILE001.TXT')
Traceback (most recent call last):
File "<console>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'FILE001.TXT'
>>> open('file001.txt') # no problem
So, my questions are these:
Is there a way to determine what the file name is without opening the file (or listing the directory that it's in)?
Why is open case-sensitive when os.path isn't?
Update: thanks for the answers, but this isn't a python problem so I'm closing the question.
A:
You might try adding nocase to the mount in your fstab, as in the example I dug up below if it isn't already there:
//server/acme/app /home/joe/.wine/drive_c/App cifs guest,rw,iocharset=utf8,nocase,file_mode=0777,dir_mode=0777 0 0
Found a link explaining normcase
normcase is a useful little function
that compensates for case-insensitive
operating systems that think that
mahadeva.mp3 and mahadeva.MP3 are the
same file. For instance, on Windows
and Mac OS, normcase will convert the
entire filename to lowercase; on
UNIX-compatible systems, it will
return the filename unchanged.
That tells you that open is probably always expecting a lower case filename on Windows filesystems.
As such, the reason os.path isn't case sensitive is that it probably calls os.path.normcase before checking for the file, while open does not. Though, that might also just be a bug.
A:
To answer your questions:
You can use stat to determine wether a file exists or not without attempting to open it.
Windows Shares filesystems are not case sensitives.
A:
def exists(path):
try:
open(path).close()
except IOError:
return False
return True
Permission issues aside, why don't you want to open the file?
| Can't tell if a file exists on a samba share | I know that the file name is file001.txt or FILE001.TXT, but I don't know which. The file is located on a Windows machine that I'm accessing via samba mount point.
The functions in os.path seem to be acting as though they were case-insensitive, but the open function seems to be case-sensitive:
>>> from os.path import exists, isfile
>>> exists('FILE001.TXT')
True
>>> isfile('FILE001.TXT')
True
>>> open('FILE001.TXT')
Traceback (most recent call last):
File "<console>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'FILE001.TXT'
>>> open('file001.txt') # no problem
So, my questions are these:
Is there a way to determine what the file name is without opening the file (or listing the directory that it's in)?
Why is open case-sensitive when os.path isn't?
Update: thanks for the answers, but this isn't a python problem so I'm closing the question.
| [
"You might try adding nocase to the mount in your fstab, as in the example I dug up below if it isn't already there:\n//server/acme/app /home/joe/.wine/drive_c/App cifs guest,rw,iocharset=utf8,nocase,file_mode=0777,dir_mode=0777 0 0\n\nFound a link explaining normcase\n\nnormcase is a useful little f... | [
1,
0,
0
] | [] | [] | [
"case_insensitive",
"python",
"samba"
] | stackoverflow_0004029280_case_insensitive_python_samba.txt |
Q:
python argument taking 3 arguments? Where?
I'm working with the google safebrowsing api, and the following code:
def getlist(self, type):
dlurl = "safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=" + api_key + "&appver=1.0&pver=2.2"
phish = "googpub-phish-shavar"
mal = "goog-malware-shavar"
self.type = type
if self.type == "phish":
req = urllib.urlopen(dlurl, phish )
data = req.read()
print(data)
Produces the following trace back:
File "./test.py", line 39, in getlist
req = urllib.urlopen(dlurl, phish )
File "/usr/lib/python2.6/urllib.py", line 88, in urlopen
return opener.open(url, data)
File "/usr/lib/python2.6/urllib.py", line 209, in open
return getattr(self, name)(url, data)
TypeError: open_file() takes exactly 2 arguments (3 given)
What am I doing wrong here? I cant spot where 3 arguments are being passed.
BTW, I'm calling this with
x = class()
x.getlist("phish")
A:
Basically, you didn't supply a method in the url, so Python assumed it was a file URL, and tried to open it as a file--which doesn't work (and throws a confusing error message in the process of failing).
Try:
dlurl = "http://safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=" + api_key + "&appver=1.0&pver=2.2"
A:
The function urllib.urlopen opens a network object denoted by a URL for reading. If the URL does not have a scheme identifier, it opens a file.
The appropriate opener is called at line 88 which leads to opener open_file at 209.
If you look at the function:
def open_file(self, url):
"""Use local file or FTP depending on form of URL."""
Answer: you should be providing a scheme like http://...
| python argument taking 3 arguments? Where? | I'm working with the google safebrowsing api, and the following code:
def getlist(self, type):
dlurl = "safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=" + api_key + "&appver=1.0&pver=2.2"
phish = "googpub-phish-shavar"
mal = "goog-malware-shavar"
self.type = type
if self.type == "phish":
req = urllib.urlopen(dlurl, phish )
data = req.read()
print(data)
Produces the following trace back:
File "./test.py", line 39, in getlist
req = urllib.urlopen(dlurl, phish )
File "/usr/lib/python2.6/urllib.py", line 88, in urlopen
return opener.open(url, data)
File "/usr/lib/python2.6/urllib.py", line 209, in open
return getattr(self, name)(url, data)
TypeError: open_file() takes exactly 2 arguments (3 given)
What am I doing wrong here? I cant spot where 3 arguments are being passed.
BTW, I'm calling this with
x = class()
x.getlist("phish")
| [
"Basically, you didn't supply a method in the url, so Python assumed it was a file URL, and tried to open it as a file--which doesn't work (and throws a confusing error message in the process of failing).\nTry:\ndlurl = \"http://safebrowsing.clients.google.com/safebrowsing/downloads?client=api&apikey=\" + api_key +... | [
4,
0
] | [] | [] | [
"arguments",
"python",
"urllib"
] | stackoverflow_0004029747_arguments_python_urllib.txt |
Q:
Python: How to ensure the last line of code has completed?
I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file has written on the disk then read it. Always, the next line of code fires while the file haven't written on disk , and thus error came up. How resolve this?
Okay..
picture.save(path, format='png')
time.sleep(1) #How to ensure the last step has finished
im = Image.open(path)
A:
Seems like you just want to check is that there's a file at path before trying to open it.
You could check for the path's existence before trying to open it and sleep for a bit if it doesn't exist, but that sleep might not be long enough, and you still might have a problem opening the file.
You really should just enclose the open operation in a try-except block:
try:
im = Image.open(path)
except [whatever exception you are getting]:
# Handle the fact that you couldn't open the file
im = None # Maybe like this..
A:
You do not need to do anything unless the previous operation is asynchronous. In your case, you should check picture.save's documentation to see if it specifically define as asynchronous. By default everything is synchronize. Each line will complete before it continues to next operation.
| Python: How to ensure the last line of code has completed? | I'm doing some kind of complex operation, it needs the last line(s) of code has completed, then proceed to the next step, for example. I need to ensure a file has written on the disk then read it. Always, the next line of code fires while the file haven't written on disk , and thus error came up. How resolve this?
Okay..
picture.save(path, format='png')
time.sleep(1) #How to ensure the last step has finished
im = Image.open(path)
| [
"Seems like you just want to check is that there's a file at path before trying to open it.\nYou could check for the path's existence before trying to open it and sleep for a bit if it doesn't exist, but that sleep might not be long enough, and you still might have a problem opening the file.\nYou really should jus... | [
1,
1
] | [] | [] | [
"file",
"python"
] | stackoverflow_0004029784_file_python.txt |
Q:
error: [Errno 32] Broken pipe when paypal calls back to python django app
Hi I am doing papal integration with my django app.
i am using latest version of django from svn and python 2.6.
However, i found every time when paypal's sandbox accessing my notify url i got 500 [Errno 32] Broken pipe my django stack.
Does anyone have similar experience with this ?
Cheers,
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 281, in run
self.finish_response()
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 321, in finish_response
self.write(data)
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 417, in write
self._write(data)
File "/usr/lib/python2.6/socket.py", line 318, in write
self.flush()
File "/usr/lib/python2.6/socket.py", line 297, in flush
self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 104] Connection reset by peer
----------------------------------------
Exception happened during processing of request from ('216.113.191.33', 21736)
Traceback (most recent call last):
File "/usr/lib/python2.6/SocketServer.py", line 283, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.6/SocketServer.py", line 309, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.6/SocketServer.py", line 322, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 562, in __init__
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
File "/usr/lib/python2.6/SocketServer.py", line 618, in __init__
self.finish()
File "/usr/lib/python2.6/SocketServer.py", line 661, in finish
self.wfile.flush()
File "/usr/lib/python2.6/socket.py", line 297, in flush
self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 32] Broken pipe
----------------------------------------
A:
The first error Connection reset by peer show you that the connection have been closed by peer (in your case Pypal) and for the Error Broken pipe this error is raised when a connection is closed suddenly without informing the other peer (in your case your machine).
A:
There are two problems. First, some of the paypal APIs (particularly MassPay) are terribly poor.
The second, and more likely, problem, is that your server is single-threaded and is having trouble properly raising an exception to paypal. I was able to resolve a similar problem by creating an html file with a form (via POST) that mocked a paypal IPN and then looking at the debug result (or better, using a debugger like the one in PyDev). You could do the same thing with curl of course.
| error: [Errno 32] Broken pipe when paypal calls back to python django app | Hi I am doing papal integration with my django app.
i am using latest version of django from svn and python 2.6.
However, i found every time when paypal's sandbox accessing my notify url i got 500 [Errno 32] Broken pipe my django stack.
Does anyone have similar experience with this ?
Cheers,
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 281, in run
self.finish_response()
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 321, in finish_response
self.write(data)
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 417, in write
self._write(data)
File "/usr/lib/python2.6/socket.py", line 318, in write
self.flush()
File "/usr/lib/python2.6/socket.py", line 297, in flush
self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 104] Connection reset by peer
----------------------------------------
Exception happened during processing of request from ('216.113.191.33', 21736)
Traceback (most recent call last):
File "/usr/lib/python2.6/SocketServer.py", line 283, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.6/SocketServer.py", line 309, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.6/SocketServer.py", line 322, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.6/dist-packages/django/core/servers/basehttp.py", line 562, in __init__
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
File "/usr/lib/python2.6/SocketServer.py", line 618, in __init__
self.finish()
File "/usr/lib/python2.6/SocketServer.py", line 661, in finish
self.wfile.flush()
File "/usr/lib/python2.6/socket.py", line 297, in flush
self._sock.sendall(buffer(data, write_offset, buffer_size))
error: [Errno 32] Broken pipe
----------------------------------------
| [
"The first error Connection reset by peer show you that the connection have been closed by peer (in your case Pypal) and for the Error Broken pipe this error is raised when a connection is closed suddenly without informing the other peer (in your case your machine).\n",
"There are two problems. First, some of th... | [
0,
0
] | [] | [] | [
"django",
"paypal",
"python"
] | stackoverflow_0004029297_django_paypal_python.txt |
Q:
Python text to image generation problems
I'm using PIL to load in various fonts and draw text to images. At the basic level, it all works.
However, I am running into a number of problems such as letters being clipped (mainly cursive or stylistic fonts with lots of tails and such). textsize() does return width/height values, yet letters are still clipped. There also doesn't seem to be methods in PIL to specify larger image sizes for the character generating. Another issue is the vertical spacing. It seems PIL returns large height values for certain fonts and thus the vertical spacing between lines is overly large.
I'm in search of a more advanced font and text handling system than PIL, given its apparent limitations.
I've been researching this a lot over the last week (Google, Python docs, Stackoverflow, etc) and I've seen people recommending to use either Imagemagick or a combination of pango and cairo. However, as much as I've read and searched for these respective technologies I am simply not finding any usable documentation that pertains to what I am trying to do. There are some Python bindings for Imagemagick, but they all seem several years out of date.
Can some of the helpful souls here on SO point me to some tutorials on how to use Pango/Cairo and/or Imagemagick?
A:
The Cairo cookbook has a number of examples for using Cairo, and the Python routines are almost mirror images of the C routines.
A:
I've had some fine results with PyGame, but I don't know if it will necessarily solve your problem.
| Python text to image generation problems | I'm using PIL to load in various fonts and draw text to images. At the basic level, it all works.
However, I am running into a number of problems such as letters being clipped (mainly cursive or stylistic fonts with lots of tails and such). textsize() does return width/height values, yet letters are still clipped. There also doesn't seem to be methods in PIL to specify larger image sizes for the character generating. Another issue is the vertical spacing. It seems PIL returns large height values for certain fonts and thus the vertical spacing between lines is overly large.
I'm in search of a more advanced font and text handling system than PIL, given its apparent limitations.
I've been researching this a lot over the last week (Google, Python docs, Stackoverflow, etc) and I've seen people recommending to use either Imagemagick or a combination of pango and cairo. However, as much as I've read and searched for these respective technologies I am simply not finding any usable documentation that pertains to what I am trying to do. There are some Python bindings for Imagemagick, but they all seem several years out of date.
Can some of the helpful souls here on SO point me to some tutorials on how to use Pango/Cairo and/or Imagemagick?
| [
"The Cairo cookbook has a number of examples for using Cairo, and the Python routines are almost mirror images of the C routines.\n",
"I've had some fine results with PyGame, but I don't know if it will necessarily solve your problem.\n"
] | [
2,
0
] | [] | [] | [
"fonts",
"python",
"text"
] | stackoverflow_0004029958_fonts_python_text.txt |
Q:
Django Poll for new records
In ajax I am polling a django url to retrieve the latest records. I do not want to display any records I have retrieved previously and I only want to retrieve 1 record for each poll request.
What would be the best way to do this?
A:
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
expire_date = models.DateField()
class Meta:
get_latest_by = 'pub_date'
>>> from mysite.models import Article
>>> Article.objects.latest()
If I'm not wrong in understanding your question, You may go for get_latest_by attribute ofMetaclass and call the methodlatest()` which may serve your purpose, in order not to retrieve the record twice you may use the obj.pk > your_prev_retired_pk.
A:
Hmm. You could do it two ways that I can think of off the bat - there are surely more.
You can add a field called "already_retrieved" and set it to True for those fields that have already been retrieved, and then only grab Whatever.objects.filter(already_retrieved=False).
Also, if they are in order by a pk, you could just keep track of how far you are in the list of pk's.
| Django Poll for new records | In ajax I am polling a django url to retrieve the latest records. I do not want to display any records I have retrieved previously and I only want to retrieve 1 record for each poll request.
What would be the best way to do this?
| [
"class Article(models.Model):\n headline = models.CharField(max_length=100)\n pub_date = models.DateField()\n expire_date = models.DateField()\n class Meta:\n get_latest_by = 'pub_date'\n\n>>> from mysite.models import Article\n>>> Article.objects.latest()\n\nIf I'm not wrong in understanding you... | [
2,
0
] | [] | [] | [
"django",
"polling",
"python"
] | stackoverflow_0004029807_django_polling_python.txt |
Q:
Overwriting default behavior for python operators
I know that to alter the default behavior of operators in python you can override some default methods like __add__ or __sub__ for + and -, but didn't find anything to override the behavior of the and and or keywords, while there are some for the bitwise operators &, |: respectively __and__ and __or__.
Do you know if there are hooks for these keywords also? I know it's strange to override the default behavior of and & or, but I need this to construct an abstract syntax tree starting from a python formula at runtime, don't really want to alter its semantics in a weird way.
If not, I would like to modify the language itself to have this support. If there's some good expert that could suggest me the right way to do so please put your hands up, otherwise I think I'll ask Guido for that :)
Thanks a lot floks!
A:
is, and, and or cannot be overloaded. Use the Python language services if you want to write a Pythonesque DSL.
| Overwriting default behavior for python operators | I know that to alter the default behavior of operators in python you can override some default methods like __add__ or __sub__ for + and -, but didn't find anything to override the behavior of the and and or keywords, while there are some for the bitwise operators &, |: respectively __and__ and __or__.
Do you know if there are hooks for these keywords also? I know it's strange to override the default behavior of and & or, but I need this to construct an abstract syntax tree starting from a python formula at runtime, don't really want to alter its semantics in a weird way.
If not, I would like to modify the language itself to have this support. If there's some good expert that could suggest me the right way to do so please put your hands up, otherwise I think I'll ask Guido for that :)
Thanks a lot floks!
| [
"is, and, and or cannot be overloaded. Use the Python language services if you want to write a Pythonesque DSL.\n"
] | [
2
] | [] | [] | [
"dynamic_languages",
"python"
] | stackoverflow_0004030153_dynamic_languages_python.txt |
Q:
Decimal to JSON
I'm pulling a sum from a DB which is a decimal value.
I'm trying to use that value in a JSON result
json.dumps( { 'sum': amount } ) #where amount is my Decimal
Django can't serialize the Decimal.
I can convert it to a string, but I'd like a numeric type within the JSON.
If I try and convert it to a float I end up with more than 2 decimal places.
What needs to happen, if possible, to get a result like the following?
{ 'sum': 500.50 }
A:
What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, similar to the example in this document: http://docs.python.org/py3k/library/json.html
>>> import json
>>> class DecimalEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, Decimal):
... return "%.2f" % obj
... return json.JSONEncoder.default(self, obj)
...
That's a nonworking example of how to do it, hopefully a good starting point for you.
A:
From this link : http://code.google.com/p/simplejson/issues/detail?id=34.
i can tell you tree think :
use cjson it work fine with decimal values.
use monkey patching like the example from this link: http://code.google.com/p/simplejson/issues/detail?id=61
use jsonutil see the last comment : http://code.google.com/p/simplejson/issues/detail?id=34#c28
you can find more detail in the first link.
A:
Decimal can be cast to a float which javascript knows how to deal with
json.dumps( { 'sum': float(amount) } )
| Decimal to JSON | I'm pulling a sum from a DB which is a decimal value.
I'm trying to use that value in a JSON result
json.dumps( { 'sum': amount } ) #where amount is my Decimal
Django can't serialize the Decimal.
I can convert it to a string, but I'd like a numeric type within the JSON.
If I try and convert it to a float I end up with more than 2 decimal places.
What needs to happen, if possible, to get a result like the following?
{ 'sum': 500.50 }
| [
"What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, similar to the example in this document: http://docs.python.org/py3k/library/json.html\n>>> import json\n>>> class DecimalEncoder(json.JSONEncoder):\n... def default(self, obj):\n... if isinstance(obj, ... | [
12,
0,
0
] | [
"There's no such thing as a Decimal type in Javascript, and also among the standard types in python. It is a database-spcific type and not part of JSON. Take Float or do an integer arithmetic.\n"
] | [
-1
] | [
"django",
"python"
] | stackoverflow_0004019856_django_python.txt |
Q:
How to set PATH to use Java and Python simultaneously
I was just wondering if there was any way to set to %PATH% variables so I can compile my Java code, along with my Python code?
For instance.. PATH is currently C:\ ... JDK_bin blah blah, and that's it. To run my python code, I have to change my path variable completely.
Any answers?
A:
Just add a semicolon after your present path, and write the new one after that.
set PATH="C:\Program Files\Java\blah\blah";C:\Python31\;C:\Windows\System32
etc...
A:
You need to add the path to python exe to your existing PATH variable which already has path to Java exes and many more paths in it.
path = %PATH%;C:\path\to\python\bin
You can also do this using windows GUI.
Note that doing an absolute assignment to PATH like
set PATH = C:\path\to\python\bin
will overwrite it, loosing the path(s) it already had.
A:
PATH variables can have multiple paths in them. Separate paths with ; on Windows and : on *nix.
set PATH=c:\path\to\java;c:\path\to\python
| How to set PATH to use Java and Python simultaneously | I was just wondering if there was any way to set to %PATH% variables so I can compile my Java code, along with my Python code?
For instance.. PATH is currently C:\ ... JDK_bin blah blah, and that's it. To run my python code, I have to change my path variable completely.
Any answers?
| [
"Just add a semicolon after your present path, and write the new one after that.\nset PATH=\"C:\\Program Files\\Java\\blah\\blah\";C:\\Python31\\;C:\\Windows\\System32\n\netc...\n",
"You need to add the path to python exe to your existing PATH variable which already has path to Java exes and many more paths in it... | [
9,
7,
4
] | [] | [] | [
"java",
"path",
"python",
"windows"
] | stackoverflow_0004030440_java_path_python_windows.txt |
Q:
Why doesn't a %en0 suffix work to connect a link-local IPv6 TCP socket in Python?
A week or so ago someone on StackOverflow asked why their Python code for connecting to an IPv6 link-local address wasn't working, and I replied that since it was a link-local address they needed to add a %en0 (or whatever the desired local-interface-name is) suffix to their target IP address. I thought I knew what I was talking about, so I didn't actually test my suggestion before answering (shame on me!).
Today I went to use that same technique for myself, only to find that it doesn't seem to work. :^( That is, this code does not work:
>>> from socket import *
>>> s = socket(AF_INET6, SOCK_STREAM)
>>> s.connect(('fe80::21f:5bff:fe3f:1b36%en0', 2001))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in connect
socket.error: [Errno 65] No route to host
The following code, on the other hand, DOES work (with or without the %en0 suffix):
>>> from socket import *
>>> s = socket(AF_INET6, SOCK_STREAM)
>>> s.connect(('fe80::21f:5bff:fe3f:1b36%en0', 2001, 0, 6))
>>>
... but I don't like doing it that way, because in order to figure out which scope ID integer to supply for the last argument, I have to execute a bunch of not-very-portable code to iterate over the local interfaces list, find the interface named 'en0', and extract its scope ID, which is more complexity overhead than I'd like to have.
Given that connect() is accepting the %en0 suffix to the IP address, why isn't it actually using it as expected to determine the scope ID?
FWIW, I am testing with Python 2.6.1 under MacOS/X 10.6.4.
A:
This is the correct way to do an ipv6 connection:
>>> addrinfo = getaddrinfo('fe80::225:ff:fecd:5aa0%en0', 2001, AF_INET6, SOCK_STREAM)
>>> addrinfo
[(30, 1, 6, '', ('fe80::225:ff:fecd:5aa0%en0', 2001, 0, 4))]
>>> (family, socktype, proto, canonname, sockaddr) = addrinfo[0]
>>> s = socket(family, socktype, proto)
>>> s.connect(sockaddr)
getaddrinfo() will return the correct numerical scope and flow information for you.
| Why doesn't a %en0 suffix work to connect a link-local IPv6 TCP socket in Python? | A week or so ago someone on StackOverflow asked why their Python code for connecting to an IPv6 link-local address wasn't working, and I replied that since it was a link-local address they needed to add a %en0 (or whatever the desired local-interface-name is) suffix to their target IP address. I thought I knew what I was talking about, so I didn't actually test my suggestion before answering (shame on me!).
Today I went to use that same technique for myself, only to find that it doesn't seem to work. :^( That is, this code does not work:
>>> from socket import *
>>> s = socket(AF_INET6, SOCK_STREAM)
>>> s.connect(('fe80::21f:5bff:fe3f:1b36%en0', 2001))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in connect
socket.error: [Errno 65] No route to host
The following code, on the other hand, DOES work (with or without the %en0 suffix):
>>> from socket import *
>>> s = socket(AF_INET6, SOCK_STREAM)
>>> s.connect(('fe80::21f:5bff:fe3f:1b36%en0', 2001, 0, 6))
>>>
... but I don't like doing it that way, because in order to figure out which scope ID integer to supply for the last argument, I have to execute a bunch of not-very-portable code to iterate over the local interfaces list, find the interface named 'en0', and extract its scope ID, which is more complexity overhead than I'd like to have.
Given that connect() is accepting the %en0 suffix to the IP address, why isn't it actually using it as expected to determine the scope ID?
FWIW, I am testing with Python 2.6.1 under MacOS/X 10.6.4.
| [
"This is the correct way to do an ipv6 connection:\n>>> addrinfo = getaddrinfo('fe80::225:ff:fecd:5aa0%en0', 2001, AF_INET6, SOCK_STREAM)\n>>> addrinfo\n[(30, 1, 6, '', ('fe80::225:ff:fecd:5aa0%en0', 2001, 0, 4))]\n>>> (family, socktype, proto, canonname, sockaddr) = addrinfo[0]\n>>> s = socket(family, socktype, pr... | [
13
] | [] | [] | [
"ipv6",
"link_local",
"python",
"scope_id",
"tcp"
] | stackoverflow_0004030269_ipv6_link_local_python_scope_id_tcp.txt |
Q:
signal.alarm() handler causing problem with pyserial
so i have a motion sensor connected to an avr micro that is communicating with my python app via usb. im using pyserial to do the comm. during my script i have an infinate loop checking for data from the avr micro. before this loop i start a timer with signal.alarm() that will call a function to end a subprocess. when this alarm goes it interrupts the pyserial comm and the program exits completly. i get the error that pyserial read() is interrupted. is there any way around this issue. any help would be awesome
A:
The problem is that your alarm will interrupt the read from the serial port, which isn't at all what you want.
It sounds like you probably want to break this into two threads that do work separately.
A:
You are using alarm(), which send a signal, and pyserial, which does reads and writes to a serial port. When you are reading or writing to a device like that, and the SIGALRM signal is received, a read() or a write() call is interrupted so the signal can be handled.
As signals are handled in userspace, and reading and writing is actually handled by the kernel, this makes things rather ugly. This is a know wart of the way signals are handled, and dates back to the very early UNIX days.
Code that handles signals correctly in python may look like:
import errno
while True:
try:
data = read_operation()
except OSError, e:
if getattr(e, 'errno', errno.EINTR):
continue
raise
else:
break
| signal.alarm() handler causing problem with pyserial | so i have a motion sensor connected to an avr micro that is communicating with my python app via usb. im using pyserial to do the comm. during my script i have an infinate loop checking for data from the avr micro. before this loop i start a timer with signal.alarm() that will call a function to end a subprocess. when this alarm goes it interrupts the pyserial comm and the program exits completly. i get the error that pyserial read() is interrupted. is there any way around this issue. any help would be awesome
| [
"The problem is that your alarm will interrupt the read from the serial port, which isn't at all what you want.\nIt sounds like you probably want to break this into two threads that do work separately.\n",
"You are using alarm(), which send a signal, and pyserial, which does reads and writes to a serial port. Whe... | [
0,
0
] | [] | [] | [
"alarm",
"pyserial",
"python",
"signals"
] | stackoverflow_0004030296_alarm_pyserial_python_signals.txt |
Q:
django multiple select in admin change-list
Our product model can have multiple campaigns. Our customers change these campaigns frequently and generally on multiple products. So what we need right now seems that we need to show a multiple select widget on a change-list of Product model where our customers can easily change the campaigns.
Any idea on this? Maybe another way to achieve this kind of UI interaction?
Thanks,
A:
say you have a product model
class Product(models.Model):
name=models.CharField(max_length=20)
cost=models.DecimalField(max_length=10)
you can subclass the admin's Modeladmin to show a list display for the products or you can do a custom modelform for the product which you can call in the product's admin
from django.contrib import admin
from django import forms
class PropertyInline(admin.TabularInine):
model=Property
extra=1
class PropertyForm(admin.ModelAdmin):
inlines=(PropertyInline,)
| django multiple select in admin change-list | Our product model can have multiple campaigns. Our customers change these campaigns frequently and generally on multiple products. So what we need right now seems that we need to show a multiple select widget on a change-list of Product model where our customers can easily change the campaigns.
Any idea on this? Maybe another way to achieve this kind of UI interaction?
Thanks,
| [
"say you have a product model\n\n\nclass Product(models.Model):\n name=models.CharField(max_length=20)\n cost=models.DecimalField(max_length=10)\n\n\n\n\nyou can subclass the admin's Modeladmin to show a list display for the products or you can do a custom modelform for the product which you can call in the prod... | [
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004013733_django_django_admin_django_models_python.txt |
Q:
AppEngine fetch through a free proxy
My (Python) AppEngine program fetches a web page from another site to scrape data from it -- but it seems like the 3rd party site is blocking requests from Google App Engine! -- I can fetch the page from development mode, but not when deployed.
Can I get around this by using a free proxy of some sort?
Can I use a free proxy to hide the fact that I am requesting from App Engine?
How do I find/choose a proxy? -- what do I need? -- how do I perform the fetch?
Is there anything else I need to know or watch out for?
A:
Probably the correct approach is to request permission from the owners of the site you are scraping.
Even if you use a proxy, there is still a big chance that requests coming through the proxy will end up blocked as well.
A:
Have you considered changing the user-agent?
result = urlfetch.fetch(u,headers = {'User-Agent': "Mozilla/5.0"},allow_truncated=True)
The API will always append "AppEngine-Google;" to the user-agent, but this might work if the restriction is not based on a IP address range.
A:
What you are talking about is a valid bug in app engine sdk. Have a look at http://code.google.com/p/googleappengine/issues/detail?id=544 for bug updates, and workarounds for java and python.
A:
I'm currently having the same problem and i was thinking about this solution (not yet tried) :
-> develop an app that fetch what you want
-> run it locally
-> fetch your local server from your initial
so the proxy is your computer which you know as not blocked
Let me know if it's works !
A:
Well to be fair, if they don't want you doing that then you probably shouldn't. It's not nice to be mean.
But if you really want to do it, the best approach would be creating a simple proxy script and running it on a VPS or some computer with a decent enough connection.
Basically you expose a REST API from your server to your GAE, then the server just makes all the same requests it gets to the target site and returns the output.
| AppEngine fetch through a free proxy | My (Python) AppEngine program fetches a web page from another site to scrape data from it -- but it seems like the 3rd party site is blocking requests from Google App Engine! -- I can fetch the page from development mode, but not when deployed.
Can I get around this by using a free proxy of some sort?
Can I use a free proxy to hide the fact that I am requesting from App Engine?
How do I find/choose a proxy? -- what do I need? -- how do I perform the fetch?
Is there anything else I need to know or watch out for?
| [
"Probably the correct approach is to request permission from the owners of the site you are scraping. \nEven if you use a proxy, there is still a big chance that requests coming through the proxy will end up blocked as well.\n",
"Have you considered changing the user-agent?\nresult = urlfetch.fetch(u,headers = {'... | [
2,
1,
1,
0,
0
] | [] | [] | [
"google_app_engine",
"proxy",
"python"
] | stackoverflow_0002050256_google_app_engine_proxy_python.txt |
Q:
Form is not running after adding fields in it
Hie friends, I made a form using the class forms.py it was running smoothly, but next time when I added two new fields in that forms.py class then on executing the command "python manage.py syncdb " it gives me the following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/lib/pymodules/python2.6/django/core/management/commands/syncdb.py", line 52, in handle_noargs
cursor = connection.cursor()
File "/usr/lib/pymodules/python2.6/django/db/backends/__init__.py", line 75, in cursor
cursor = self._cursor()
File "/usr/lib/pymodules/python2.6/django/db/backends/sqlite3/base.py", line 174, in _cursor
self.connection = Database.connect(**kwargs)
pysqlite2.dbapi2.OperationalError: unable to open database file
A:
Making changes to forms does not affect you database schema, there is no need to run syncdb after changing a form.
The error you are receiving has its roots elsewhere.
A:
it seems the problem is not with your forms.py but with your sqlite database file.can you delete the sqlite database file and syncdb again
~$ rm default.db
~$ manage.py syncdb
| Form is not running after adding fields in it | Hie friends, I made a form using the class forms.py it was running smoothly, but next time when I added two new fields in that forms.py class then on executing the command "python manage.py syncdb " it gives me the following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/lib/pymodules/python2.6/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/lib/pymodules/python2.6/django/core/management/base.py", line 351, in handle
return self.handle_noargs(**options)
File "/usr/lib/pymodules/python2.6/django/core/management/commands/syncdb.py", line 52, in handle_noargs
cursor = connection.cursor()
File "/usr/lib/pymodules/python2.6/django/db/backends/__init__.py", line 75, in cursor
cursor = self._cursor()
File "/usr/lib/pymodules/python2.6/django/db/backends/sqlite3/base.py", line 174, in _cursor
self.connection = Database.connect(**kwargs)
pysqlite2.dbapi2.OperationalError: unable to open database file
| [
"Making changes to forms does not affect you database schema, there is no need to run syncdb after changing a form. \nThe error you are receiving has its roots elsewhere.\n",
"it seems the problem is not with your forms.py but with your sqlite database file.can you delete the sqlite database file and syncdb agai... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004030086_django_python.txt |
Q:
Generate Python function in runtime and invoke them with string name
foo.py
def foo_001(para): tmp = para + 2 return tmp
def foo_002(para): tmp = para * 2 return tmp
def foo_003(para): tmp = para / 2 return tmp
...
def foo_100(para): tmp = #complex algo, return tmp
main.py
from foo import *
fun_name = ["foo_001","foo_002","foo_002" ... "foo_100"]
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
here is my question:
can I get the fun_name list in runtime, because I want save them in a text file?
I found there's common part in function defination which is "tmp = #algo", can I extract them out form those definations and can I define those functions in runtime? I want something like this:
foo.py
def foo_factory():
# in somehow
return adict #function_name/function pair
template = [
["foo_001","tmp = para + 2"],
["foo_002","tmp = para * 2"],
["foo_002","tmp = para + 2"],
...
["foo_100","tmp = #complex algo"]
main.py
from foo import *
dic = foo_factory(template)
fun_name = dic.keys()
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
#or
rzt.extent(dic(i)())
A:
fnmap = {
'foo_001': foo_001,
'foo_002': foo_002,
'foo_003': foo_003,
}
print fnmap['foo_002'](3)
Use a decorator to enumerate the functions if you don't feel like typing out the whole map.
| Generate Python function in runtime and invoke them with string name | foo.py
def foo_001(para): tmp = para + 2 return tmp
def foo_002(para): tmp = para * 2 return tmp
def foo_003(para): tmp = para / 2 return tmp
...
def foo_100(para): tmp = #complex algo, return tmp
main.py
from foo import *
fun_name = ["foo_001","foo_002","foo_002" ... "foo_100"]
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
here is my question:
can I get the fun_name list in runtime, because I want save them in a text file?
I found there's common part in function defination which is "tmp = #algo", can I extract them out form those definations and can I define those functions in runtime? I want something like this:
foo.py
def foo_factory():
# in somehow
return adict #function_name/function pair
template = [
["foo_001","tmp = para + 2"],
["foo_002","tmp = para * 2"],
["foo_002","tmp = para + 2"],
...
["foo_100","tmp = #complex algo"]
main.py
from foo import *
dic = foo_factory(template)
fun_name = dic.keys()
src = 1
rzt = []
for i in fun_name:
rzt.extent(eval(i)(src))
#or
rzt.extent(dic(i)())
| [
"fnmap = {\n 'foo_001': foo_001,\n 'foo_002': foo_002,\n 'foo_003': foo_003,\n}\n\nprint fnmap['foo_002'](3)\n\nUse a decorator to enumerate the functions if you don't feel like typing out the whole map.\n"
] | [
0
] | [] | [] | [
"function",
"python",
"runtime"
] | stackoverflow_0004030729_function_python_runtime.txt |
Q:
Using Python to read images from a www.flickr.com account
Ok, so I need to build this application where I'll read images from a www.flickr.com account and use the images in my Python app. How will I do that? Any ideas? Thanks.
A:
You could use one of the various flickr python libraries :
http://code.google.com/p/flickrpy/
http://pypi.python.org/pypi/Flickr.API/
http://stuvel.eu/projects/flickrapi
And for a good overview of flickr API, always look at the docs: http://www.flickr.com/services/api/
An example:
import flickrapi
api_key = 'API KEY YYYYYYYYYY' # you will need a key
api_password = 'your secret'
flickrClient = flickrapi.FlickrAPI(api_key, api_password)
# now you could use the methods on this client
# flickrClient.methodname(param)
favourites = flickrClient.favorites_getPublicList(user_id='userid')
# Get the title of the photos
for photo in favourites.photos[0].photo:
print photo['title']
[Edit:]
For authentication look at : http://stuvel.eu/flickrapi/documentation/#authentication
| Using Python to read images from a www.flickr.com account | Ok, so I need to build this application where I'll read images from a www.flickr.com account and use the images in my Python app. How will I do that? Any ideas? Thanks.
| [
"You could use one of the various flickr python libraries :\n\nhttp://code.google.com/p/flickrpy/\nhttp://pypi.python.org/pypi/Flickr.API/\nhttp://stuvel.eu/projects/flickrapi\n\nAnd for a good overview of flickr API, always look at the docs: http://www.flickr.com/services/api/\nAn example:\nimport flickrapi\napi_k... | [
9
] | [] | [] | [
"flickr",
"python"
] | stackoverflow_0004030824_flickr_python.txt |
Q:
Difference between qt and PyQt4
Well I am new to Qt and found its easier to work with python , I dont know how far its true .
but some of the code snippets have
import qt
and some have
import PyQt4
I don't know what the difference is, when I tried to interchange them I did get some errors , like some function was not recognizable and so on, also I am trying to build front end GUI for my application, which GUI framework would u suggest ? Is there anything close to VB like environment ?
A:
Old PyQt3 use qt
import qt
Current PyQt4 use PyQt4
import PyQt4
If you use PySide, use PySide
import PySide
| Difference between qt and PyQt4 | Well I am new to Qt and found its easier to work with python , I dont know how far its true .
but some of the code snippets have
import qt
and some have
import PyQt4
I don't know what the difference is, when I tried to interchange them I did get some errors , like some function was not recognizable and so on, also I am trying to build front end GUI for my application, which GUI framework would u suggest ? Is there anything close to VB like environment ?
| [
"Old PyQt3 use qt\nimport qt\n\nCurrent PyQt4 use PyQt4\nimport PyQt4\n\nIf you use PySide, use PySide\nimport PySide\n\n"
] | [
5
] | [] | [] | [
"pyqt4",
"python",
"qt"
] | stackoverflow_0004025849_pyqt4_python_qt.txt |
Q:
Why does Python complain about reference before assignment when increasing variables in a function?
Why does Python complain about chrome being referenced before assignment? It does not complain about the dictionary. This is with Python 2.5 if it makes a difference.
def f():
google['browser'] = 'chrome'
chrome += 1
google = dict()
chrome = 1
f()
I can make it work with global chrome of course, but I'd like to know why Python does't consider the variable to be assigned. Thanks.
A:
In the statement
chrome += 1
and it has not been created yet.
The variables are created the first time they are assigned. In this case, when python sees the code incrementing 'chrome', it doesn't see this variable at all.
Try rearranging your code as
chrome = 1
def f():
global chrome
google['browser'] = 'chrome'
chrome += 1
google = dict()
f()
A:
It's out of scope: read here
| Why does Python complain about reference before assignment when increasing variables in a function? | Why does Python complain about chrome being referenced before assignment? It does not complain about the dictionary. This is with Python 2.5 if it makes a difference.
def f():
google['browser'] = 'chrome'
chrome += 1
google = dict()
chrome = 1
f()
I can make it work with global chrome of course, but I'd like to know why Python does't consider the variable to be assigned. Thanks.
| [
"In the statement \nchrome += 1\n\nand it has not been created yet. \nThe variables are created the first time they are assigned. In this case, when python sees the code incrementing 'chrome', it doesn't see this variable at all.\nTry rearranging your code as\nchrome = 1\n\ndef f():\n global chrome\n google['brow... | [
5,
-1
] | [] | [] | [
"function",
"python",
"variables"
] | stackoverflow_0004030968_function_python_variables.txt |
Q:
Initialise class object by name
Since everything in python is an object, i was wondering if there was a way i could initialise a class object using the name of the class
for example,
class Foo:
"""Class Foo"""
How could i access this class by "Foo", ie something like c = get_class("Foo")
A:
If the class is in your scope:
get_class = lambda x: globals()[x]
If you need to get a class from a module, you can use getattr:
import urllib2
handlerClass = getattr(urllib2, 'HTTPHandler')
A:
Have you heard of the inspect module?
Check out this snippet I found.
| Initialise class object by name | Since everything in python is an object, i was wondering if there was a way i could initialise a class object using the name of the class
for example,
class Foo:
"""Class Foo"""
How could i access this class by "Foo", ie something like c = get_class("Foo")
| [
"If the class is in your scope:\nget_class = lambda x: globals()[x]\n\nIf you need to get a class from a module, you can use getattr:\nimport urllib2\nhandlerClass = getattr(urllib2, 'HTTPHandler')\n\n",
"Have you heard of the inspect module?\nCheck out this snippet I found.\n"
] | [
44,
1
] | [
"I think your searching reflection \nsee http://en.wikipedia.org/wiki/Reflection_%28computer_science%29#Python\nOr a better Example from the german wikipedia:\n>>> # the object\n>>> class Person(object):\n... def __init__(self, name):\n... self.name = name\n... def say_hello(self):\n... return '... | [
-2
] | [
"python"
] | stackoverflow_0004030982_python.txt |
Q:
Python : is there a shortcut for pattern [sth = get_sth() ; if sth: do_a_thing_on(sth)]
HI !
I guess everything is in the question ...
I was just wondering if there is a nice way in Python to shorten this pattern :
something = get_something()
if something:
do_a_thing_with(something)
Meaning that I would like to enter in the if context only if the variable something is not None (or False), and then in this context having this variable set automatically ! Is it possible with with statement ?
PS : I don't want to have to DEFINE more stuff... I am looking for some statement to use on the fly ?!
A:
This is as pythonic as it gets.
Things should be no more simplified than they are and no more complex than they should be.
See how the with statement works and providing a context guard. would be complicated enough.
http://effbot.org/pyref/with.htm
http://effbot.org/pyref/context-managers.htm
A:
If it is a pattern that is very frequent in your code (as you suggested in a comment to @pyfunc's answer), you can just make it a function:
def safeProcessData(getData, handleData):
buffer = getData()
if buffer:
handleData(buffer)
In this case the parameters getData and handleData would be callables, meaning any function (free or member) and objects that implement __call__.
A:
As others have said, your existing code is already nice and short... If you really want a one-liner, try a list comprehension:
[do_a_thing_with(something) for something in [get_something()] if something]
| Python : is there a shortcut for pattern [sth = get_sth() ; if sth: do_a_thing_on(sth)] | HI !
I guess everything is in the question ...
I was just wondering if there is a nice way in Python to shorten this pattern :
something = get_something()
if something:
do_a_thing_with(something)
Meaning that I would like to enter in the if context only if the variable something is not None (or False), and then in this context having this variable set automatically ! Is it possible with with statement ?
PS : I don't want to have to DEFINE more stuff... I am looking for some statement to use on the fly ?!
| [
"This is as pythonic as it gets. \nThings should be no more simplified than they are and no more complex than they should be. \nSee how the with statement works and providing a context guard. would be complicated enough.\n\nhttp://effbot.org/pyref/with.htm\nhttp://effbot.org/pyref/context-managers.htm\n\n",
"If i... | [
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004031106_python.txt |
Q:
Possible to programmatically ALTER multiple MySQL tables?
I have multiple MySQL tables with names of the form "Shard_0", "Shard_1", "Shard_2" ... "Shard_n" All of them have identical table structure. They all live in the same database.
Say I want to add a column to all those tables. Is there a way to do that programmatically?
Something like:
# pseudo code
for i in range(n):
tablename = "shard_"+str(i)
ALTER TABLE tablename ...
Is it possible to do something like that? If so what language and/or library do I need?
Thanks
A:
No problem. Python has several third party libraries to connect to a db. But the simplest approach if you have to do this for just one time would be a python script that writes the SQL instructions just to stdout:
for i in range(n):
tablename = "shard_"+str(i)
print 'ALTER TABLE tablename ...'
Then just call it from CLI like this:
./sqlgenscript.py | mysql -u username -p
A:
Yes its possible, you can use MySqlDb module for python and write the queries similar to sql queries and execute them to update the tables. Have a look at this: http://mysql-python.sourceforge.net/MySQLdb.html
A:
I think you can create a routine which takes one argument, and send "i" as argument to your routine. Then you can call your routine.
Call test.My_Alter(i);
where i=1,2,3,...
| Possible to programmatically ALTER multiple MySQL tables? | I have multiple MySQL tables with names of the form "Shard_0", "Shard_1", "Shard_2" ... "Shard_n" All of them have identical table structure. They all live in the same database.
Say I want to add a column to all those tables. Is there a way to do that programmatically?
Something like:
# pseudo code
for i in range(n):
tablename = "shard_"+str(i)
ALTER TABLE tablename ...
Is it possible to do something like that? If so what language and/or library do I need?
Thanks
| [
"No problem. Python has several third party libraries to connect to a db. But the simplest approach if you have to do this for just one time would be a python script that writes the SQL instructions just to stdout:\nfor i in range(n):\n tablename = \"shard_\"+str(i)\n print 'ALTER TABLE tablename ...'\n\nThen... | [
4,
1,
0
] | [] | [] | [
"database",
"database_administration",
"mysql",
"python",
"schema"
] | stackoverflow_0004030579_database_database_administration_mysql_python_schema.txt |
Q:
Python Syntax doubt
Hey, I have been using the Pymt library and they have this convention to referring their widgets:
from pymt import *
# create a slider from 0.-1.
sl = MTXYSlider()
@sl.event
def on_value_change(x, y):
print 'Slider value change', x, y
runTouchApp(sl)
what's with the "@"? What does it signify in Python?Thanks.
A:
It signifies a decorator
A:
basically it is a function that takes another function as an argument . if is a way python implements a Decorator Pattern.
the equivalent code would be
sl.event(on_value_change(x, y))
| Python Syntax doubt | Hey, I have been using the Pymt library and they have this convention to referring their widgets:
from pymt import *
# create a slider from 0.-1.
sl = MTXYSlider()
@sl.event
def on_value_change(x, y):
print 'Slider value change', x, y
runTouchApp(sl)
what's with the "@"? What does it signify in Python?Thanks.
| [
"It signifies a decorator\n",
"basically it is a function that takes another function as an argument . if is a way python implements a Decorator Pattern. \nthe equivalent code would be \n\n\nsl.event(on_value_change(x, y))\n\n\n\n\n\n"
] | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0004031288_python.txt |
Q:
Why does my python interactive console not work properly?
I made a very simple interactive console that I'd like to use in a complicated scraping application. It looks like this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs, code
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sys.__stderr__ = codecs.getwriter('utf8')(sys.__stderr__)
if 'DEBUG' in os.environ:
import pdb
import sys
oeh = sys.excepthook
def debug_exceptions(type, value, traceback):
pdb.post_mortem(traceback)
oeh(type, value, traceback)
sys.excepthook = debug_exceptions
class CLI(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>", histfile=None):
code.InteractiveConsole.__init__(self, locals, filename)
try:
import readline
except ImportError:
pass
else:
try:
import rlcompleter
readline.set_completer(rlcompleter.Completer(locals).complete)
except ImportError:
pass
readline.parse_and_bind("tab: complete")
self.interact()
if __name__ == "__main__":
hello="I am a local"
CLI(locals=locals())
If I call it from another simple application, it works just fine:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs, cli
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sys.__stderr__ = codecs.getwriter('utf8')(sys.__stderr__)
from cli import CLI
foo="i am a local"
CLI(locals=locals())
However, when I call it from my scraping framework which is based off twill and mechanize for now (though I intend to switch it to gevent) when call up the CLI in exactly the same way, the arrow keys don't work, tab completion doesn't work, in fact it behaves like readline doesn't exist. I've tried reloading the readline module and passing it direct parse_and_bind commands but for some reason it just will not play properly. Any hints or suggestions as to what has been clobbered that is preventing it from working as expected or am I just going to have to remove all the external modules in use and put them in, one by one to see what happened?
I'm suspicious of twill seeing as it has it's own basic CLI but if anyone knows I'd be very happy to know if anyone has a good idea what's going on.
Oh and please no comments about what I'm doing with stderr and stdout, it's just boilerplate code that gets put into python files, I always run them from utf8 consoles and it's not what I'm asking about...
A:
OK, I found out it was ME that was causing the problem, my older boiler-plate code used to this before I noticed it causing problems in some cases:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
That old code was still present in one of my own files, changing that code to the lower-level version of:
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sys.__stderr__ = codecs.getwriter('utf8')(sys.__stderr__)
Or removing it completely, since it didn't need to be in that file anyway fixed the issue.
| Why does my python interactive console not work properly? | I made a very simple interactive console that I'd like to use in a complicated scraping application. It looks like this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs, code
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sys.__stderr__ = codecs.getwriter('utf8')(sys.__stderr__)
if 'DEBUG' in os.environ:
import pdb
import sys
oeh = sys.excepthook
def debug_exceptions(type, value, traceback):
pdb.post_mortem(traceback)
oeh(type, value, traceback)
sys.excepthook = debug_exceptions
class CLI(code.InteractiveConsole):
def __init__(self, locals=None, filename="<console>", histfile=None):
code.InteractiveConsole.__init__(self, locals, filename)
try:
import readline
except ImportError:
pass
else:
try:
import rlcompleter
readline.set_completer(rlcompleter.Completer(locals).complete)
except ImportError:
pass
readline.parse_and_bind("tab: complete")
self.interact()
if __name__ == "__main__":
hello="I am a local"
CLI(locals=locals())
If I call it from another simple application, it works just fine:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, codecs, cli
sys.__stdout__ = codecs.getwriter('utf8')(sys.__stdout__)
sys.__stderr__ = codecs.getwriter('utf8')(sys.__stderr__)
from cli import CLI
foo="i am a local"
CLI(locals=locals())
However, when I call it from my scraping framework which is based off twill and mechanize for now (though I intend to switch it to gevent) when call up the CLI in exactly the same way, the arrow keys don't work, tab completion doesn't work, in fact it behaves like readline doesn't exist. I've tried reloading the readline module and passing it direct parse_and_bind commands but for some reason it just will not play properly. Any hints or suggestions as to what has been clobbered that is preventing it from working as expected or am I just going to have to remove all the external modules in use and put them in, one by one to see what happened?
I'm suspicious of twill seeing as it has it's own basic CLI but if anyone knows I'd be very happy to know if anyone has a good idea what's going on.
Oh and please no comments about what I'm doing with stderr and stdout, it's just boilerplate code that gets put into python files, I always run them from utf8 consoles and it's not what I'm asking about...
| [
"OK, I found out it was ME that was causing the problem, my older boiler-plate code used to this before I noticed it causing problems in some cases:\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\nsys.stderr = codecs.getwriter('utf8')(sys.stderr)\n\nThat old code was still present in one of my own files, changi... | [
3
] | [] | [] | [
"python",
"readline"
] | stackoverflow_0004031135_python_readline.txt |
Q:
How to get the convert a Jython class to Java class in Jython intepreter?
I am trying to register a User Defined Function with Esper API. It take a class or string type arguement
http://esper.codehaus.org/esper-4.0.0/doc/api/com/espertech/esper/client/ConfigurationOperations.html#addImport(java.lang.String)
class MyUdf():
@staticmethod
def udf():
return 50
conf.addImport(myudf.getClass().getName())
The error message
AttributeError: class MyUdf has no attribute 'getClass'
I can import java class by
from java.lang import Math
conf.addImport(Math)
@larsmans: class seems only exists in Java Class class
class MyUdf():
@staticmethod
def udf():
return 50
def main():
a = 'abc'
print a.__class__
u = MyUdf
print u.__class__
Traceback (most recent call last):
line 79, in main print u.__class__ AttributeError: class MyUdf has no attribute '__class__'
A:
I don't think this is possible. Jython classes are not Java classes, and as far as I can tell there's no pure-jython mechanism to corce it.
Generally, I would say that you should take the object factory method mentioned in the Jython book, and combine with a proxy class, which is what you'd pass as the parameter.
However, that method involves writing lots of Java, and it seems that in your case it would simpler to just write the MyUdf class in Java and be done with it.
Alternatively, you might be able to do something with dynamic bytecode generation, but that's a whole new rabbit hole...
| How to get the convert a Jython class to Java class in Jython intepreter? | I am trying to register a User Defined Function with Esper API. It take a class or string type arguement
http://esper.codehaus.org/esper-4.0.0/doc/api/com/espertech/esper/client/ConfigurationOperations.html#addImport(java.lang.String)
class MyUdf():
@staticmethod
def udf():
return 50
conf.addImport(myudf.getClass().getName())
The error message
AttributeError: class MyUdf has no attribute 'getClass'
I can import java class by
from java.lang import Math
conf.addImport(Math)
@larsmans: class seems only exists in Java Class class
class MyUdf():
@staticmethod
def udf():
return 50
def main():
a = 'abc'
print a.__class__
u = MyUdf
print u.__class__
Traceback (most recent call last):
line 79, in main print u.__class__ AttributeError: class MyUdf has no attribute '__class__'
| [
"I don't think this is possible. Jython classes are not Java classes, and as far as I can tell there's no pure-jython mechanism to corce it.\nGenerally, I would say that you should take the object factory method mentioned in the Jython book, and combine with a proxy class, which is what you'd pass as the parameter.... | [
0
] | [] | [] | [
"esper",
"java",
"jython",
"python"
] | stackoverflow_0003850493_esper_java_jython_python.txt |
Q:
python semantic proxy/server, which framework to use?
This year me and a friend have to make a project for the final year of university. The plan is to make a proxy/sever that allows to store ontologies and RDF's, by this way this data is "chained" to a web, so you can make a request for that web and the proxy will send you the homepage with metadata.
We have been thinking to use python and rdflib, and for the web we don't know which framework is the best. We thought of django, but we think that is very big for our purpose, and we decided that webpy or web2py is a better option.
We don't have any python coding experience, this will be our very first time. We have been always programming in c++ and java.
So taking into account everything we've mentioned our question is, which would be the best web framework for our project? And will rdflib suit fine with this framework?
Thanks :)
A:
I have developed several Web applications with Python framworks consuming RDF data. The choice always depends on the performance needed and the amount of data you'll have to handle.
If the number of triples you'll handle is in the magnitude of few thousands then you can easily put together a framework with RDFlib + Django. I have used this choice with toy applications but as soon as you have to deal with lots of data you'll realise that it simply doesn't scale. Not because of Django, the main problem is RDFlib's implementation of a triple store - it is not great.
If you're familiar with C/C++ I recommend you to have a look at Redland libraries. They are written in C and you have bindings for Python so you can still develop your Web layer with Django and pull out RDF data with Python. We do this quite a lot and it normally works. This option will scale a bit more but won't be great either.
In case your data grows to millions of triples then I recommend you to go for a Scalable Triple store. You can access them through SPARQL and HTTP. My choice is always 4store. Here you have a Python client to issue queries and assert/remove data 4store Python Client
| python semantic proxy/server, which framework to use? | This year me and a friend have to make a project for the final year of university. The plan is to make a proxy/sever that allows to store ontologies and RDF's, by this way this data is "chained" to a web, so you can make a request for that web and the proxy will send you the homepage with metadata.
We have been thinking to use python and rdflib, and for the web we don't know which framework is the best. We thought of django, but we think that is very big for our purpose, and we decided that webpy or web2py is a better option.
We don't have any python coding experience, this will be our very first time. We have been always programming in c++ and java.
So taking into account everything we've mentioned our question is, which would be the best web framework for our project? And will rdflib suit fine with this framework?
Thanks :)
| [
"I have developed several Web applications with Python framworks consuming RDF data. The choice always depends on the performance needed and the amount of data you'll have to handle.\nIf the number of triples you'll handle is in the magnitude of few thousands then you can easily put together a framework with RDFlib... | [
3
] | [] | [] | [
"proxy",
"python",
"rdf",
"semantics"
] | stackoverflow_0004031393_proxy_python_rdf_semantics.txt |
Q:
Removing non-english words from a sentence in python
I have written a code which sends queries to Google and returns the results. I extract the snippets(summaries) from these results for further processing. However, sometime non-english words are in these snippets which I don't want them. for example:
/\u02b0w\u025bn w\u025bn unstressed \u02b0w\u0259n w\u0259n/
I only want the "unstressed" word in this sentence.
How can I do that?
thanks
A:
PyEnchant might be a simple option for you. I do not know about its speed, but you can do things like:
>>> import enchant
>>> d = enchant.Dict("en_US")
>>> d.check("Hello")
True
>>> d.check("Helo")
False
>>>
A tutorial is found here, it also has options to return suggestions which you can you again for another query or something. In addition you can check if your result is in latin-1 (is_utf8() excists, do not know if is_latin-1() does also, maybe use something like Enca which detects the encoding of text files, on the basis of knowledge of their language.)
A:
You can compare the words you receive with a dictionary of english words, for example /usr/share/dict/words on a BSD system.
I would guess that googles results for the most part is grammatically correct, but if not, you might have to look into stemming in order to match against your dictionary.
A:
You can use PyWordNet. That is a python interface for the WordNet. Just split your sentence on white spaces and check for each word is it in the dictionary.
| Removing non-english words from a sentence in python | I have written a code which sends queries to Google and returns the results. I extract the snippets(summaries) from these results for further processing. However, sometime non-english words are in these snippets which I don't want them. for example:
/\u02b0w\u025bn w\u025bn unstressed \u02b0w\u0259n w\u0259n/
I only want the "unstressed" word in this sentence.
How can I do that?
thanks
| [
"PyEnchant might be a simple option for you. I do not know about its speed, but you can do things like:\n>>> import enchant\n>>> d = enchant.Dict(\"en_US\")\n>>> d.check(\"Hello\")\nTrue\n>>> d.check(\"Helo\")\nFalse\n>>>\n\nA tutorial is found here, it also has options to return suggestions which you can you again... | [
4,
1,
1
] | [] | [] | [
"non_english",
"python",
"unicode"
] | stackoverflow_0004031556_non_english_python_unicode.txt |
Q:
ArcGIS python 2.5 script - create a stats table by iterating the recordset
I need to iterate the fields and compute sum of few columns group by the value in another column .
For ex base table is
C1 C2 C3 C4 C5
a1 2 3 4 q
a1 4 5 7 a
a2 34 56 6 e
a2 4 5 5 5
a3 3 3 3 4
a3 3 3 3 3
The result table should be
c2 c3 c4
a1 6 8 11
a2 38 61 11
a3 6 6 6
50 75 28
I am able to iterate the fields to get the value of each field but got stuck in creating a two dimension matrix of result format. I was looking into 2 dimension array to achieve this scenario.
A:
Working from a lot of assumptions here since the question is quite unspecific...
# table containing only the actual data
table = [[2,3,4,"q"],[4,5,7,"a"],[34,56,6,"e"],[4,5,5,5],[3,3,3,4],[3,3,3,3]]
result = []
# iterate through table[0/2/4/...] zipped together with table[1/3/5/...]
for (row1, row2) in zip(table[::2], table[1::2]):
# add the first three elements of each row and append the results to our result
result.append([c1+c2 for c1,c2 in zip(row1[:3], row2[:3])])
print(result)
outputs
[[6, 8, 11], [38, 61, 11], [6, 6, 6]]
| ArcGIS python 2.5 script - create a stats table by iterating the recordset | I need to iterate the fields and compute sum of few columns group by the value in another column .
For ex base table is
C1 C2 C3 C4 C5
a1 2 3 4 q
a1 4 5 7 a
a2 34 56 6 e
a2 4 5 5 5
a3 3 3 3 4
a3 3 3 3 3
The result table should be
c2 c3 c4
a1 6 8 11
a2 38 61 11
a3 6 6 6
50 75 28
I am able to iterate the fields to get the value of each field but got stuck in creating a two dimension matrix of result format. I was looking into 2 dimension array to achieve this scenario.
| [
"Working from a lot of assumptions here since the question is quite unspecific...\n# table containing only the actual data\ntable = [[2,3,4,\"q\"],[4,5,7,\"a\"],[34,56,6,\"e\"],[4,5,5,5],[3,3,3,4],[3,3,3,3]]\nresult = []\n\n# iterate through table[0/2/4/...] zipped together with table[1/3/5/...]\nfor (row1, row2) i... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004031550_python.txt |
Q:
Python WSGI deployment on Windows for CPU-bound application
What options do I have for the deployment of a CPU bound Python-WSGI application on Windows?
The application benefits greatly from multiple CPUs (image manipulation/encoding) but the GIL prevents it from using them.
My understanding is:
mod_wsgi has no support for WSGIDaemonProcess on Windows and Apache itself only runs with one process
all fork based solutions (flup, spawning, gunicorn) only work on unix
Are there any other deployment options I'm missing?
PS: I asked that on serverfault but someone suggested to ask here.
A:
I have successfully used isapi-wsgi to deploy WSGI web apps on Windows IIS (I assume that since you're deploying on Windows, IIS is an option).
Create an IIS Application Pool to host your application in and configure it as a Web Garden (Properties | Performance | Maximum number of worker processes).
Disclaimer: I have never used this feature myself (I have always used the default App Pool configuration, where Max. number of worker processes is 1). But it is my understanding that this will spin up more processes to handle requests.
A:
It would be a bit of a mess, but you could use the subprocess module to fire off worker processes yourself. I'm pretty sure that Popen.wait() and/or Popen.communicate() ought to release the GIL. You've still got the process creation overhead though, so you might not gain a lot/anything over standard CGI.
Another option is to have separate server/worker processes running the whole time and use some form of IPC, although this isn't going to be an easy option. Have a look at the multiprocessing module, and potentially also Pyro.
| Python WSGI deployment on Windows for CPU-bound application | What options do I have for the deployment of a CPU bound Python-WSGI application on Windows?
The application benefits greatly from multiple CPUs (image manipulation/encoding) but the GIL prevents it from using them.
My understanding is:
mod_wsgi has no support for WSGIDaemonProcess on Windows and Apache itself only runs with one process
all fork based solutions (flup, spawning, gunicorn) only work on unix
Are there any other deployment options I'm missing?
PS: I asked that on serverfault but someone suggested to ask here.
| [
"I have successfully used isapi-wsgi to deploy WSGI web apps on Windows IIS (I assume that since you're deploying on Windows, IIS is an option).\nCreate an IIS Application Pool to host your application in and configure it as a Web Garden (Properties | Performance | Maximum number of worker processes).\nDisclaimer: ... | [
1,
0
] | [] | [] | [
"mod_wsgi",
"python",
"windows",
"wsgi"
] | stackoverflow_0004012621_mod_wsgi_python_windows_wsgi.txt |
Q:
About the image size that generated from matplotlib
I generated a histogram by using matplotlib
import numpy as np
import pylab as P
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
P.figure()
bins = 10
n, bins, patches = P.hist(x, bins, normed=1, histtype='bar', rwidth=0.8)
P.show()
I want to make the picture smaller, how could I do that?
Thanks for your help
A:
If you just want to set it for this specific figure, then change your figure declaration to:
P.figure(figsize=(i,j))
where i is the width in inches and j is the height in inches.
A:
In addition to specifying the figsize, there's also a dpi option - although this is more important if you're using one of the image generating backends.
| About the image size that generated from matplotlib | I generated a histogram by using matplotlib
import numpy as np
import pylab as P
mu, sigma = 200, 25
x = mu + sigma*P.randn(10000)
P.figure()
bins = 10
n, bins, patches = P.hist(x, bins, normed=1, histtype='bar', rwidth=0.8)
P.show()
I want to make the picture smaller, how could I do that?
Thanks for your help
| [
"If you just want to set it for this specific figure, then change your figure declaration to:\nP.figure(figsize=(i,j))\n\nwhere i is the width in inches and j is the height in inches.\n",
"In addition to specifying the figsize, there's also a dpi option - although this is more important if you're using one of the... | [
4,
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0004012047_matplotlib_python.txt |
Q:
Is python logger thread-safe or not?
Is python logger thread-safe or not? I use python 2.6.
A:
Yes, it is thread-safe, but there are some cautions in the documentation that you need to be aware of. Search for "thread" in this page.
A:
Yes it is.
A:
Seems to be:
http://chrisrbennett.com/2008/04/python-logger-config-thread-safety.html
Not sure he's talking about 2.6 though.
| Is python logger thread-safe or not? | Is python logger thread-safe or not? I use python 2.6.
| [
"Yes, it is thread-safe, but there are some cautions in the documentation that you need to be aware of. Search for \"thread\" in this page.\n",
"Yes it is.\n",
"Seems to be:\nhttp://chrisrbennett.com/2008/04/python-logger-config-thread-safety.html\nNot sure he's talking about 2.6 though.\n"
] | [
5,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004032155_python.txt |
Q:
slow File Processing in python
I am trying a file operation using python.Aim is to continuously read a file of size(100bytes),pack and send them through socket. These files are read from a directory.
Problem: when i run the program continuously, execution time is increasing. Initially, execution time is less than a second; later it reaches till 8~10seconds. I am not able get exact reason for the delay.If anyone can throw some light on the issue, it will be more helpful.
Here i have attached my code...
def handlefile(filename):
for sat in range(len(Numfiles)):
filename =
fsize = os.path.getsize(filename)
if fsize != 100:
continue
rfile = open(filename,'rb')
text = rfile.read()
msg = struct.unpack("<100b",text)
for i in range(len(msg)):
packMessage = packMessage + struct.pack("<b",msg[i])
print "time:",datetime.datetime.now() - startTime
The file are binary files.
Initial time taken : 671 ms
on executing continuously for more than 10 times,time increases slowly.
Last few values,
671ms
.
.
.
.
9.879 ms
88.686 ms
135.954 ms
I am using python-2.5.4 version.
If anyone had come across similar problem. Please provide me some inputs.
Thanks
Das
A:
From what I see, packMessage is growing monotonically:
packMessage = packMessage + struct.pack("<b",msg[i])
If you repeat it many times, it may grow big, consume a lot of memory, and at some point your application may become much slower. Try looking at top or htop when you run your program (in top, press M to sort by memory allocation, f to add resident memory field).
Also opening and reading the same file every time is not the best solution from the performance point of view. Consider reading it only once before entering the loop.
A:
Have you checked the number of file-handles your process has open? You may want yo use the with-statement to make sure they get closed when not needed anymore:
with open(filename, 'rb') as rfile:
text = rfile.read()
# etc.
When the with-block is left, the file will closed automatically.
| slow File Processing in python | I am trying a file operation using python.Aim is to continuously read a file of size(100bytes),pack and send them through socket. These files are read from a directory.
Problem: when i run the program continuously, execution time is increasing. Initially, execution time is less than a second; later it reaches till 8~10seconds. I am not able get exact reason for the delay.If anyone can throw some light on the issue, it will be more helpful.
Here i have attached my code...
def handlefile(filename):
for sat in range(len(Numfiles)):
filename =
fsize = os.path.getsize(filename)
if fsize != 100:
continue
rfile = open(filename,'rb')
text = rfile.read()
msg = struct.unpack("<100b",text)
for i in range(len(msg)):
packMessage = packMessage + struct.pack("<b",msg[i])
print "time:",datetime.datetime.now() - startTime
The file are binary files.
Initial time taken : 671 ms
on executing continuously for more than 10 times,time increases slowly.
Last few values,
671ms
.
.
.
.
9.879 ms
88.686 ms
135.954 ms
I am using python-2.5.4 version.
If anyone had come across similar problem. Please provide me some inputs.
Thanks
Das
| [
"From what I see, packMessage is growing monotonically:\npackMessage = packMessage + struct.pack(\"<b\",msg[i])\n\nIf you repeat it many times, it may grow big, consume a lot of memory, and at some point your application may become much slower. Try looking at top or htop when you run your program (in top, press M ... | [
4,
3
] | [] | [] | [
"file_handling",
"python"
] | stackoverflow_0004032012_file_handling_python.txt |
Q:
How save implement class in python?
I have instance of the my class. I want to save implementation of class with instance's pickle copy in file. After, I want to use this instance to another computer where there is no implementation of the my class. I don't want to save text of implementation manually.
How can I do this?
A:
Use a dict instead of a class.
A:
If you don't want to copy your source code to the "other computer" then the best best is to use native data structures, i.e. dict or list or tuples etc.
Pack what ever you want to pack & store it in these data structures, then simply do this -
import pickle
def save_to_disk(data, filename):
pickle.dump(data, open(filename, 'w'))
return
def read_from_disk(filename):
data = pickle.load(open(filename))
return data
I have heard cPickle is faster then pickle
| How save implement class in python? | I have instance of the my class. I want to save implementation of class with instance's pickle copy in file. After, I want to use this instance to another computer where there is no implementation of the my class. I don't want to save text of implementation manually.
How can I do this?
| [
"Use a dict instead of a class.\n",
"If you don't want to copy your source code to the \"other computer\" then the best best is to use native data structures, i.e. dict or list or tuples etc.\nPack what ever you want to pack & store it in these data structures, then simply do this -\nimport pickle\n\ndef save_to_... | [
0,
0
] | [] | [] | [
"class",
"python",
"serialization"
] | stackoverflow_0004031453_class_python_serialization.txt |
Q:
Changing the key name of an entity
I understand that they are not supposed to be changed, this is somewhat of a schema migration and only a one-time thing.
I would like to change the key names of entities in my Google App Engine application, effectively deleting and re-crating an entity and updating all references to it.
What is the best way to do this? I'm interesting in hearing anyone's experience with such things.
A:
Since changing the key name is functionally identical to creating a new, identical entity with that key, what you want to do is clone the entity with the new key. Here's some code that does just that.
| Changing the key name of an entity | I understand that they are not supposed to be changed, this is somewhat of a schema migration and only a one-time thing.
I would like to change the key names of entities in my Google App Engine application, effectively deleting and re-crating an entity and updating all references to it.
What is the best way to do this? I'm interesting in hearing anyone's experience with such things.
| [
"Since changing the key name is functionally identical to creating a new, identical entity with that key, what you want to do is clone the entity with the new key. Here's some code that does just that.\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004032247_google_app_engine_python.txt |
Q:
what is the fastest way to update thousands rows in mysql
lets assume you have a table with 1M rows and growing ...
every five minutes of every day you run a python programm which have to update some fields of 50K rows
my question is: what is the fastest way to do the work?
runs those updates in loop and after last one is executed than fire up a cursor commit?
or generate file and than run it throught command line?
create temp table by huge and fast insert and than run a single update to production table?
do prepared statements?
split it up to 1K updates per execute, to generate smaller logs files?
turn off logging while running update?
or do a cases in mysql examples (but this works only up to 255 rows)
i dont know ... have anyone do something like this? what is the best practise? i need to run it as fast as possible ...
A:
Here's some ways you could speed up your UPDATES.
When you UPDATE, the table records are just being rewritten with new data. And all this must be done again on INSERT. That's why you should always use INSERT ... ON DUPLICATE KEY UPDATE instead of REPLACE.
The former one is an UPDATE operation in case of a key violation, while the latter one is DELETE / INSERT
Here's an example INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1; More on this here.
UPDATE1: It's a good idea to do your inserts all in a single query. This should speed up your UPDATES. See here on how to do that.
UPDATE2: Now that I have had a chance to read your other sub-questions. Here's what I know-
instead of in a loop, try to execute all UPDATE in a single sql & single commit.
Not sure this is going to make any difference. SQL queries are more important.
Now this is something you could experiment with. Benchmark it. This kind of a thing depends on the size of the TABLE & the INDEXES you have, plus INNODB or MYISAM.
No idea about this.
refer first point.
Yes, this might speed your stuff up slightly. Also see if you have slow_query_log turned on. This logs all slow queries to a separate logfile. Turn this off too.
Again. refer first point.
A:
query execution process: Server first parsing your query then execute you need to analysis
the query
then server take less time to parse then he execute faster instead of slow in other way
| what is the fastest way to update thousands rows in mysql |
lets assume you have a table with 1M rows and growing ...
every five minutes of every day you run a python programm which have to update some fields of 50K rows
my question is: what is the fastest way to do the work?
runs those updates in loop and after last one is executed than fire up a cursor commit?
or generate file and than run it throught command line?
create temp table by huge and fast insert and than run a single update to production table?
do prepared statements?
split it up to 1K updates per execute, to generate smaller logs files?
turn off logging while running update?
or do a cases in mysql examples (but this works only up to 255 rows)
i dont know ... have anyone do something like this? what is the best practise? i need to run it as fast as possible ...
| [
"Here's some ways you could speed up your UPDATES.\nWhen you UPDATE, the table records are just being rewritten with new data. And all this must be done again on INSERT. That's why you should always use INSERT ... ON DUPLICATE KEY UPDATE instead of REPLACE.\nThe former one is an UPDATE operation in case of a key vi... | [
4,
0
] | [] | [] | [
"mysql",
"performance",
"python"
] | stackoverflow_0004031814_mysql_performance_python.txt |
Q:
Pip, Virtualenv & Git project setup and bootstrapping
Assuming you have a project setup like this:
-WebApp
|_ requirements.txt
|_ bootstrap.py (virtualenv bootstrap script)
|_ src
|_ setup.py
|_ develop-app
|_ somecode.py
|_ morecode.py
The bootstrap.py is created with virtualenv:
https://virtualenv.pypa.io/en/latest/reference.html#creating-your-own-bootstrap-scripts
Now, the entire WebApp dir is a git repo (obviously excluding the virtualenv). The purpose is to create a portable virtualenv/git environment. The problem is if you put the develop-app in your requirements.txt as develop, it will install it under /src in your virtualenv dir, and symlink that into your virtual-env site-packages. What you end up with is two copies of your source code—one that's tracked by git and the one in the Virtualenv that you use but is not tracked by git.
How would you ensure that changes made in the directory tracked by git (develop-app) automatically gets updated within your virtualenv?
A:
How about not adding your develop app to the requirements.txt list.. and just run the code from your git repro? The point of requirements is to specify which requirements your development app has right? It is rather strange to me to make it require itself.
| Pip, Virtualenv & Git project setup and bootstrapping | Assuming you have a project setup like this:
-WebApp
|_ requirements.txt
|_ bootstrap.py (virtualenv bootstrap script)
|_ src
|_ setup.py
|_ develop-app
|_ somecode.py
|_ morecode.py
The bootstrap.py is created with virtualenv:
https://virtualenv.pypa.io/en/latest/reference.html#creating-your-own-bootstrap-scripts
Now, the entire WebApp dir is a git repo (obviously excluding the virtualenv). The purpose is to create a portable virtualenv/git environment. The problem is if you put the develop-app in your requirements.txt as develop, it will install it under /src in your virtualenv dir, and symlink that into your virtual-env site-packages. What you end up with is two copies of your source code—one that's tracked by git and the one in the Virtualenv that you use but is not tracked by git.
How would you ensure that changes made in the directory tracked by git (develop-app) automatically gets updated within your virtualenv?
| [
"How about not adding your develop app to the requirements.txt list.. and just run the code from your git repro? The point of requirements is to specify which requirements your development app has right? It is rather strange to me to make it require itself.\n"
] | [
4
] | [] | [] | [
"development_environment",
"pip",
"python",
"virtualenv"
] | stackoverflow_0003996708_development_environment_pip_python_virtualenv.txt |
Q:
python hex hmac md5 of passwords not matching javascript
i have a javascript password coder
md5 = hex_hmac_md5(secret, password)
How can i emulate this in python - ive tried md5 but that is not the same value
i got my md5 javascript code from this website:
Pajs Home
(md5.js)
He states the use is as follows:
In many uses of hashes you end up
wanting to combine a key with some
data. It isn't so bad to do this by
simple concatenation, but HMAC is
specifically designed for this use.
The usage is:
hash = hex_hmac_md5("key", "data");
The HMAC result is also available
base-64 encoded or as a binary string,
using b64_hmac_* or str_hmac_*.
Some other hash libraries have the
arguments the other way round. If the
JavaScript HMAC doesn't match the
value your server library generates,
try swapping the order.
I have tried some python like this:
> def md5_test(secret, password):
>
> return md5(secret+password).hexdigest()
Can anyone tell me what the code should be in python to get the same value?
Thanks
A:
That's what Python's hmac module is for, don't use the MD5 function directly.
# Right
import hmac
# Note that hmac.new defaults to using MD5
hmac.new("password", "message").hexdigest() # 'f37438341e3d22aa11b4b2e838120dcf'
# Wrong
from hashlib import md5
md5("message"+"password").hexdigest() # 'd0647ee3be62a57c9475541c378b1fac'
md5("password"+"message").hexdigest() # 'c494404d2dd827b05e27bd1f30a763d2'
Also take a look at how HMAC is implemented (e.g. on Wikipedia).
| python hex hmac md5 of passwords not matching javascript | i have a javascript password coder
md5 = hex_hmac_md5(secret, password)
How can i emulate this in python - ive tried md5 but that is not the same value
i got my md5 javascript code from this website:
Pajs Home
(md5.js)
He states the use is as follows:
In many uses of hashes you end up
wanting to combine a key with some
data. It isn't so bad to do this by
simple concatenation, but HMAC is
specifically designed for this use.
The usage is:
hash = hex_hmac_md5("key", "data");
The HMAC result is also available
base-64 encoded or as a binary string,
using b64_hmac_* or str_hmac_*.
Some other hash libraries have the
arguments the other way round. If the
JavaScript HMAC doesn't match the
value your server library generates,
try swapping the order.
I have tried some python like this:
> def md5_test(secret, password):
>
> return md5(secret+password).hexdigest()
Can anyone tell me what the code should be in python to get the same value?
Thanks
| [
"That's what Python's hmac module is for, don't use the MD5 function directly.\n# Right\nimport hmac\n# Note that hmac.new defaults to using MD5\nhmac.new(\"password\", \"message\").hexdigest() # 'f37438341e3d22aa11b4b2e838120dcf'\n\n# Wrong\nfrom hashlib import md5\nmd5(\"message\"+\"password\").hexdigest() # 'd06... | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004032694_python.txt |
Q:
Is it possible for my Mercurial hook to call code from another file?
I have a hook function named precommit_bad_branch which imports hook_utils. When invoking precommit_bad_branch via a commit I get the following error message:
error: precommit.branch_check hook raised an exception: No module named hook_utils
abort: No module named hook_utils!
It looks like I'm not allowed to call hook_utils from precommit_bad_branch. The code works fine if I call it explicitly without involving Mercurial.
Is it possible for my hook to call code from another file?
My hgrc hook part looks like this:
[hooks]
precommit.branch_check = python:C:\workspaces\hg_hooks\next_hooks.py:precommit_bad_branch
precommit.debug_code_check = python:C:\workspaces\hg_hooks\common_hooks.py:precommit_contains_debug_code
preupdate.merge_check = python:C:\workspaces\hg_hooks\next_hooks.py:preupdate_bad_merge
A:
Put the C:\workspaces\hg_hooks directory in your PYTHONPATH and you will be able to write
[hooks]
precommit.branch_check = python:next_hooks.precommit_bad_branch
in your configuration file and you will also be able to do
import hook_utils
inside any Python file, including the next_hooks.py file.
Alternatively, you can modify sys.path from next_hooks.py, perhaps with code like this:
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import hook_utils
| Is it possible for my Mercurial hook to call code from another file? | I have a hook function named precommit_bad_branch which imports hook_utils. When invoking precommit_bad_branch via a commit I get the following error message:
error: precommit.branch_check hook raised an exception: No module named hook_utils
abort: No module named hook_utils!
It looks like I'm not allowed to call hook_utils from precommit_bad_branch. The code works fine if I call it explicitly without involving Mercurial.
Is it possible for my hook to call code from another file?
My hgrc hook part looks like this:
[hooks]
precommit.branch_check = python:C:\workspaces\hg_hooks\next_hooks.py:precommit_bad_branch
precommit.debug_code_check = python:C:\workspaces\hg_hooks\common_hooks.py:precommit_contains_debug_code
preupdate.merge_check = python:C:\workspaces\hg_hooks\next_hooks.py:preupdate_bad_merge
| [
"Put the C:\\workspaces\\hg_hooks directory in your PYTHONPATH and you will be able to write\n[hooks]\nprecommit.branch_check = python:next_hooks.precommit_bad_branch\n\nin your configuration file and you will also be able to do\nimport hook_utils\n\ninside any Python file, including the next_hooks.py file.\nAltern... | [
2
] | [] | [] | [
"mercurial",
"mercurial_hook",
"python",
"python_import"
] | stackoverflow_0004031290_mercurial_mercurial_hook_python_python_import.txt |
Q:
How to find all words that have the same appearence in two different languages?
The russian alphabet includes many letters that are the same in the English alphabet. Here is the list of common letters: L='acekopuxy'
Now, given two huge lists R and E, each in the form [word_A, word_B, ...], where each word_N is a lowercase word, I want to create a list C, which should contain only those words that have the same spelling in E and in R. For example, a word 'cop' must be in C, because it is in the list R as well as in E.
Is there any polynomial way to do it?
P.S.: One important note: because of the different character encodings, there are two L lists, LE for English letters and LR for Russian, but the appearance of their letters is the same:
LE='acekopuxy'
LR='асекориху'
A:
You can use sets for this:
english_set = set(E)
russian_set = set(R)
common_words = english_set.intersection(russian_set)
I'm not sure I got the encoding part right though, but if that means letters that look similar are actually different bytes, you can for example prepare the russian list by replacing these letters by their english counterpart prior to doing the intersection.
A:
You can use regular expressions for this:
^[acekopuxy]+$
will match words that contain only those characters.
import re
regex = re.compile(r"^[acekopuxy]+$", re.I)
output = []
for word in mylist:
if regex.match(word):
output.append(word)
You'll need to do this for both lists, using the correct encodings. That means that for the Russian list, you'll need to use the equivalent characters, like ^[\u0441\u1234...]$.
Then, if you want to find the words that "look the same", you could use a translation table to convert the words in one of the list into the format of the other list, then convert the lists to sets, and check their intersection.
A:
Eset = set(E)
C = [w for w in R if w.replace(LR,LE) in Eset]
Not sure if I understood the problem correctly, but assuming good hashing, this runs in O(n).
A:
You need to tell the program yourself, which characters are similar. Since they are each different Unicode codepoints, you will have to have a mapping like this:
var RE_map = (
(u'c', u'\u0441'),
# ...and so on
)
Then, translate all words from R to their E representation:
for ec, rc in RE_map:
string = string.replace(rc, ec)
and finally check, if the string is now in E:
if string in E:
print "The word exists of characters similar in Latin and Cyrillic."
| How to find all words that have the same appearence in two different languages? | The russian alphabet includes many letters that are the same in the English alphabet. Here is the list of common letters: L='acekopuxy'
Now, given two huge lists R and E, each in the form [word_A, word_B, ...], where each word_N is a lowercase word, I want to create a list C, which should contain only those words that have the same spelling in E and in R. For example, a word 'cop' must be in C, because it is in the list R as well as in E.
Is there any polynomial way to do it?
P.S.: One important note: because of the different character encodings, there are two L lists, LE for English letters and LR for Russian, but the appearance of their letters is the same:
LE='acekopuxy'
LR='асекориху'
| [
"You can use sets for this:\nenglish_set = set(E)\nrussian_set = set(R)\ncommon_words = english_set.intersection(russian_set)\n\nI'm not sure I got the encoding part right though, but if that means letters that look similar are actually different bytes, you can for example prepare the russian list by replacing thes... | [
3,
1,
1,
1
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0004032835_algorithm_python.txt |
Q:
Serialize django model with foreign key models
How to serialize Django model in json format if I want to include foreign key models fields?
If I have:
class Model1(models.Model):
name=models.CharField()
child=models.ForeignKey(Model2)
class Mode2(models.Model):
field1=models.CharField()
field2=models.IntegerField()
I wanna include everything in json...
A:
I had similar problems so I took some code that I had done before, and improved it. It actually ended-up in a full python serialization framework SpitEat. You can download an try it here. The documentation is not very good yet, so here is the code you have to use to serialize your thing :
>>> from spiteat.djangosrz import DjangoModelSrz #you should actually put spiteat in your path first
>>> Model1Srz = DjangoModelSrz.factory(Model1)
>>> srz_instance = Model1Srz(some_obj_you_want_to_serialize)
>>> srz_instance.spit()
... {
... 'pk': <a_pk>,
... 'id': <an_id>,
... 'name': <a_name>,
... 'child': {
... 'pk': <another_pk>,
... 'id': <another_id>,
... 'field1': <a_value>,
... 'field2': <another_value>
... }
... }
So, complete, deep serialization. You can customize things (choose which fields are included, etc ... But that's not tested yet, and not well documented).
The doc will become better in the next days, as the code will, so you can begin to use it without fearing that there will be no support !
Of course, once your have your object serialized, just use json as :
>>> import json
>>> json_srz = json.dumps(srz_instance.spit())
And you have what you came for !
A:
it's been sometimes that i didn't work on django but is this work for you ?
import simplejson as json
data = Model1.objects.get(pk=some_id)
to_dump = {'pk': data.pk, 'name':data.name,
'fields':{'field_1':data.child.field_1,
'field_2':data.child.field_2
}
}
json_data = json.dumps(to_dump)
| Serialize django model with foreign key models | How to serialize Django model in json format if I want to include foreign key models fields?
If I have:
class Model1(models.Model):
name=models.CharField()
child=models.ForeignKey(Model2)
class Mode2(models.Model):
field1=models.CharField()
field2=models.IntegerField()
I wanna include everything in json...
| [
"I had similar problems so I took some code that I had done before, and improved it. It actually ended-up in a full python serialization framework SpitEat. You can download an try it here. The documentation is not very good yet, so here is the code you have to use to serialize your thing :\n>>> from spiteat.djangos... | [
2,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004015229_django_python.txt |
Q:
Closing Perspective Broker connection in Twisted
I have program which has servers interacting with each other using Twisted's remote procedure calls, and I run in problems with closing connections when they are not needed anymore. Connections should be able to close itself in both sides.
Case 1: How do I close connection in connecting part?
factory = pb.PBClientFactory()
reactor.connectTCP(ip, port, factory)
deferred = factory.login(credentials.UsernamePassword(username, password), client=self)
deferred.addCallbacks(self.connectedToServer, self.errorConnectingToServer)
def connectedToServer(self, server):
self.server = server
# Closing connection comes here
Case 2: How do I close connection in server part?
class MyPerspective(pb.Avatar):
def connected(self, server):
self.client = server
# Closing connection comes here
At the moment I use raising pb.Error() to close connection, but I don't think that's the proper way to do it.
A:
Another option is reference.broker.transport.loseConnection().
RemoteReference instances which are created over a PB connection are given a broker attribute. The broker attribute refers to the protocol instance that created them. As usual for a protocol, the broker has a transport attribute, and the transport has a loseConnection method.
| Closing Perspective Broker connection in Twisted | I have program which has servers interacting with each other using Twisted's remote procedure calls, and I run in problems with closing connections when they are not needed anymore. Connections should be able to close itself in both sides.
Case 1: How do I close connection in connecting part?
factory = pb.PBClientFactory()
reactor.connectTCP(ip, port, factory)
deferred = factory.login(credentials.UsernamePassword(username, password), client=self)
deferred.addCallbacks(self.connectedToServer, self.errorConnectingToServer)
def connectedToServer(self, server):
self.server = server
# Closing connection comes here
Case 2: How do I close connection in server part?
class MyPerspective(pb.Avatar):
def connected(self, server):
self.client = server
# Closing connection comes here
At the moment I use raising pb.Error() to close connection, but I don't think that's the proper way to do it.
| [
"Another option is reference.broker.transport.loseConnection(). \nRemoteReference instances which are created over a PB connection are given a broker attribute. The broker attribute refers to the protocol instance that created them. As usual for a protocol, the broker has a transport attribute, and the transport... | [
1
] | [] | [] | [
"python",
"rpc",
"twisted"
] | stackoverflow_0004032699_python_rpc_twisted.txt |
Q:
django-piston : Overriding default serialization in emitters
I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.
More precisely, my models are subclassed from a special Model class, which inherits from django.db.models.base.ModelBase, but cannot be serialized as regular django models ... Therefore, I would like to override the serializer for all subclasses of this special Model class.
I don't know piston well ... I've looked at the code, and the mapping type->serializer (for base types) seems to be hard-coded.
Does anybody know if there is a standard way to override it ???
A:
You can do the serialization yourself. The handlers only expect and return a python dictionary. For this though, you can't just plug it into a model. Create your own resource handler for your base type, which is capable of building your Model from a dict.
class ModelHandler(HandlerBase):
allowed_methods = ('Get',)
def read(self, request, id=None):
if id is not None:
m = Model.objects.get(id=id)
ret = {}
ret['field'] = m.field
return ret
A:
Ok ... I couldn't have it working, so I took some code that I had written myself some time ago, made it cleaner, it ended-up in a full Python serialization framework SpitEat. I have begun writing some documentation, but it's a work in progress.
I have given-up using piston, since it is not the first time it disappoints me by its lack of flexibility on (de)serialization operations.
SpitEat aims to be fully customizable, (by seeing serialization from a more abstract point of view than just "django objects") and provides serializers for Django, tested, but not so well documented yet, and with features that are still missing (again it is a work in progress).
| django-piston : Overriding default serialization in emitters | I am currently writing an API for a django project, and using django-piston for this. However, I need to customize the way certain base types are serialized.
More precisely, my models are subclassed from a special Model class, which inherits from django.db.models.base.ModelBase, but cannot be serialized as regular django models ... Therefore, I would like to override the serializer for all subclasses of this special Model class.
I don't know piston well ... I've looked at the code, and the mapping type->serializer (for base types) seems to be hard-coded.
Does anybody know if there is a standard way to override it ???
| [
"You can do the serialization yourself. The handlers only expect and return a python dictionary. For this though, you can't just plug it into a model. Create your own resource handler for your base type, which is capable of building your Model from a dict.\nclass ModelHandler(HandlerBase):\n allowed_methods = ('... | [
1,
1
] | [] | [] | [
"django",
"django_piston",
"python",
"serialization"
] | stackoverflow_0003966490_django_django_piston_python_serialization.txt |
Q:
Stopping an application (punjab) that is run using Twisted
I am trying to run punjab connection manager with very less python knowledge. I followed the punjab docs and can start the application. But how do I stop/restart it ?
twistd -y punjab.tac
starts punjab first time but after that if I enter the same command , it says
Another twistd server is running, PID 3726.
Precisely I want to set the host and port options for punjab using the command line and restart it again. Please help. Thanks
A:
A server started with twistd is stopped in the somewhat typical UNIX fashion: send it a signal - INT is a good first choice:
kill -INT 3726
This should initiate shutdown. You can check in the log file, generally twistd.log in the same directory as you started the server.
Since the PID of the running process is tracked in twistd.pid (again, same directory), you can also grab that information directly from the file instead of having to type (and perhaps mistype) it:
kill -INT `cat twistd.pid`
| Stopping an application (punjab) that is run using Twisted | I am trying to run punjab connection manager with very less python knowledge. I followed the punjab docs and can start the application. But how do I stop/restart it ?
twistd -y punjab.tac
starts punjab first time but after that if I enter the same command , it says
Another twistd server is running, PID 3726.
Precisely I want to set the host and port options for punjab using the command line and restart it again. Please help. Thanks
| [
"A server started with twistd is stopped in the somewhat typical UNIX fashion: send it a signal - INT is a good first choice:\nkill -INT 3726\n\nThis should initiate shutdown. You can check in the log file, generally twistd.log in the same directory as you started the server.\nSince the PID of the running process ... | [
5
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0004032839_python_twisted.txt |
Q:
Django and MongoDB Engine - Problem with object IDs!
I'm using Django 1.3beta and django-mongodb-engine for database backend.
Problem is when I save an object with a pk set I get this error:
/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.pyc in get_prep_lookup(self, lookup_type, value)
290 return value
291 elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
--> 292 return self.get_prep_value(value)
293 elif lookup_type in ('range', 'in'):
294 return [self.get_prep_value(v) for v in value]
/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.pyc in get_prep_value(self, value)
477 if value is None:
478 return None
--> 479 return int(value)
480
481 def contribute_to_class(self, cls, name):
ValueError: invalid literal for int() with base 10: '4cc75881006e4a1e0f000000'
I guess it is because mongodb items are stored with a key in hexadecimal, while django expects an int.
Any ideas what I can do about this?
A:
You'll need django-nonrel fork of django. If you'll follow the link you've posted, you'll see it's specified in "Requirements"
| Django and MongoDB Engine - Problem with object IDs! | I'm using Django 1.3beta and django-mongodb-engine for database backend.
Problem is when I save an object with a pk set I get this error:
/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.pyc in get_prep_lookup(self, lookup_type, value)
290 return value
291 elif lookup_type in ('exact', 'gt', 'gte', 'lt', 'lte'):
--> 292 return self.get_prep_value(value)
293 elif lookup_type in ('range', 'in'):
294 return [self.get_prep_value(v) for v in value]
/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.pyc in get_prep_value(self, value)
477 if value is None:
478 return None
--> 479 return int(value)
480
481 def contribute_to_class(self, cls, name):
ValueError: invalid literal for int() with base 10: '4cc75881006e4a1e0f000000'
I guess it is because mongodb items are stored with a key in hexadecimal, while django expects an int.
Any ideas what I can do about this?
| [
"You'll need django-nonrel fork of django. If you'll follow the link you've posted, you'll see it's specified in \"Requirements\"\n"
] | [
3
] | [] | [] | [
"django",
"django_models",
"mongodb",
"python"
] | stackoverflow_0004031788_django_django_models_mongodb_python.txt |
Q:
what would be a quick way to do nested splitting of brackets in python?
I have a file of the following format:
ID1 { some text }
ID2 { some text }
They don't have to come line by line format, so that we can have:
ID1 { some [crlf]
text [crlf]
}
ID2 [crlf] { some t [crlf]
ex [crlf]
t}
and so on, meaning some text can be more than one line and there could be a CRLF immediately following ID. The main invariant is that all IDs are enclosed by { }.
The thing is that some text itself could have { and } in it.
What would be a quick way to take such a file and separate it into a list of strings, each being ID { text }, while taking into account nested brackets?
Taking into account some error analysis, in case brackets are not balanced, would be great.
A:
Using pyparsing you can knock this out in about 6 lines, and then get on with your other work. Here are two variations on a solution, depending on how you want the parse results structured:
data = """ID1 { some text } ID2 { some {with some more text nested in braces} text }"""
from pyparsing import Word, alphas, alphanums, dictOf, nestedExpr, originalTextFor
# identifier starts with any alpha, followed by any alpha, num, or '_'
ident = Word(alphas,alphanums+"_")
# Solution 1
# list of items is a dict of pairs of idents and nested {}'s
# - returns {}'s expressions as nested structures
itemlist = dictOf(ident, nestedExpr("{","}"))
items = itemlist.parseString(data)
print items.dump()
"""
prints:
[['ID1', ['some', 'text']], ['ID2', ['some', ['with', 'some', 'more', ...
- ID1: ['some', 'text']
- ID2: ['some', ['with', 'some', 'more', 'text', 'nested', 'in', 'braces'], 'text']
"""
# Solution 2
# list of items is a dict of pairs of idents and nested {}'s
# - returns {}'s expressions as strings of text extract from the
# original input string
itemlist = dictOf(ident, originalTextFor(nestedExpr("{","}")))
items = itemlist.parseString(data)
print items.dump()
"""
prints:
[['ID1', '{ some text }'], ['ID2', '{ some {with some more text nested in ...
- ID1: { some text }
- ID2: { some {with some more text nested in braces} text }
"""
A:
This is a simple question of "how do I write a rescursive decent parser that matches brackets.
Given this grammar:
STMT_LIST := STMT+
STMT := ID '{' DATA '}'
DATA := TEXT | STMT
ID := [a-z0-9]+
TEXT := [^}]*
A parser might look like:
import sys
import re
def parse(data):
"""
STMT
"""
while data:
data, statement_id, clause = parse_statement(data)
print repr((statement_id, clause))
def consume_whitespace(data):
return data.lstrip()
def parse_statement(data):
m = re.match('[a-zA-Z0-9]+', data)
if not m:
raise ValueError, "No ID found"
statement_id = m.group(0)
data = consume_whitespace(data[len(statement_id):])
data, clause = parse_clause(data)
return consume_whitespace(data), statement_id, clause
def parse_clause(data):
clause = []
if not data.startswith('{'):
raise ValueError, "No { found"
data = data[1:]
closebrace = data.index('}')
try:
openbrace = data.index('{')
except ValueError:
openbrace = sys.maxint
while openbrace < closebrace:
clause.append(data[:openbrace])
data, subclause = parse_clause(data[openbrace:])
clause.append(subclause)
closebrace = data.index('}')
try:
openbrace = data.index('{')
except ValueError:
openbrace = sys.maxint
clause.append(data[:closebrace])
data = data[closebrace+1:]
return data, clause
parse("ID { foo { bar } }")
parse("ID { foo { bar } } baz { tee fdsa { fdsa } }")
This is a nasty parser to be honest. If you were to structure it nicer you would end up with a proper token stream from a lexxer and pass that to the actual parser. As it is the 'token stream' is just a string that we strip info off the start of.
I would recommend looking at pyparsing if you wanted anything more complicated.
A:
regex is out of the question, obviously. Have you looked at pyparsing?
[EDIT]
OTOH this might work:
from functools import wraps
def transition(method):
@wraps(method)
def trans(state, *args, **kwargs):
command = method(state, *args, **kwargs)
state.__class__ = command(state)
return trans
class State(object):
def __new__(cls):
state = object.__new__(cls)
state._identities = []
return state
def unchanged(state):
return state.__class__
def shifting(identity):
def command(state):
return identity
return command
def pushing(identity, afterwards=None):
def command(state):
state._identities.append(afterwards or state.__class__)
return identity
return command
def popped(state):
return state._identities.pop()
##############################################################################
import re
tokenize = re.compile(flags=re.VERBOSE | re.MULTILINE, pattern=r"""
(?P<word> \w+ ) |
(?P<braceleft> { ) |
(?P<braceright> } ) |
(?P<eoi> $ ) |
(?P<error> \S ) # catch all (except white space)
""").finditer
def parse(parser, source, builder):
for each in tokenize(source):
dispatch = getattr(parser, each.lastgroup)
dispatch(each.group(), builder)
class ParsingState(State):
def eoi(self, token, *args):
raise ValueError('premature end of input in parsing state %s' %
self.__class__.__name__
)
def error(self, token, *args):
raise ValueError('parsing state %s does not understand token %s' % (
self.__class__.__name__, token
))
def __getattr__(self, name):
def raiser(token, *args):
raise ValueError(
'parsing state %s does not understand token "%s" of type %s' %
(self.__class__.__name__, token, name)
)
return raiser
class Id(ParsingState):
@transition
def word(self, token, builder):
builder.add_id(token)
return shifting(BeginContent)
@transition
def eoi(self, token, builder):
return shifting(DoneParsing)
class BeginContent(ParsingState):
@transition
def braceleft(self, token, builder):
return shifting(Content)
class Content(ParsingState):
@transition
def word(self, token, builder):
builder.add_text(token)
return unchanged
@transition
def braceleft(self, token, builder):
builder.add_text(token)
return pushing(PushedContent)
@transition
def braceright(self, token, builder):
return shifting(Id)
class PushedContent(Content):
@transition
def braceright(self, token, builder):
builder.add_text(token)
return popped
class DoneParsing(ParsingState):
pass
##############################################################################
class Entry(object):
def __init__(self, idname):
self.idname = idname
self.text = []
def __str__(self):
return '%s { %s }' % (self.idname, ' '.join(self.text))
class Builder(object):
def __init__(self):
self.entries = []
def add_id(self, id_token):
self.entries.append(Entry(id_token))
def add_text(self, text_token):
self.entries[-1].text.append(text_token)
##############################################################################
if __name__ == '__main__':
file_content = """
id1 { some text } id2 {
some { text }
}
"""
builder = Builder()
parse(Id(), file_content, builder)
for entry in builder.entries:
print entry
A:
Here's the brute force method, with error detection included or indicated:
# parsebrackets.py
def parse_brackets(data):
# step 1: find the 0-nesting-level { and }
lpos = []
rpos = []
nest = 0
for i, c in enumerate(data):
if c == '{':
if nest == 0:
lpos.append(i)
nest += 1
elif c == '}':
nest -= 1
if nest < 0:
raise Exception('too many } at offset %d' % i)
if nest == 0:
rpos.append(i)
if nest > 0:
raise Exception('too many { in data')
prev = -1
# step 2: extract the pieces
for start, end in zip(lpos, rpos):
key = data[prev+1:start].strip()
# insert test for empty key here
text = data[start:end+1]
prev = end
yield key, text
if data[prev+1:].strip():
raise Exception('non-blank text after last }')
Output:
>>> from parsebrackets import parse_brackets as pb
>>> for k, t in pb(' foo {bar {zot\n}} guff {qwerty}'):
... print repr(k), repr(t)
...
'foo' '{bar {zot\n}}'
'guff' '{qwerty}'
>>>
| what would be a quick way to do nested splitting of brackets in python? | I have a file of the following format:
ID1 { some text }
ID2 { some text }
They don't have to come line by line format, so that we can have:
ID1 { some [crlf]
text [crlf]
}
ID2 [crlf] { some t [crlf]
ex [crlf]
t}
and so on, meaning some text can be more than one line and there could be a CRLF immediately following ID. The main invariant is that all IDs are enclosed by { }.
The thing is that some text itself could have { and } in it.
What would be a quick way to take such a file and separate it into a list of strings, each being ID { text }, while taking into account nested brackets?
Taking into account some error analysis, in case brackets are not balanced, would be great.
| [
"Using pyparsing you can knock this out in about 6 lines, and then get on with your other work. Here are two variations on a solution, depending on how you want the parse results structured:\ndata = \"\"\"ID1 { some text } ID2 { some {with some more text nested in braces} text }\"\"\"\n\nfrom pyparsing import Word,... | [
4,
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004029235_python.txt |
Q:
Python logic in assignment
Given that secure is a boolean, what do the following statements do?
Especially the first statement.
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
A:
I hate this Python idiom, it's completely opaque until someone explains it. In 2.6 or higher, you'd use:
protocol = "https" if secure else "http"
A:
It sets protocol to "https" if secure is true, else it sets it to "http".
Try it in the interpreter:
>>> True and "https" or "http"
'https'
>>> False and "https" or "http"
'http'
A:
Python generalises boolean operations a bit, compared to other languages. Before the "if" conditional operator was added (similar to C's ?: ternary operator), people sometimes wrote equivalent expressions using this idiom.
and is defined to return the first value if it's boolean-false, else returns the second value:
a and b == a if not bool(a) else b #except that a is evaluated only once
or returns its first value if it's boolean-true, else returns its second value:
a or b == a if bool(a) else b #except that a is evaluated only once
If you plug in True and False for a and b in the above expressions, you'll see that they work out as you would expect, but they work for other types, like integers, strings, etc. as well. Integers are treated as false if they're zero, containers (including strings) are false if they're empty, and so on.
So protocol = secure and "https" or "http" does this:
protocol = (secure if not secure else "https") or "http"
...which is
protocol = ((secure if not bool(secure) else "https")
if bool(secure if not bool(secure) else "https") else "http")
The expression secure if not bool(secure) else "https" gives "https" if secure is True, else returns the (false) secure value. So secure if not bool(secure) else "https" has the same truth-or-falseness as secure by itself, but replaces boolean-true secure values with "https". The outer or part of the expression does the opposite - it replaces boolean-false secure values with "http", and doesn't touch "https", because it's true.
This means that the overall expression does this:
if secure is false, then the expression evaluates to "http"
if secure is true, then the expression evaluates to "https"
...which is the result that other answers have indicated.
The second statement is just string formatting - it substitutes each of the tuple of strings into the main "format" string wherever %s appears.
A:
The first line was answered well by the Ned and unwind.
The 2nd statement is a string replacement. Each %s is a placeholder for a string value. So if the values are:
protocol = "http"
get_host(request) = "localhost"
request.get_full_path() = "/home"
the resulting string would be:
http://localhost/home
A:
In psuedocode:
protocol = (if secure then "https" else "http")
newurl = protocol + "://" + get_host(request) + request.get_full_path()
| Python logic in assignment | Given that secure is a boolean, what do the following statements do?
Especially the first statement.
protocol = secure and "https" or "http"
newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
| [
"I hate this Python idiom, it's completely opaque until someone explains it. In 2.6 or higher, you'd use:\nprotocol = \"https\" if secure else \"http\"\n\n",
"It sets protocol to \"https\" if secure is true, else it sets it to \"http\".\nTry it in the interpreter:\n>>> True and \"https\" or \"http\"\n'https'\n>>... | [
13,
5,
5,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004033298_python.txt |
Q:
capitalization of library class names
Why do collection.defaultdict and collection.OrderedDict have different capitalizations?
Is there some subtle difference that I should be aware of?
(P3K)
A:
The capitalization of the class names is irrelevant, it doesn't signify anything. Except that Python has sometimes grown organically and the standard library doesn't have the same homogenous feel as other large libraries such as the Win32 API or the Java standard library.
A:
Usually, that is in accordance with good style, classes are capitalised.
def MyClass (object):
pass
my_instance = MyClass()
like this.
You should read this document about it:
http://www.python.org/dev/peps/pep-0008/
A:
defaultdict is written in C and pep8 don't apply , in the other hand OrderDict is written in python,
you can read C code norm for the C implementation of Python here : PEP 7
reference : source code python2.7
defaultdict : Modules/_collectionsmodule.c
OrderDict : Lib/collections.py
| capitalization of library class names | Why do collection.defaultdict and collection.OrderedDict have different capitalizations?
Is there some subtle difference that I should be aware of?
(P3K)
| [
"The capitalization of the class names is irrelevant, it doesn't signify anything. Except that Python has sometimes grown organically and the standard library doesn't have the same homogenous feel as other large libraries such as the Win32 API or the Java standard library.\n",
"Usually, that is in accordance wit... | [
5,
2,
1
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004032925_python_python_3.x.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.