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:
Matching blank entries in django queryset for optional field with corresponding ones in a required field
I have a django queryset in my views whose values I pack before passing to my template. There is a problem when the queryset returns none since associated values are not unpacked. the quersyet is called comments.
Here is my views.py
def forums(request ):
post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId')))
if request.user.is_staff== True :
staff = 1
else:
staff = 0
staffis = 1
if newpostform.is_valid():
topic = request.POST['postSubject']
poster = request.POST['postPoster']
newpostform.save()
return HttpResponseRedirect('/forums')
else:
newpostform = PostForm(initial = {'postPoster':user.id})
if request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
post_list = list((forum.objects.filter(child='0')&forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)))or(forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)).values('childParentId')))
if request.method == 'POST':
delpostformset = DelPostFormSet(request.POST)
if delpostformset.is_valid():
delpostformset.save()
return HttpResponseRedirect('/forums')
else:
delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))
"""if readform.is_valid():
user=get_object_or_404(UserProfile.objects.all())
readform.save()
else:
readform = ReadForumForm()"""
post= zip( post_list,comments, delpostformset.forms)
paginator = Paginator(post, 10) # Show 10 contacts per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
post = paginator.page(page)
except (EmptyPage, InvalidPage):
post = paginator.page(paginator.num_pages)
return render_to_response('forum.html', {'post':post, 'newpostform': newpostform,'delpost':delpostformset, 'username':user.username, 'comments':comments, 'user':user, },context_instance = RequestContext( request ))
I realised that the issue was with the comments queryset comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId'))) which will only returns values for posts that have comments. so i now need a way to return 0 comments when a value in post-list post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate')) does not have any comments (optional field).
Here is my models.py
class forum(models.Model):
postID = models.AutoField(primary_key=True)
postSubject = models.CharField(max_length=100)
postBody = models.TextField()
postPoster = models.ForeignKey(UserProfile)
postDate = models.DateTimeField(auto_now_add=True)
child = models.BooleanField()
childParentId = models.ForeignKey('self',blank=True, null=True)
deleted = models.BooleanField()
def __unicode__(self):
return u' %d' % ( self.postID)
A:
You could just do this:
comments = list(queryset or [])
if the queryset resolves to None, then the empty list will be used and comments will just be an empty list.
A:
I don't think you are doing it right. I don't believe that queryset can return None. Why not just chain the filter methods?
list(forum.objects.filter(child='0').filter(deleted='0').order_by('postDate'))
If you have more complex queries, you can use the Query objects of django, which allow you to use the & and | logical operators.
|
Matching blank entries in django queryset for optional field with corresponding ones in a required field
|
I have a django queryset in my views whose values I pack before passing to my template. There is a problem when the queryset returns none since associated values are not unpacked. the quersyet is called comments.
Here is my views.py
def forums(request ):
post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId')))
if request.user.is_staff== True :
staff = 1
else:
staff = 0
staffis = 1
if newpostform.is_valid():
topic = request.POST['postSubject']
poster = request.POST['postPoster']
newpostform.save()
return HttpResponseRedirect('/forums')
else:
newpostform = PostForm(initial = {'postPoster':user.id})
if request.GET:
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']
post_list = list((forum.objects.filter(child='0')&forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)))or(forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)).values('childParentId')))
if request.method == 'POST':
delpostformset = DelPostFormSet(request.POST)
if delpostformset.is_valid():
delpostformset.save()
return HttpResponseRedirect('/forums')
else:
delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))
"""if readform.is_valid():
user=get_object_or_404(UserProfile.objects.all())
readform.save()
else:
readform = ReadForumForm()"""
post= zip( post_list,comments, delpostformset.forms)
paginator = Paginator(post, 10) # Show 10 contacts per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
post = paginator.page(page)
except (EmptyPage, InvalidPage):
post = paginator.page(paginator.num_pages)
return render_to_response('forum.html', {'post':post, 'newpostform': newpostform,'delpost':delpostformset, 'username':user.username, 'comments':comments, 'user':user, },context_instance = RequestContext( request ))
I realised that the issue was with the comments queryset comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId'))) which will only returns values for posts that have comments. so i now need a way to return 0 comments when a value in post-list post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate')) does not have any comments (optional field).
Here is my models.py
class forum(models.Model):
postID = models.AutoField(primary_key=True)
postSubject = models.CharField(max_length=100)
postBody = models.TextField()
postPoster = models.ForeignKey(UserProfile)
postDate = models.DateTimeField(auto_now_add=True)
child = models.BooleanField()
childParentId = models.ForeignKey('self',blank=True, null=True)
deleted = models.BooleanField()
def __unicode__(self):
return u' %d' % ( self.postID)
|
[
"You could just do this:\ncomments = list(queryset or [])\n\nif the queryset resolves to None, then the empty list will be used and comments will just be an empty list.\n",
"I don't think you are doing it right. I don't believe that queryset can return None. Why not just chain the filter methods?\nlist(forum.objects.filter(child='0').filter(deleted='0').order_by('postDate'))\n\nIf you have more complex queries, you can use the Query objects of django, which allow you to use the & and | logical operators.\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002603694_django_python.txt
|
Q:
Django sub-applications & module structure
I am developing a Django application, which is a large system that requires multiple sub-applications to keep things neat. Therefore, I have a top level directory that is a Django app (as it has an empty models.py file), and multiple subdirectories, which are also applications in themselves.
The reason I have laid my application out in this way is because the sub-applications are separated, but they would never be used on their own, outside the parent application. It therefore makes no sense to distribute them separately.
When installing my application, the settings file has to include something like this:
INSTALLED_APPS = (
...
'myapp',
'myapp.subapp1',
'myapp.subapp2',
...
)
...which is obviously suboptimal. This also has the slightly nasty result of requiring that all the sub-applications are referred to by their "inner" name (i.e. subapp1, subapp2 etc.). For example, if I want to reset the database tables for subapp1, I have to type:
python manage.py reset subapp1
This is annoying, especially because I have a sub-app called core - which is likely to conflict with another application's name when my application is installed in a user's project.
Am I doing this completely wrongly, or is there away to force these "inner" apps to be referred to by their full name?
A:
You are doing it the right way, since django itself does it that way. The admin app for instance is registered in INSTALLED_APPS as django.contrib.admin, but to reset it you have to use manage.py reset admin, and indeed, manage.py reset django.contrib.admin does not work.
It could be considered as a bug in django...
However, you should not be concerned by name conflicts, because you should always run django inside a virtualenv environment, isolated from the rest of the python installation. This is an immensely more powerful and flexible solution than running django on an ordinary python installation. More info, for instance, here: http://mathematism.com/2009/jul/30/presentation-pip-and-virtualenv/
|
Django sub-applications & module structure
|
I am developing a Django application, which is a large system that requires multiple sub-applications to keep things neat. Therefore, I have a top level directory that is a Django app (as it has an empty models.py file), and multiple subdirectories, which are also applications in themselves.
The reason I have laid my application out in this way is because the sub-applications are separated, but they would never be used on their own, outside the parent application. It therefore makes no sense to distribute them separately.
When installing my application, the settings file has to include something like this:
INSTALLED_APPS = (
...
'myapp',
'myapp.subapp1',
'myapp.subapp2',
...
)
...which is obviously suboptimal. This also has the slightly nasty result of requiring that all the sub-applications are referred to by their "inner" name (i.e. subapp1, subapp2 etc.). For example, if I want to reset the database tables for subapp1, I have to type:
python manage.py reset subapp1
This is annoying, especially because I have a sub-app called core - which is likely to conflict with another application's name when my application is installed in a user's project.
Am I doing this completely wrongly, or is there away to force these "inner" apps to be referred to by their full name?
|
[
"You are doing it the right way, since django itself does it that way. The admin app for instance is registered in INSTALLED_APPS as django.contrib.admin, but to reset it you have to use manage.py reset admin, and indeed, manage.py reset django.contrib.admin does not work.\nIt could be considered as a bug in django...\nHowever, you should not be concerned by name conflicts, because you should always run django inside a virtualenv environment, isolated from the rest of the python installation. This is an immensely more powerful and flexible solution than running django on an ordinary python installation. More info, for instance, here: http://mathematism.com/2009/jul/30/presentation-pip-and-virtualenv/\n"
] |
[
12
] |
[] |
[] |
[
"django",
"django_apps",
"python"
] |
stackoverflow_0002617522_django_django_apps_python.txt
|
Q:
Why is this logical expression in python False?
My question is, why are these expressions False?
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> num = raw_input("Choose a number: ")
Choose a number: 5
>>> print num
5
>>> print ( num < 18 )
False
>>> print ( num == 5 )
False
Because if i try this:
>>> print ( num > 0 )
True
The expression works fine.
A:
This statement:
num = raw_input("Choose a number: ")
makes num a string, not a number, despite its misleading name. It so happens that Python 2 lets you compare strings with numbers, and in your version considers all strings larger than all numbers (the contents of the string play no role).
Use num = int(num) to make an integer (and be sure to use a try/except to catch possible errors when the user has typed something other than a number!) before you start comparing.
(In Python 3, the function's name changes from raw_input to input, and it still returns strings; however in Python 3 comparing a string with a number is considered an error, so you would get an exception rather than True or False in each of your comparison attempts).
A:
The variable num does not actually contain the number 5; it contains the string "5". Because Python is strongly typed, 5 == "5" is False. Try converting it to an integer first:
>>> print (int(num) < 18)
True
A:
num is a string. You can't meaningfully compare a string to an integer and a string is never equal to an integer (so == returns false and < and > return whatever they want). The reason that < and > don't throw an error (before python 3) when you compare strings and integers is to be able to sort heterogeneous lists.
A:
Try num = float(raw_input("Choose..."))
You're evaluating a string in your boolean expressions.
|
Why is this logical expression in python False?
|
My question is, why are these expressions False?
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> num = raw_input("Choose a number: ")
Choose a number: 5
>>> print num
5
>>> print ( num < 18 )
False
>>> print ( num == 5 )
False
Because if i try this:
>>> print ( num > 0 )
True
The expression works fine.
|
[
"This statement:\nnum = raw_input(\"Choose a number: \")\n\nmakes num a string, not a number, despite its misleading name. It so happens that Python 2 lets you compare strings with numbers, and in your version considers all strings larger than all numbers (the contents of the string play no role).\nUse num = int(num) to make an integer (and be sure to use a try/except to catch possible errors when the user has typed something other than a number!) before you start comparing.\n(In Python 3, the function's name changes from raw_input to input, and it still returns strings; however in Python 3 comparing a string with a number is considered an error, so you would get an exception rather than True or False in each of your comparison attempts).\n",
"The variable num does not actually contain the number 5; it contains the string \"5\". Because Python is strongly typed, 5 == \"5\" is False. Try converting it to an integer first:\n>>> print (int(num) < 18)\nTrue\n\n",
"num is a string. You can't meaningfully compare a string to an integer and a string is never equal to an integer (so == returns false and < and > return whatever they want). The reason that < and > don't throw an error (before python 3) when you compare strings and integers is to be able to sort heterogeneous lists.\n",
"Try num = float(raw_input(\"Choose...\"))\nYou're evaluating a string in your boolean expressions.\n"
] |
[
9,
3,
2,
1
] |
[] |
[] |
[
"expression",
"python"
] |
stackoverflow_0002617681_expression_python.txt
|
Q:
BOO Vs IronPython
What is the difference between IronPython and BOO? Is there a need for 2 Python-like languages?
A:
IronPython is designed to be a faithful implementation of Python on the .NET platform. Version 1 targets Python 2.4 for compatibility, and version 2 targets version 2.5 (although most of the Python standard library modules implemented in C aren't supported).
Boo's stated aim is to be a "wrist-friendly [dynamic] language for the CLI." It takes a lot of inspiration from Python, but diverges on four main points:
It's designed specifically to take good advantage of the .NET platform
The designer diverges from Python syntax where he doesn't agree with the design decisions (most notably, lack of explicit self)
The language is explicitly designed to be "wrist friendly" -- that is, to minimize the need for the Shift key or other multi-key combinations to be used.
Boo is statically typed by default, but allows optional duck typing.
There are some other minor differences in implementation/performance, but the divergent design goals above should (IMO) inform your choice of languages.
Two more things to take into account are maturity and community. Python is much more mature than Boo, and has a much larger community. IronPython also has the explicit blessing of Microsoft.
A:
IronPython is a python implementation wheras Boo is another language with a python-esque syntax. One major difference is that Boo is statically typed by default.
I'm sure there are more differences, I've only looked at Boo briefly, but I've been meaning to look at bit deeper (so many languages so little time!).
Here is a list of Boo gotchas for python programmers which sums up the differences quite nicely:
http://boo.codehaus.org/Gotchas+for+Python+Users
A:
IronPython is Python.
Boo looks like Python.
They have different goals and while IronPython aims to be just like Python, Boo does not. Boo is not worried about compatibility with Python like IronPython is...
A:
In a nutshell, Boo's claim to fame is that it is supposed to give you most of the benefits of Python's elegant, terse syntax and very high-level abstractions, but without sacrificing (most) of the speed advantages of a statically typed language like C#.
|
BOO Vs IronPython
|
What is the difference between IronPython and BOO? Is there a need for 2 Python-like languages?
|
[
"IronPython is designed to be a faithful implementation of Python on the .NET platform. Version 1 targets Python 2.4 for compatibility, and version 2 targets version 2.5 (although most of the Python standard library modules implemented in C aren't supported).\nBoo's stated aim is to be a \"wrist-friendly [dynamic] language for the CLI.\" It takes a lot of inspiration from Python, but diverges on four main points:\n\nIt's designed specifically to take good advantage of the .NET platform\nThe designer diverges from Python syntax where he doesn't agree with the design decisions (most notably, lack of explicit self)\nThe language is explicitly designed to be \"wrist friendly\" -- that is, to minimize the need for the Shift key or other multi-key combinations to be used.\nBoo is statically typed by default, but allows optional duck typing.\n\nThere are some other minor differences in implementation/performance, but the divergent design goals above should (IMO) inform your choice of languages.\nTwo more things to take into account are maturity and community. Python is much more mature than Boo, and has a much larger community. IronPython also has the explicit blessing of Microsoft.\n",
"IronPython is a python implementation wheras Boo is another language with a python-esque syntax. One major difference is that Boo is statically typed by default.\nI'm sure there are more differences, I've only looked at Boo briefly, but I've been meaning to look at bit deeper (so many languages so little time!).\nHere is a list of Boo gotchas for python programmers which sums up the differences quite nicely:\n\nhttp://boo.codehaus.org/Gotchas+for+Python+Users\n\n",
"IronPython is Python.\nBoo looks like Python.\nThey have different goals and while IronPython aims to be just like Python, Boo does not. Boo is not worried about compatibility with Python like IronPython is...\n",
"In a nutshell, Boo's claim to fame is that it is supposed to give you most of the benefits of Python's elegant, terse syntax and very high-level abstractions, but without sacrificing (most) of the speed advantages of a statically typed language like C#.\n"
] |
[
18,
11,
3,
1
] |
[] |
[] |
[
"boo",
"clr",
"ironpython",
"python"
] |
stackoverflow_0000600539_boo_clr_ironpython_python.txt
|
Q:
How does ironpython speed compare to other .net languages?
I would like to give sources for what I'm saying but I just dont have them, it's something I heard.
Once a programming professor told me that some software benchmarking done to .net vs Python in some particular items it gave a relation of 5:8 in favor of .NET . That was his argument in favor of Python not being so much slower than .NET
Here it's the thing, I would like to try IronPython since I could combine the web framework I know the most (asp.net) with the language I like the most (Python) and I was wondering about the speed of programs in asp.net in Python vs the speed of programs in ASP.NET with VB.net or C#. Is there any software benchmarking on this?
Also, shouldnt the speeds of IronPython compared to other .NET languages be similar, since IronPython unlike Python have to compile to the .NET intermediate code? Can someone enlight me on these issues?
Greetings
A:
Here are two interesting links with comparisons between IronPython, CPython, and C# (among others):
CPython vs C# (Mono) benchmarks, based on several programs detailed on the site.
CPython vs IronPython benchmarks, based on PyStone and PyBench, for versions 2.6.
So apparently it does along the lines of what your professor told you. But as you know, it depends so much on what you are using.
The difference is mainly due to the dynamic nature of the objects used in Python, whereas C# is strongly typed. So IronPython uses one more level (the DLR - Dynamic Language Runtime) on top of what C# is run from (the CLR - the Common Language Runtime), to resolve this difference.
I usually hate to cite Wikipedia articles, but this is a good starting point: http://en.wikipedia.org/wiki/Dynamic_Language_Runtime
Now to come back to your project, the performances will probably be more dependent on your algorithms/heuristics - how you query a database for example - than on the language. If you are familiar with a web framework and are happy with it, it's a good idea to stick with the same environment rather than gain a possible few percents on something you'll have to tame first. It wouldn't be the same if the application was CPU-intensive of course.
A:
You could enable .net tracing, which outputs timing information at the bottom of the page. Make an app in C#/.Net and an app using Python and look at the differences in timing. That will give you a definitive answer.
In all honesty I think you're better off just using C#, it's "faster" to develop since the VS environment is there for you and it's going to run faster since it doesn't have to use the dynamic language runtime.
A:
IronPython will be considerably slower than C#. You could think of the comparison as very roughly between CPython and C, but with the gap somewhat smaller.
|
How does ironpython speed compare to other .net languages?
|
I would like to give sources for what I'm saying but I just dont have them, it's something I heard.
Once a programming professor told me that some software benchmarking done to .net vs Python in some particular items it gave a relation of 5:8 in favor of .NET . That was his argument in favor of Python not being so much slower than .NET
Here it's the thing, I would like to try IronPython since I could combine the web framework I know the most (asp.net) with the language I like the most (Python) and I was wondering about the speed of programs in asp.net in Python vs the speed of programs in ASP.NET with VB.net or C#. Is there any software benchmarking on this?
Also, shouldnt the speeds of IronPython compared to other .NET languages be similar, since IronPython unlike Python have to compile to the .NET intermediate code? Can someone enlight me on these issues?
Greetings
|
[
"Here are two interesting links with comparisons between IronPython, CPython, and C# (among others):\n\nCPython vs C# (Mono) benchmarks, based on several programs detailed on the site.\nCPython vs IronPython benchmarks, based on PyStone and PyBench, for versions 2.6.\n\nSo apparently it does along the lines of what your professor told you. But as you know, it depends so much on what you are using.\nThe difference is mainly due to the dynamic nature of the objects used in Python, whereas C# is strongly typed. So IronPython uses one more level (the DLR - Dynamic Language Runtime) on top of what C# is run from (the CLR - the Common Language Runtime), to resolve this difference.\nI usually hate to cite Wikipedia articles, but this is a good starting point: http://en.wikipedia.org/wiki/Dynamic_Language_Runtime\nNow to come back to your project, the performances will probably be more dependent on your algorithms/heuristics - how you query a database for example - than on the language. If you are familiar with a web framework and are happy with it, it's a good idea to stick with the same environment rather than gain a possible few percents on something you'll have to tame first. It wouldn't be the same if the application was CPU-intensive of course.\n",
"You could enable .net tracing, which outputs timing information at the bottom of the page. Make an app in C#/.Net and an app using Python and look at the differences in timing. That will give you a definitive answer.\nIn all honesty I think you're better off just using C#, it's \"faster\" to develop since the VS environment is there for you and it's going to run faster since it doesn't have to use the dynamic language runtime.\n",
"IronPython will be considerably slower than C#. You could think of the comparison as very roughly between CPython and C, but with the gap somewhat smaller.\n"
] |
[
9,
1,
0
] |
[] |
[] |
[
".net",
"ironpython",
"performance",
"python"
] |
stackoverflow_0001693205_.net_ironpython_performance_python.txt
|
Q:
How do I write raw binary data in Python?
I've got a Python program that stores and writes data to a file. The data is raw binary data, stored internally as str. I'm writing it out through a utf-8 codec. However, I get UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 25: character maps to <undefined> in the cp1252.py file.
This looks to me like Python is trying to interpret the data using the default code page. But it doesn't have a default code page. That's why I'm using str, not unicode.
I guess my questions are:
How do I represent raw binary data in memory, in Python?
When I'm writing raw binary data out through a codec, how do I encode/unencode it?
A:
NOTE: this was written for Python 2.x. Not sure if applicable to 3.x.
Your use of str for raw binary data in memory is correct.
[If you're using Python 2.6+, it's even better to use bytes which in 2.6+ is just an alias to str but expresses your intention better, and will help if one day you port the code to Python 3.]
As others note, writing binary data through a codec is strange. A write codec takes unicode and outputs bytes into the file. You're trying to do it backwards, hence our confusion about your intentions...
[And your diagnosis of the error looks correct: since the codec expects unicode, Python is decoding your str into unicode with the system's default encoding, which chokes.]
What you want to see in the output file?
If the file should contain the binary data as-is:
Then you must not send it through a codec; you must write it
directly to the file. A codec encodes everything and can only
emit valid encodings of unicode (in your case, valid UTF-8).
There is no input you can give it to make it emit arbitrary
byte sequences!
If you require a mixture of UTF-8 and raw binary data, you
should open the file directly, and intermix writes of some_data
with some_text.encode('utf8')...
Note however that mixing UTF-8 with raw arbitrary data is very
bad design, because such files are very inconvenient to deal
with! Tools that understand unicode will choke on the binary
data, leaving you with not convenient way to even view (let alone
modify) the file.
If you want a friendly representation of arbitrary bytes in
unicode:
Pass data.encode('base64') to the codec. Base64 produces only
clean ascii (letters, numbers, and a little punctuation) so it
can be clearly embedded in anything, it clearly looks to people as
binary data, and it's reasonably compact (slightly over 33%
overhead).
P.S. you may note that data.encode('base64') is strange.
.encode() is supposed to take unicode but I'm giving it a
string?! Python has several pseudo-codecs that convert str->str
such as 'base64' and 'zlib'.
.encode() always returns an str but you'll feed it into a codec
expecting unicode?! In this case it will only contain clean
ascii, so it doesn't matter. You may write explicitly
data.encode('base64').encode('utf8') if it makes you feel
better.
If you need a 1:1 mapping from arbitrary bytes to unicode:
Pass data.decode('latin1') to the codec. latin1 maps
bytes 0-255 to unicode characters 0-255, which is kinda elegant.
The codec will, of course, encode your characters - 128-255 are
encoded as 2 or 3 bytes in UTF-8 (surprisingly, the average
overhead is 50%, more than base64!). This quite kills the
"elegance" of having a 1:1 mapping.
Note also that unicode characters 0-255 include nasty
invisible/control characters (newline, formfeed, soft hyphen, etc.)
making your binary data annoying to view in text editors.
Considering these drawbacks, I do not recommend latin1 unless
you understand exactly why you want it.
I'm just mentioning it as the other "natural" encoding that springs
to mind.
A:
You shouldn't normally use codecs with str, except to turn them into unicodes. Perhaps you should be looking at using the latin-1 codec if you think you want "raw" data in your unicodes.
A:
For your first question: in Python, regular strings (ie, not unicode strings) are binary data. If you want to write the unicode strings and binary data, turn the unicode strings into binary data and put them together:
# encode the unicode string as a string
bytes = unicodeString.encode('utf-8')
# add it to the other string
raw_data += bytes
# write it all to a file
yourFile.write(raw_data)
For your second question: you write() the raw data; then, when you read it, you do so like this:
import codecs
yourFile = codecs.open( "yourFileName", "r", "utf-8" )
# and now just use yourFile.read() to read it
|
How do I write raw binary data in Python?
|
I've got a Python program that stores and writes data to a file. The data is raw binary data, stored internally as str. I'm writing it out through a utf-8 codec. However, I get UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 25: character maps to <undefined> in the cp1252.py file.
This looks to me like Python is trying to interpret the data using the default code page. But it doesn't have a default code page. That's why I'm using str, not unicode.
I guess my questions are:
How do I represent raw binary data in memory, in Python?
When I'm writing raw binary data out through a codec, how do I encode/unencode it?
|
[
"NOTE: this was written for Python 2.x. Not sure if applicable to 3.x.\nYour use of str for raw binary data in memory is correct.\n[If you're using Python 2.6+, it's even better to use bytes which in 2.6+ is just an alias to str but expresses your intention better, and will help if one day you port the code to Python 3.]\nAs others note, writing binary data through a codec is strange. A write codec takes unicode and outputs bytes into the file. You're trying to do it backwards, hence our confusion about your intentions...\n[And your diagnosis of the error looks correct: since the codec expects unicode, Python is decoding your str into unicode with the system's default encoding, which chokes.]\nWhat you want to see in the output file?\n\nIf the file should contain the binary data as-is:\nThen you must not send it through a codec; you must write it \ndirectly to the file. A codec encodes everything and can only \nemit valid encodings of unicode (in your case, valid UTF-8).\nThere is no input you can give it to make it emit arbitrary \nbyte sequences!\n\nIf you require a mixture of UTF-8 and raw binary data, you \nshould open the file directly, and intermix writes of some_data \nwith some_text.encode('utf8')...\n\nNote however that mixing UTF-8 with raw arbitrary data is very \nbad design, because such files are very inconvenient to deal \nwith! Tools that understand unicode will choke on the binary \ndata, leaving you with not convenient way to even view (let alone \nmodify) the file.\nIf you want a friendly representation of arbitrary bytes in \nunicode:\nPass data.encode('base64') to the codec. Base64 produces only \nclean ascii (letters, numbers, and a little punctuation) so it \ncan be clearly embedded in anything, it clearly looks to people as \nbinary data, and it's reasonably compact (slightly over 33% \noverhead).\nP.S. you may note that data.encode('base64') is strange.\n\n.encode() is supposed to take unicode but I'm giving it a \nstring?! Python has several pseudo-codecs that convert str->str \nsuch as 'base64' and 'zlib'.\n.encode() always returns an str but you'll feed it into a codec \nexpecting unicode?! In this case it will only contain clean \nascii, so it doesn't matter. You may write explicitly \ndata.encode('base64').encode('utf8') if it makes you feel \nbetter.\n\nIf you need a 1:1 mapping from arbitrary bytes to unicode:\nPass data.decode('latin1') to the codec. latin1 maps \nbytes 0-255 to unicode characters 0-255, which is kinda elegant.\nThe codec will, of course, encode your characters - 128-255 are \nencoded as 2 or 3 bytes in UTF-8 (surprisingly, the average \noverhead is 50%, more than base64!). This quite kills the \n\"elegance\" of having a 1:1 mapping.\nNote also that unicode characters 0-255 include nasty \ninvisible/control characters (newline, formfeed, soft hyphen, etc.)\nmaking your binary data annoying to view in text editors.\nConsidering these drawbacks, I do not recommend latin1 unless \nyou understand exactly why you want it.\nI'm just mentioning it as the other \"natural\" encoding that springs \nto mind.\n\n",
"You shouldn't normally use codecs with str, except to turn them into unicodes. Perhaps you should be looking at using the latin-1 codec if you think you want \"raw\" data in your unicodes.\n",
"For your first question: in Python, regular strings (ie, not unicode strings) are binary data. If you want to write the unicode strings and binary data, turn the unicode strings into binary data and put them together:\n# encode the unicode string as a string\nbytes = unicodeString.encode('utf-8')\n# add it to the other string\nraw_data += bytes\n# write it all to a file\nyourFile.write(raw_data)\n\nFor your second question: you write() the raw data; then, when you read it, you do so like this:\nimport codecs\nyourFile = codecs.open( \"yourFileName\", \"r\", \"utf-8\" )\n# and now just use yourFile.read() to read it\n\n"
] |
[
22,
0,
0
] |
[] |
[] |
[
"codec",
"python",
"string"
] |
stackoverflow_0002611205_codec_python_string.txt
|
Q:
Python Pyme: Simple decryption without user interaction
I am using Pyme to interface with GPGME and have had no problems signing / encrypting. When I try to decrypt, however, it always brings up the prompt for the passphrase despite having set it via a c.set_passphrase_cb callback. Am I doing something wrong?
A:
I have a similar problem.
My code looks like this:
def passphrase_callback(hint='', desc='', prev_bad=''):
return 'password'
class CryptoEngine:
class NoSignKeys(Exception):
def init(self, str):
Exception.init(self, str)
def __init__(self, user_id, passphrase):
"Initialize with ID (e-mail)"
self.user_id = user_id
self.passphrase = passphrase
def verify(self, data):
c = core.Context()
sig = core.Data(string = data)
file = None
plain = core.Data()
c.op_verify(sig, file, plain)
result = c.op_verify_result()
plain.seek(0, 0)
plaintext = plain.read()
sig = result.signatures
status = False
for s in sig:
status = (s.status == 0)
return status, plaintext
def sign(self, data):
c = core.Context()
for sigkey in c.op_keylist_all(self.user_id, 1):
if sigkey.can_sign:
c.signers_add(sigkey)
if not c.signers_enum(0):
raise CryptoEngine.NoSignKeys("No secret %s's keys suitable for signing" % self.user_id)
plain = core.Data(data)
sig = core.Data()
c.set_passphrase_cb(passphrase_callback)
c.op_sign(plain, sig, mode.CLEAR)
sig.seek(0, 0)
return sig.read()
Despite setting the passphrase callback I still either get a message box asking for the
passphrase or just an exception notifying of a bad password.
Did someone solve this problem and could share his knowledge?
Thanks,
Yan
A:
Add "c.set_armor(1)" before you set the passphrase callback.
|
Python Pyme: Simple decryption without user interaction
|
I am using Pyme to interface with GPGME and have had no problems signing / encrypting. When I try to decrypt, however, it always brings up the prompt for the passphrase despite having set it via a c.set_passphrase_cb callback. Am I doing something wrong?
|
[
"I have a similar problem.\nMy code looks like this:\ndef passphrase_callback(hint='', desc='', prev_bad=''):\n return 'password'\nclass CryptoEngine:\n class NoSignKeys(Exception):\n def init(self, str):\n Exception.init(self, str)\ndef __init__(self, user_id, passphrase):\n \"Initialize with ID (e-mail)\"\n self.user_id = user_id\n self.passphrase = passphrase\ndef verify(self, data):\n c = core.Context()\n sig = core.Data(string = data)\n file = None\n plain = core.Data()\n c.op_verify(sig, file, plain)\n result = c.op_verify_result()\n plain.seek(0, 0)\n plaintext = plain.read()\n sig = result.signatures\n status = False\n for s in sig:\n status = (s.status == 0)\n return status, plaintext\n\ndef sign(self, data):\n c = core.Context()\n for sigkey in c.op_keylist_all(self.user_id, 1):\n if sigkey.can_sign:\n c.signers_add(sigkey)\n if not c.signers_enum(0):\n raise CryptoEngine.NoSignKeys(\"No secret %s's keys suitable for signing\" % self.user_id)\n\n plain = core.Data(data)\n sig = core.Data()\n c.set_passphrase_cb(passphrase_callback)\n c.op_sign(plain, sig, mode.CLEAR)\n sig.seek(0, 0)\n return sig.read()\n\nDespite setting the passphrase callback I still either get a message box asking for the \npassphrase or just an exception notifying of a bad password.\nDid someone solve this problem and could share his knowledge?\nThanks,\nYan\n",
"Add \"c.set_armor(1)\" before you set the passphrase callback.\n"
] |
[
1,
0
] |
[] |
[] |
[
"gnupg",
"gpgme",
"pyme",
"python"
] |
stackoverflow_0001288959_gnupg_gpgme_pyme_python.txt
|
Q:
How to replace empty string with zero in comma-separated string?
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
A:
You could use
[(int(x) if x else 0) for x in data.split(',')]
data.split(',') splits the string into a list. It splits on the comma character:
['8', '5', '', '1', '4', '7', '', '', '', ...]
The expression
(int(x) if x else 0)
returns int(x) if x is True, 0 if x is False. Note that the empty string is False.
A:
Regular expressions are often unnecessary in Python. Given string s, try:
','.join(x or '0' for x in s.split(','))
I am assuming you want to fill the blanks with 0. If you want a list of integers instead of a string, try this:
[(x and int(x)) or 0 for x in s.split(',')]
A:
s = "8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
s = re.sub('((?<=,)|^)(?=,|$)', '0', s)
print s
Prints:
8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8,6,3,9,0,2,5,4,0,0,0,0,3,2,0,0,7,4,1,1,0,4,0,6,9,0,5,0,0,0,5,0,0,1,0,6,3,0,0,6,5,0,0,0,7,4,0,1,7,6,0,0,0,8,0,5,0,0,7,1,0,3,9,0
A:
>>> s="8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
>>> s=s.split(",")
>>> for n,i in enumerate(s):
... if i=="" : s[n]=0
...
>>> s
['8', '5', 0, '1', '4', '7', 0, 0, 0, '7', 0, '1', '9', '3', '6', 0, 0, '8', '6', '3', '9', 0, '2', '5', '4', 0, 0, 0, 0, '3', '2', 0, 0, '7', '4', '1', '1', 0, '4', 0, '6', '9', 0, '5', 0, 0, 0, '5', 0, 0, '1', 0, '6', '3', 0, 0, '6', '5', 0, 0, 0, '7', '4', 0, '1', '7', '6', 0, 0, 0, '8', 0, '5', 0, 0, '7', '1', 0, '3', '9', 0]
>>>
A:
Simplest I can think of is
[int(x or 0) for x in s.split(',')]
or
[int('0'+x) for x in s.split(',')]
A:
My solution uses map,lambda, and split. The final code looks like this:
sudoku_string = "1,2,3,,4,5,,6"
output_string = map(lambda x: '0' if x=='' else x, sudoku_string.split(","))
If you want the output as a list (i.e. [1,2,3,0,4,5,0,6]), then use
output_list = map(lambda x: 0 if x=='' else int(x), sudoku_string.split(",")
The commands map and lambda are very useful. map takes in a function and a list (really an iterable, but that's another story), and applies the function to every element of this list. So
def plus_one(x):
return x+1
map(plus_one, [1,2,3,4])
returns [2,3,4,5]. lambda is a way to quickly define functions, so we can write plus_one as
lambda x: x+1
Lastly, split takes a string and creates a list by 'splitting' the string by the argument you pass. So "1 2 3 4".split(" ") yields [1,2,3,4].
|
How to replace empty string with zero in comma-separated string?
|
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
|
[
"You could use \n[(int(x) if x else 0) for x in data.split(',')]\n\ndata.split(',') splits the string into a list. It splits on the comma character:\n['8', '5', '', '1', '4', '7', '', '', '', ...]\n\nThe expression\n(int(x) if x else 0)\n\nreturns int(x) if x is True, 0 if x is False. Note that the empty string is False.\n",
"Regular expressions are often unnecessary in Python. Given string s, try:\n','.join(x or '0' for x in s.split(','))\n\nI am assuming you want to fill the blanks with 0. If you want a list of integers instead of a string, try this:\n[(x and int(x)) or 0 for x in s.split(',')]\n\n",
"s = \"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,\"\ns = re.sub('((?<=,)|^)(?=,|$)', '0', s)\nprint s\n\nPrints:\n8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8,6,3,9,0,2,5,4,0,0,0,0,3,2,0,0,7,4,1,1,0,4,0,6,9,0,5,0,0,0,5,0,0,1,0,6,3,0,0,6,5,0,0,0,7,4,0,1,7,6,0,0,0,8,0,5,0,0,7,1,0,3,9,0\n\n",
">>> s=\"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,\"\n>>> s=s.split(\",\")\n>>> for n,i in enumerate(s):\n... if i==\"\" : s[n]=0\n...\n>>> s\n['8', '5', 0, '1', '4', '7', 0, 0, 0, '7', 0, '1', '9', '3', '6', 0, 0, '8', '6', '3', '9', 0, '2', '5', '4', 0, 0, 0, 0, '3', '2', 0, 0, '7', '4', '1', '1', 0, '4', 0, '6', '9', 0, '5', 0, 0, 0, '5', 0, 0, '1', 0, '6', '3', 0, 0, '6', '5', 0, 0, 0, '7', '4', 0, '1', '7', '6', 0, 0, 0, '8', 0, '5', 0, 0, '7', '1', 0, '3', '9', 0]\n>>>\n\n",
"Simplest I can think of is\n[int(x or 0) for x in s.split(',')]\n\nor\n[int('0'+x) for x in s.split(',')]\n\n",
"My solution uses map,lambda, and split. The final code looks like this:\nsudoku_string = \"1,2,3,,4,5,,6\"\noutput_string = map(lambda x: '0' if x=='' else x, sudoku_string.split(\",\"))\n\nIf you want the output as a list (i.e. [1,2,3,0,4,5,0,6]), then use\noutput_list = map(lambda x: 0 if x=='' else int(x), sudoku_string.split(\",\")\n\nThe commands map and lambda are very useful. map takes in a function and a list (really an iterable, but that's another story), and applies the function to every element of this list. So\ndef plus_one(x):\n return x+1\nmap(plus_one, [1,2,3,4])\n\nreturns [2,3,4,5]. lambda is a way to quickly define functions, so we can write plus_one as \nlambda x: x+1\n\nLastly, split takes a string and creates a list by 'splitting' the string by the argument you pass. So \"1 2 3 4\".split(\" \") yields [1,2,3,4].\n"
] |
[
11,
5,
4,
0,
0,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002606976_python_string.txt
|
Q:
SQLAlchemy Mapping problem
I am trying to sqlalchemy to correctly map my data. Note that a unified group is basically a group of groups. (One unifiedGroup maps to many groups but each group can only map to one ug).
So basically this is the definition of my unifiedGroups:
CREATE TABLE `unifiedGroups` (
`ugID` INT AUTO_INCREMENT,
`gID` INT NOT NULL,
PRIMARY KEY(`ugID`, `gID`),
KEY( `gID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
;
Note that each row is a ugID, gID tuple. ( I do not know before hand how many gID is per ugID so this is probably the most sensible and simplest method).
Definition for my UnifiedGroup class
class UnifiedGroup(object):
"""UnifiedProduct behaves very much like a group
"""
def __init__(self, ugID):
self.ugID=ugID
#Added by mapping
self.groups=False
def __str__(self):
return '<%s:%s>' % (self.ugID, ','.join( [g for g in self.groups]))
These are my mapping tables:
tb_groupsInfo = Table( 'groupsInfo', metadata,
Column('gID', Integer, primary_key=True),
Column('gName', String(128)),
)
tb_unifiedGroups = Table( 'unifiedGroups', metadata,
Column('ugID', Integer, primary_key=True),
Column('gID', Integer, ForeignKey('groupsInfo.gID')),
)
My mapper maps in the following manner:
mapper( UnifiedGroup, tb_unifiedGroups, properties={
'groups': relation( Group, backref='unifiedGroup')
})
However, when I tried to do groupInstance.unifiedGroup, I am getting an empty list [],
while groupInstance.unifiedGroup.groups returns me an error:
AttributeError: 'InstrumentedList' object has no attribute 'groups'
Traceback (most recent call last):
File "Mapping.py", line 119, in <module>
print p.group.unifiedGroup.groups
AttributeError: 'InstrumentedList' object has no attribute 'groups'
What is wrong?
A:
If you want a one-to-many relationship between unifiedgroups and groups, you will need to have the foreign key be in the groups table. It simply doesn't make sense any other way.
|
SQLAlchemy Mapping problem
|
I am trying to sqlalchemy to correctly map my data. Note that a unified group is basically a group of groups. (One unifiedGroup maps to many groups but each group can only map to one ug).
So basically this is the definition of my unifiedGroups:
CREATE TABLE `unifiedGroups` (
`ugID` INT AUTO_INCREMENT,
`gID` INT NOT NULL,
PRIMARY KEY(`ugID`, `gID`),
KEY( `gID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
;
Note that each row is a ugID, gID tuple. ( I do not know before hand how many gID is per ugID so this is probably the most sensible and simplest method).
Definition for my UnifiedGroup class
class UnifiedGroup(object):
"""UnifiedProduct behaves very much like a group
"""
def __init__(self, ugID):
self.ugID=ugID
#Added by mapping
self.groups=False
def __str__(self):
return '<%s:%s>' % (self.ugID, ','.join( [g for g in self.groups]))
These are my mapping tables:
tb_groupsInfo = Table( 'groupsInfo', metadata,
Column('gID', Integer, primary_key=True),
Column('gName', String(128)),
)
tb_unifiedGroups = Table( 'unifiedGroups', metadata,
Column('ugID', Integer, primary_key=True),
Column('gID', Integer, ForeignKey('groupsInfo.gID')),
)
My mapper maps in the following manner:
mapper( UnifiedGroup, tb_unifiedGroups, properties={
'groups': relation( Group, backref='unifiedGroup')
})
However, when I tried to do groupInstance.unifiedGroup, I am getting an empty list [],
while groupInstance.unifiedGroup.groups returns me an error:
AttributeError: 'InstrumentedList' object has no attribute 'groups'
Traceback (most recent call last):
File "Mapping.py", line 119, in <module>
print p.group.unifiedGroup.groups
AttributeError: 'InstrumentedList' object has no attribute 'groups'
What is wrong?
|
[
"If you want a one-to-many relationship between unifiedgroups and groups, you will need to have the foreign key be in the groups table. It simply doesn't make sense any other way.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002617697_python_sqlalchemy.txt
|
Q:
Exposing classes inside modules within a Python package directly in the package's namespace
I have a wxPython application with the various GUI classes in their own modules in a package called gui. With this setup, importing the main window would be done as follows:
from gui.mainwindow import MainWindow
This looked messy to me so I changed the __init__.py file for the gui package to import the class directly into the package namespace:
from mainwindow import MainWindow
This allows me to import the main window like this:
from gui import MainWindow
This looks better to me aesthetically and I think it also more closely represents what I'm doing (importing the MainWindow class from the gui "namespace"). The reason I made the gui package was to keep all the GUI stuff together. I could have just as easily made a single gui module and stuffed all the GUI classes in it, but I think that would have been unmanageable. The package now appears to work like a module, but allows me to separate the classes into their own modules (along with helper functions, etc.).
This whole thing strikes me as somewhat petty, I just thought I'd throw it out there to see what others think about the idea.
A:
Well, this is a quite common pattern and I think it is also the reason why you can include things inside __init__.py files.
As a confirmation, just grep for import statements in __init__.py files, and you will see that it is widely used in both standard library and common packages.
|
Exposing classes inside modules within a Python package directly in the package's namespace
|
I have a wxPython application with the various GUI classes in their own modules in a package called gui. With this setup, importing the main window would be done as follows:
from gui.mainwindow import MainWindow
This looked messy to me so I changed the __init__.py file for the gui package to import the class directly into the package namespace:
from mainwindow import MainWindow
This allows me to import the main window like this:
from gui import MainWindow
This looks better to me aesthetically and I think it also more closely represents what I'm doing (importing the MainWindow class from the gui "namespace"). The reason I made the gui package was to keep all the GUI stuff together. I could have just as easily made a single gui module and stuffed all the GUI classes in it, but I think that would have been unmanageable. The package now appears to work like a module, but allows me to separate the classes into their own modules (along with helper functions, etc.).
This whole thing strikes me as somewhat petty, I just thought I'd throw it out there to see what others think about the idea.
|
[
"Well, this is a quite common pattern and I think it is also the reason why you can include things inside __init__.py files.\nAs a confirmation, just grep for import statements in __init__.py files, and you will see that it is widely used in both standard library and common packages.\n"
] |
[
6
] |
[] |
[] |
[
"namespaces",
"python",
"wxpython"
] |
stackoverflow_0002618425_namespaces_python_wxpython.txt
|
Q:
sampling integers uniformly efficiently in python using numpy/scipy
I have a problem where depending on the result of a random coin flip, I have to sample a random starting position from a string. If the sampling of this random position is uniform over the string, I thought of two approaches to do it: one using multinomial from numpy.random, the other using the simple randint function of Python standard lib. I tested this as follows:
from numpy import *
from numpy.random import multinomial
from random import randint
import time
def use_multinomial(length, num_points):
probs = ones(length)/float(length)
for n in range(num_points):
result = multinomial(1, probs)
def use_rand(length, num_points):
for n in range(num_points):
rand(1, length)
def main():
length = 1700
num_points = 50000
t1 = time.time()
use_multinomial(length, num_points)
t2 = time.time()
print "Multinomial took: %s seconds" %(t2 - t1)
t1 = time.time()
use_rand(length, num_points)
t2 = time.time()
print "Rand took: %s seconds" %(t2 - t1)
if __name__ == '__main__':
main()
The output is:
Multinomial took: 6.58072400093 seconds
Rand took: 2.35189199448 seconds
it seems like randint is faster, but it still seems very slow to me. Is there a vectorized way to get this to be much faster, using numpy or scipy?
thanks.
A:
I changed your code to actually return values (and used randint instead of rand - isn't that what you meant?) like this...
def use_multinomial(length, num_points):
probs = ones(length)/float(length)
return multinomial(1, probs, num_points)
def use_rand(length, num_points):
return [randint(1,length) for _ in range(num_points)]
Then I tried my own version, using numpy.random.randint to generate a numpy array of random points on the string:
def use_np_randint(length, num_point):
return nprandint(1, length, num_points)
The results:
Multinomial took: 13.6279997826 seconds
Rand took: 0.185000181198 seconds
NP randint took: 0.00100016593933 seconds
Multinomial is obviously really slow comparitively, but is that even what you want? I thought you said you wanted a uniform distribution? Using numpy's randint is clearly the fastest of the bunch.
|
sampling integers uniformly efficiently in python using numpy/scipy
|
I have a problem where depending on the result of a random coin flip, I have to sample a random starting position from a string. If the sampling of this random position is uniform over the string, I thought of two approaches to do it: one using multinomial from numpy.random, the other using the simple randint function of Python standard lib. I tested this as follows:
from numpy import *
from numpy.random import multinomial
from random import randint
import time
def use_multinomial(length, num_points):
probs = ones(length)/float(length)
for n in range(num_points):
result = multinomial(1, probs)
def use_rand(length, num_points):
for n in range(num_points):
rand(1, length)
def main():
length = 1700
num_points = 50000
t1 = time.time()
use_multinomial(length, num_points)
t2 = time.time()
print "Multinomial took: %s seconds" %(t2 - t1)
t1 = time.time()
use_rand(length, num_points)
t2 = time.time()
print "Rand took: %s seconds" %(t2 - t1)
if __name__ == '__main__':
main()
The output is:
Multinomial took: 6.58072400093 seconds
Rand took: 2.35189199448 seconds
it seems like randint is faster, but it still seems very slow to me. Is there a vectorized way to get this to be much faster, using numpy or scipy?
thanks.
|
[
"I changed your code to actually return values (and used randint instead of rand - isn't that what you meant?) like this...\ndef use_multinomial(length, num_points):\n probs = ones(length)/float(length)\n return multinomial(1, probs, num_points)\n\ndef use_rand(length, num_points):\n return [randint(1,length) for _ in range(num_points)]\n\nThen I tried my own version, using numpy.random.randint to generate a numpy array of random points on the string:\ndef use_np_randint(length, num_point):\n return nprandint(1, length, num_points)\n\nThe results:\nMultinomial took: 13.6279997826 seconds\nRand took: 0.185000181198 seconds\nNP randint took: 0.00100016593933 seconds\n\nMultinomial is obviously really slow comparitively, but is that even what you want? I thought you said you wanted a uniform distribution? Using numpy's randint is clearly the fastest of the bunch.\n"
] |
[
3
] |
[] |
[] |
[
"numpy",
"python",
"random",
"scipy"
] |
stackoverflow_0002618400_numpy_python_random_scipy.txt
|
Q:
build an API service in Django
I want to build an API service using Django. A basic workflow goes like this:
First, an http request goes to http://mycompany.com/create?id=001&callback=http://callback.com. It will create a folder on the server with name 001.
Second, if the folder does not exist, it will be created. You get response immediately in XML format. It will look like:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>
<statusCode>0</statusCode>
<message>Success</message>
</status>
<group id="001"/>
</response>
Finally, the server will do its job (i.e. creating the folder). After it is done, the server does a callback to the URL provided.
Currently, I use
return render_to_response('create.xml', {'statusCode': statusCode,
'statusMessage': statusMessage,
'groupId': groupId,
}, mimetype = 'text/xml')
to send the XML response back. I have an XML template which has statusCode, statusMessage, groupId placeholders.
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>
<statusCode>{{ statusCode }}</statusCode>
<message>{{ statusMessage }}</message>
</status>
{% if not statusCode %}
<group id="{{ groupId }}"/>
{% endif %}
</response>
But in this way I have to put step 3 before step 2, because otherwise step 3 will not be executed if it is after return statement.
Can somebody give me some suggestions how to do this? Thanks.
A:
I have a feeling that you might be missing some Django fundamentals here.
Why is create.py inside of your url?
If you're using Django's url routing and views, the render_to_response should work fine. You might be jumping to an incorrect conclusion regarding why your response isn't getting returned.
I'm not sure I understand the statement:
But in this way I have to put step 3
before step 2, because otherwise step
3 will not be executed if it is after
return statement.
Step 3 is not after the return statement. It is part of the return statement.
You could always do something like this to split up the process:
# Code that creates folder, statusCode, statusMessage, groupId
response = render_to_response('create.xml', {'statusCode': statusCode,
'statusMessage': statusMessage,
'groupId': groupId,
}, mimetype = 'text/xml')
# Some other code, maybe an import pdb; pdb.set_trace()
# So that you can inspect the response inside of a python shell.
return response
A:
You can use celery for the problem of te queue
|
build an API service in Django
|
I want to build an API service using Django. A basic workflow goes like this:
First, an http request goes to http://mycompany.com/create?id=001&callback=http://callback.com. It will create a folder on the server with name 001.
Second, if the folder does not exist, it will be created. You get response immediately in XML format. It will look like:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>
<statusCode>0</statusCode>
<message>Success</message>
</status>
<group id="001"/>
</response>
Finally, the server will do its job (i.e. creating the folder). After it is done, the server does a callback to the URL provided.
Currently, I use
return render_to_response('create.xml', {'statusCode': statusCode,
'statusMessage': statusMessage,
'groupId': groupId,
}, mimetype = 'text/xml')
to send the XML response back. I have an XML template which has statusCode, statusMessage, groupId placeholders.
<?xml version="1.0" encoding="UTF-8"?>
<response>
<status>
<statusCode>{{ statusCode }}</statusCode>
<message>{{ statusMessage }}</message>
</status>
{% if not statusCode %}
<group id="{{ groupId }}"/>
{% endif %}
</response>
But in this way I have to put step 3 before step 2, because otherwise step 3 will not be executed if it is after return statement.
Can somebody give me some suggestions how to do this? Thanks.
|
[
"I have a feeling that you might be missing some Django fundamentals here. \nWhy is create.py inside of your url? \nIf you're using Django's url routing and views, the render_to_response should work fine. You might be jumping to an incorrect conclusion regarding why your response isn't getting returned.\nI'm not sure I understand the statement:\n\nBut in this way I have to put step 3\n before step 2, because otherwise step\n 3 will not be executed if it is after\n return statement.\n\nStep 3 is not after the return statement. It is part of the return statement.\nYou could always do something like this to split up the process:\n# Code that creates folder, statusCode, statusMessage, groupId\nresponse = render_to_response('create.xml', {'statusCode': statusCode,\n 'statusMessage': statusMessage,\n 'groupId': groupId,\n }, mimetype = 'text/xml')\n# Some other code, maybe an import pdb; pdb.set_trace() \n# So that you can inspect the response inside of a python shell.\nreturn response\n\n",
"You can use celery for the problem of te queue\n"
] |
[
4,
2
] |
[] |
[] |
[
"api",
"django",
"python"
] |
stackoverflow_0002618126_api_django_python.txt
|
Q:
Python Game using pyGame with Window Menu elements
Here's the deal. I'm trying to write an arkanoid clone game and the thing is that I need a window menu like you get in pyGTK. For example File->(Open/Save/Exit) .. something like that and opening an "about" context where the author should be written.
I'm already using pyGame for writting the game logic. I've tried pgu to write the GUI but that doesn't help me, altough it has those menu elements I'm taking about, you can't include the screen of the game in it's container.
Does anybody know how to include such window menus with the usage of pyGame ?
A:
wxPython allows you to integrate a Pygame window inside of a "normal" wxPython window - check out their wiki entry for how to do it. This should allow you to have a normal window (with File/Help/etc.) menus, but have a Pygame surface to which you can draw for your game.
|
Python Game using pyGame with Window Menu elements
|
Here's the deal. I'm trying to write an arkanoid clone game and the thing is that I need a window menu like you get in pyGTK. For example File->(Open/Save/Exit) .. something like that and opening an "about" context where the author should be written.
I'm already using pyGame for writting the game logic. I've tried pgu to write the GUI but that doesn't help me, altough it has those menu elements I'm taking about, you can't include the screen of the game in it's container.
Does anybody know how to include such window menus with the usage of pyGame ?
|
[
"wxPython allows you to integrate a Pygame window inside of a \"normal\" wxPython window - check out their wiki entry for how to do it. This should allow you to have a normal window (with File/Help/etc.) menus, but have a Pygame surface to which you can draw for your game.\n"
] |
[
4
] |
[] |
[] |
[
"menu",
"pygame",
"python",
"user_interface"
] |
stackoverflow_0002618446_menu_pygame_python_user_interface.txt
|
Q:
Storing URLs while Spidering
I created a little web spider in Python which I'm using to collect URLs. I'm not interested in the content. Right now I'm keeping all the visited URLs in a set in memory, because I don't want my spider to visit URLs twice. Of course that's a very limited way of accomplishing this.
So what's the best way to keep track of my visited URLs?
Should I use a database?
which one? MySQL, SQLite, PostgreSQL?
how should I save the URLs? As a primary key trying to insert every URL before visiting it?
Or should I write them to a file?
one file?
multiple files? how should I design the file-structure?
I'm sure there are books and a lot of papers on this or similar topics. Can you give me some advice what I should read?
A:
I've written a lot of spiders. To me, a bigger problem than running out of memory is the potential of losing all the URLs you've spidered already if the code or machine crashes or you decide you need to tweak the code. If you run out of RAM most machines and OSes these days will page so you'll slow down but still function. Having to rebuild a set of URLs gathered over hours and hours of run-time because its no longer available can be a real blow to productivity.
Keeping information in RAM that you do NOT want to lose is bad. Obviously a database is the way to go at that point because you need fast random access to see if you've already found a URL. Of course in-memory lookups are faster but the trade-off of figuring out WHICH urls to keep in memory adds overhead. Rather than try writing code to determine which URLs I need/don't-need, I keep it in the database and concentrate on making my code clean and maintainable and my SQL queries and schemas sensible. Make your URL field a unique index and the DBM will be able to find them in no time while automatically avoiding redundant links.
Your connection to the internet and sites you're accessing will probably be a lot slower than your connection to a database on a machine on your internal network. A SQLite database on the same machine might be the fastest, though the DBM itself isn't as sophisticated as Postgres, which is my favorite. I found that putting the database on another machine on the same switch as my spidering machine to be extremely fast; Making one machine handle the spidering, parsing, and then the database reads/writes is pretty intensive so if you have an old box throw Linux on it, install Postgres, and go to town. Throw some extra RAM in the box if you need more speed. Having that separate box for database use can be very nice.
A:
These seem to be the important aspects to me:
You can't keep the URLs in memory as RAM will get too high
You need fast existence lookups at least O(logn)
You need fast insertions
There are many ways to do this and it depends on how big your database will get. I think an SQL database can provide a good model for your problem.
Probably all you need is an SQLite database. Typically string lookups for existence check is a slow operation. To speed this up you can create a CRC hash of the URL and store both the CRC and URL in your database. You would have an index on that CRC field.
When you insert: You insert the URL and the hash
When you want to do an existance lookup: You take the CRC of the potentially new URL and check if it is in your database already.
There is of course a chance of collision on the URL hashes, but if 100% spanning is not important to you then you can take the hit of not having a URL in your DB when there is a collision.
You could also decrease collisions in many ways. For example you can increase the size of your CRC (CRC8 instead of CRC4) and use a hashing algorithm with a bigger size. Or use CRC as well as URL length.
A:
It depends on the scale of the spidering you're going to be doing, and the kind of machine you're doing it on. Suppose a typical URL is a string of 60 bytes or so, an in-memory set will take a bit more than 100 bytes per URL (sets and dicts in Python are never allowed to grow beyond 60% full, for speed reasons). If you have a 64-bit machine (and Python distro) with about 16 GB of RAM available, you could surely devote over 10 GB to the crucial set in question, letting you easily spider about 100 million URLs or so; but at the other extreme, if you have a 32-bit machine with 3GB of RAM, you clearly can't devote much more than a GB to the crucial set, limiting you to about 10 million URLs. Sqlite would help around the same range of sized where a 32-bit machine couldn't make it but a generously-endowed 64-bit one could -- say 100 or 200 million URLs.
Beyond those, I'd recommend PostgreSQL, which also has the advantage of being able to run on a different machine (on a fast LAN) with basically no problems, letting you devote your main machine to spidering. I guess MySQL &c would be OK for that too, but I love PostgreSQL standard compliance and robustness;-). This would allow, say, a few billion URLs with no problems (just a fast disk, or better a RAID arrangement, and as much RAM as you can afford to speed things up, of course).
Trying to save memory/storage by using a fixed-length hash in lieu of URLs that might be quite long is fine if you're OK with an occasional false positive that will stop you from crawling what's actually a new URL. Such "collisions" need not be at all likely: even if you only use 8 bytes for the hash, you should only have a substantial risk of some collision when you're looking at billions of URLs (the "square root heuristic" for this well-known problem).
With 8-bytes strings to represent the URLs, the in-memory set architecture should easily support a billion URLs or more on a well-endowed machine as above outlined.
So, roughly how many URLs do you want to spider, and how much RAM can you spare?-)
A:
Are you just storing URL's? You should take a look at mongoDB. It's a NoSQL database that's pretty easy to implement.
http://try.mongodb.org/
It's got python bindings, too:
http://api.mongodb.org/python/1.5.2%2B/index.html
A:
Since it's likely that you'll see similar URLs at similar times (e.g., while spidering a website, you'll see lots of links to the main page of the website) I would advise that you keep the URLs in a dictionary until your memory becomes limited (just hardcode a reasonable number like 10M URLs or similar) and then flush the dictionary to a CDB database file when it becomes too large.
That way, the majority of your URL checks will be in memory (which is fast) while the ones that aren't in memory will still require only 1-2 reads from disk to verify that you've visited them.
A:
Consider Pickling for now: Simple structured storage.
Mileage will vary of course because, as the other responders have said, you'll quickly exhaust your RAM.
|
Storing URLs while Spidering
|
I created a little web spider in Python which I'm using to collect URLs. I'm not interested in the content. Right now I'm keeping all the visited URLs in a set in memory, because I don't want my spider to visit URLs twice. Of course that's a very limited way of accomplishing this.
So what's the best way to keep track of my visited URLs?
Should I use a database?
which one? MySQL, SQLite, PostgreSQL?
how should I save the URLs? As a primary key trying to insert every URL before visiting it?
Or should I write them to a file?
one file?
multiple files? how should I design the file-structure?
I'm sure there are books and a lot of papers on this or similar topics. Can you give me some advice what I should read?
|
[
"I've written a lot of spiders. To me, a bigger problem than running out of memory is the potential of losing all the URLs you've spidered already if the code or machine crashes or you decide you need to tweak the code. If you run out of RAM most machines and OSes these days will page so you'll slow down but still function. Having to rebuild a set of URLs gathered over hours and hours of run-time because its no longer available can be a real blow to productivity.\nKeeping information in RAM that you do NOT want to lose is bad. Obviously a database is the way to go at that point because you need fast random access to see if you've already found a URL. Of course in-memory lookups are faster but the trade-off of figuring out WHICH urls to keep in memory adds overhead. Rather than try writing code to determine which URLs I need/don't-need, I keep it in the database and concentrate on making my code clean and maintainable and my SQL queries and schemas sensible. Make your URL field a unique index and the DBM will be able to find them in no time while automatically avoiding redundant links.\nYour connection to the internet and sites you're accessing will probably be a lot slower than your connection to a database on a machine on your internal network. A SQLite database on the same machine might be the fastest, though the DBM itself isn't as sophisticated as Postgres, which is my favorite. I found that putting the database on another machine on the same switch as my spidering machine to be extremely fast; Making one machine handle the spidering, parsing, and then the database reads/writes is pretty intensive so if you have an old box throw Linux on it, install Postgres, and go to town. Throw some extra RAM in the box if you need more speed. Having that separate box for database use can be very nice.\n",
"These seem to be the important aspects to me:\n\nYou can't keep the URLs in memory as RAM will get too high\nYou need fast existence lookups at least O(logn)\nYou need fast insertions \n\nThere are many ways to do this and it depends on how big your database will get. I think an SQL database can provide a good model for your problem. \nProbably all you need is an SQLite database. Typically string lookups for existence check is a slow operation. To speed this up you can create a CRC hash of the URL and store both the CRC and URL in your database. You would have an index on that CRC field. \n\nWhen you insert: You insert the URL and the hash\nWhen you want to do an existance lookup: You take the CRC of the potentially new URL and check if it is in your database already. \n\nThere is of course a chance of collision on the URL hashes, but if 100% spanning is not important to you then you can take the hit of not having a URL in your DB when there is a collision. \nYou could also decrease collisions in many ways. For example you can increase the size of your CRC (CRC8 instead of CRC4) and use a hashing algorithm with a bigger size. Or use CRC as well as URL length. \n",
"It depends on the scale of the spidering you're going to be doing, and the kind of machine you're doing it on. Suppose a typical URL is a string of 60 bytes or so, an in-memory set will take a bit more than 100 bytes per URL (sets and dicts in Python are never allowed to grow beyond 60% full, for speed reasons). If you have a 64-bit machine (and Python distro) with about 16 GB of RAM available, you could surely devote over 10 GB to the crucial set in question, letting you easily spider about 100 million URLs or so; but at the other extreme, if you have a 32-bit machine with 3GB of RAM, you clearly can't devote much more than a GB to the crucial set, limiting you to about 10 million URLs. Sqlite would help around the same range of sized where a 32-bit machine couldn't make it but a generously-endowed 64-bit one could -- say 100 or 200 million URLs.\nBeyond those, I'd recommend PostgreSQL, which also has the advantage of being able to run on a different machine (on a fast LAN) with basically no problems, letting you devote your main machine to spidering. I guess MySQL &c would be OK for that too, but I love PostgreSQL standard compliance and robustness;-). This would allow, say, a few billion URLs with no problems (just a fast disk, or better a RAID arrangement, and as much RAM as you can afford to speed things up, of course).\nTrying to save memory/storage by using a fixed-length hash in lieu of URLs that might be quite long is fine if you're OK with an occasional false positive that will stop you from crawling what's actually a new URL. Such \"collisions\" need not be at all likely: even if you only use 8 bytes for the hash, you should only have a substantial risk of some collision when you're looking at billions of URLs (the \"square root heuristic\" for this well-known problem).\nWith 8-bytes strings to represent the URLs, the in-memory set architecture should easily support a billion URLs or more on a well-endowed machine as above outlined.\nSo, roughly how many URLs do you want to spider, and how much RAM can you spare?-)\n",
"Are you just storing URL's? You should take a look at mongoDB. It's a NoSQL database that's pretty easy to implement.\nhttp://try.mongodb.org/\nIt's got python bindings, too:\nhttp://api.mongodb.org/python/1.5.2%2B/index.html\n",
"Since it's likely that you'll see similar URLs at similar times (e.g., while spidering a website, you'll see lots of links to the main page of the website) I would advise that you keep the URLs in a dictionary until your memory becomes limited (just hardcode a reasonable number like 10M URLs or similar) and then flush the dictionary to a CDB database file when it becomes too large.\nThat way, the majority of your URL checks will be in memory (which is fast) while the ones that aren't in memory will still require only 1-2 reads from disk to verify that you've visited them.\n",
"Consider Pickling for now: Simple structured storage. \nMileage will vary of course because, as the other responders have said, you'll quickly exhaust your RAM.\n"
] |
[
9,
7,
4,
2,
1,
0
] |
[] |
[] |
[
"database",
"python",
"storage",
"url",
"web_crawler"
] |
stackoverflow_0002615830_database_python_storage_url_web_crawler.txt
|
Q:
Error install PyGtk
I tried to install pygtk on mac. I downloaded the pygtk file, opened up terminal and set it to my working directory, then ran the command "python setup.py install". There was an import error because there was no module dsextras. Does anyone know how to install pygtk on a mac or get dsextras.
A:
PyGtk is a beast to install because has many dependencies (see this post).
I recommend you to install pyGtk using macports, it will handle dependencies hell for you.
|
Error install PyGtk
|
I tried to install pygtk on mac. I downloaded the pygtk file, opened up terminal and set it to my working directory, then ran the command "python setup.py install". There was an import error because there was no module dsextras. Does anyone know how to install pygtk on a mac or get dsextras.
|
[
"PyGtk is a beast to install because has many dependencies (see this post).\nI recommend you to install pyGtk using macports, it will handle dependencies hell for you.\n"
] |
[
2
] |
[] |
[] |
[
"pygtk",
"python"
] |
stackoverflow_0002618006_pygtk_python.txt
|
Q:
Generating all possible subsets of a given QuerySet in Django
This is just an example, but given the following model:
class Foo(models.model):
bar = models.IntegerField()
def __str__(self):
return str(self.bar)
def __unicode__(self):
return str(self.bar)
And the following QuerySet object:
foobar = Foo.objects.filter(bar__lt=20).distinct()
(meaning, a set of unique Foo models with bar <= 20), how can I generate all possible subsets of foobar? Ideally, I'd like to further limit the subsets so that, for each subset x of foobar, the sum of all f.bar in x (where f is a model of type Foo) is between some maximum and minimum value.
So, for example, given the following instance of foobar:
>> print foobar
[<Foo: 5>, <Foo: 10>, <Foo: 15>]
And min=5, max=25, I'd like to build an object (preferably a QuerySet, but possibly a list) that looks like this:
[[<Foo: 5>], [<Foo: 10>], [<Foo: 15>], [<Foo: 5>, <Foo: 10>],
[<Foo: 5>, <Foo: 15>], [<Foo: 10>, <Foo: 15>]]
I've experimented with itertools but it doesn't seem particularly well-suited to my needs.
I think this could be accomplished with a complex QuerySet but I'm not sure how to start.
A:
S = [list(itertools.combinations(foobar,i)) for i in xrange(1, len(foobar))]
It produces non-flat list. You can flatten it by:
list(itertools.chain.from_iterable(S))
A:
This will give you the powerset of foobar (as a list)
from itertools import combinations
[j for i in range(len(foobar)+1) for j in combinations(foobar,i)]
Adding a filter for the minval and maxval gives:
from itertools import combinations
[j for i in range(len(foobar)+1) for j in combinations(foobar,i)
if minval <= sum(f.bar for f in j) <= maxval]
Lets create a class and try it out
>>> from itertools import combinations
>>> class Foo(object):
... def __init__(self, bar):
... self.bar=bar
... def __repr__(self):
... return "<Foo: %s>"%self.bar
...
>>> foobar=[Foo(5),Foo(10),Foo(15)]
>>> minval=5
>>> maxval=25
>>> [j for i in range(len(foobar)+1) for j in combinations(foobar,i)
if minval <= sum(f.bar for f in j) <= maxval]
[(<Foo: 5>,), (<Foo: 10>,), (<Foo: 15>,), (<Foo: 5>, <Foo: 10>), (<Foo: 5>, <Foo: 15>), (<Foo: 10>, <Foo: 15>)]
If you need lists rather than tuples it's trivial to add that in too
>>> [list(j) for i in range(len(foobar)+1) for j in combinations(foobar,i) if minval <= sum(f.bar for f in j) <= maxval ]
[[<Foo: 5>], [<Foo: 10>], [<Foo: 15>], [<Foo: 5>, <Foo: 10>], [<Foo: 5>, <Foo: 15>], [<Foo: 10>, <Foo: 15>]]
|
Generating all possible subsets of a given QuerySet in Django
|
This is just an example, but given the following model:
class Foo(models.model):
bar = models.IntegerField()
def __str__(self):
return str(self.bar)
def __unicode__(self):
return str(self.bar)
And the following QuerySet object:
foobar = Foo.objects.filter(bar__lt=20).distinct()
(meaning, a set of unique Foo models with bar <= 20), how can I generate all possible subsets of foobar? Ideally, I'd like to further limit the subsets so that, for each subset x of foobar, the sum of all f.bar in x (where f is a model of type Foo) is between some maximum and minimum value.
So, for example, given the following instance of foobar:
>> print foobar
[<Foo: 5>, <Foo: 10>, <Foo: 15>]
And min=5, max=25, I'd like to build an object (preferably a QuerySet, but possibly a list) that looks like this:
[[<Foo: 5>], [<Foo: 10>], [<Foo: 15>], [<Foo: 5>, <Foo: 10>],
[<Foo: 5>, <Foo: 15>], [<Foo: 10>, <Foo: 15>]]
I've experimented with itertools but it doesn't seem particularly well-suited to my needs.
I think this could be accomplished with a complex QuerySet but I'm not sure how to start.
|
[
"S = [list(itertools.combinations(foobar,i)) for i in xrange(1, len(foobar))]\n\nIt produces non-flat list. You can flatten it by:\nlist(itertools.chain.from_iterable(S))\n\n",
"This will give you the powerset of foobar (as a list)\nfrom itertools import combinations\n[j for i in range(len(foobar)+1) for j in combinations(foobar,i)]\n\nAdding a filter for the minval and maxval gives:\nfrom itertools import combinations\n[j for i in range(len(foobar)+1) for j in combinations(foobar,i)\n if minval <= sum(f.bar for f in j) <= maxval]\n\nLets create a class and try it out\n>>> from itertools import combinations\n>>> class Foo(object):\n... def __init__(self, bar):\n... self.bar=bar\n... def __repr__(self):\n... return \"<Foo: %s>\"%self.bar\n... \n>>> foobar=[Foo(5),Foo(10),Foo(15)]\n>>> minval=5\n>>> maxval=25\n>>> [j for i in range(len(foobar)+1) for j in combinations(foobar,i) \n if minval <= sum(f.bar for f in j) <= maxval]\n[(<Foo: 5>,), (<Foo: 10>,), (<Foo: 15>,), (<Foo: 5>, <Foo: 10>), (<Foo: 5>, <Foo: 15>), (<Foo: 10>, <Foo: 15>)]\n\nIf you need lists rather than tuples it's trivial to add that in too\n>>> [list(j) for i in range(len(foobar)+1) for j in combinations(foobar,i) if minval <= sum(f.bar for f in j) <= maxval ]\n[[<Foo: 5>], [<Foo: 10>], [<Foo: 15>], [<Foo: 5>, <Foo: 10>], [<Foo: 5>, <Foo: 15>], [<Foo: 10>, <Foo: 15>]]\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"django_queryset",
"python"
] |
stackoverflow_0002618641_django_django_queryset_python.txt
|
Q:
Does Python's shelve module use memory-mapped IO?
Does anyone know if Python's shelve module uses memory-mapped IO?
Maybe that question is a bit misleading. I realize that shelve uses an underlying dbm-style module to do its dirty work. What are the chances that the underlying module uses mmap?
I'm prototyping a datastore, and while I realize premature optimization is generally frowned upon, this could really help me understand the trade-offs involved in my design.
A:
Existing dbm implementations in the Python standard library all use "normal" I/O, not memory mapping. You'll need to code your own dbmish implementation with memory mapping, and integrate it with shelve (directly, or, more productively, through anydbm).
A:
I'm not sure what you're trying to learn by asking this question, since you already seem to know the answer: it depends on the actual dbm store being used. Some of them will use mmap -- I expect everything but dumbdbm to use mmap -- but so what? The overhead in shelve is almost certainly not in the mmap-versus-fileIO choice, but in the pickling operation. You can't mmap the dbm file sensibly yourself in either case, as the dbm module may have its own fancy locking (and it may not be a single file anyway, like when it uses bsddb.)
If you're just looking for inspiration for your own datastore, well, don't look at shelve, since all it does is pickle-and-pass-along to another datastore.
|
Does Python's shelve module use memory-mapped IO?
|
Does anyone know if Python's shelve module uses memory-mapped IO?
Maybe that question is a bit misleading. I realize that shelve uses an underlying dbm-style module to do its dirty work. What are the chances that the underlying module uses mmap?
I'm prototyping a datastore, and while I realize premature optimization is generally frowned upon, this could really help me understand the trade-offs involved in my design.
|
[
"Existing dbm implementations in the Python standard library all use \"normal\" I/O, not memory mapping. You'll need to code your own dbmish implementation with memory mapping, and integrate it with shelve (directly, or, more productively, through anydbm).\n",
"I'm not sure what you're trying to learn by asking this question, since you already seem to know the answer: it depends on the actual dbm store being used. Some of them will use mmap -- I expect everything but dumbdbm to use mmap -- but so what? The overhead in shelve is almost certainly not in the mmap-versus-fileIO choice, but in the pickling operation. You can't mmap the dbm file sensibly yourself in either case, as the dbm module may have its own fancy locking (and it may not be a single file anyway, like when it uses bsddb.)\nIf you're just looking for inspiration for your own datastore, well, don't look at shelve, since all it does is pickle-and-pass-along to another datastore.\n"
] |
[
4,
3
] |
[] |
[] |
[
"dbm",
"mmap",
"python",
"shelve"
] |
stackoverflow_0002618921_dbm_mmap_python_shelve.txt
|
Q:
Error when feeding a mysql db with a python-parsed data
I use this bit of code to feed some data i have parsed from a web page to a mysql database
c=db.cursor()
c.executemany(
"""INSERT INTO data (SID, Time, Value1, Level1, Value2, Level2, Value3, Level3, Value4, Level4, Value5, Level5, ObsDate)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
clean_data
)
The parsed data looks like this (there are several hundred such lines)
clean_data = [(161,00:00:00,8.19,1,4.46,4,7.87,4,6.54,null,4.45,6,2010-04-12),(162,00:00:00,7.55,1,9.52,1,1.90,1,4.76,null,0.14,1,2010-04-12),(164,00:00:00,8.01,1,8.09,1,0,null,8.49,null,0.20,2,2010-04-12),(166,00:00:00,8.30,1,4.77,4,10.99,5,9.11,null,0.36,2,2010-04-12)]
if i hard code the data as above mySQL accepts my request (except for some quibbles about formatting)
but if the variable clean_data is instead defined as the result of the parsing code, like this:
cleaner = [(""" $!!'""", ')]'),(' $!!', ') etc etc]
def processThis(str,lst):
for find, replace in lst:
str = str.replace(find, replace)
return str
clean_data = processThis(data,cleaner)
then i get the dreaded "TypeError: not enough arguments for format string"
After playing with formatting options for a few hours (I am very new to this) I am confused... what is the difference between the hard coded data and the result of the processThis function as fas as mySQL is concerned?
Any idea greatly appreciated...
A:
This is a guess...
processThis returns a string. It doesn't return a list of tuples.
What happens if you try repr(clean_data)? I think you will get something like the following:
"[(161,00:00:00,8.19,1,4.46,4,7.87,4,6.54,null,4.45,6,2010-04-12)]"
That is a single string. So you are passing in a single string parameter to the query, rather than 13 values.
Your data parsing will need to be improved. You'll want to split the string and convert values into integers, floats, etc.
A:
Here is a stab at parsing your string into separate values:
import datetime
import time
src = "161,00:00:00,8.19,1,4.46,4,7.87,4,6.54,null,4.45,6,2010-04-12"
asFloat = lambda x : float(x)
asInt = lambda x : int(x)
asTime = lambda x : datetime.datetime(*time.strptime(x,'%H:%M:%S')[:7]).time()
asDate = lambda x : datetime.datetime(*time.strptime(x,'%Y-%m-%d')[:3]).date()
asNone = lambda x : None if x=='null' else int('ValueError')
converters = (asDate,asTime,asInt,asFloat,asNone,)
def convert(x):
for cnv in converters:
try:
return cnv(x)
except ValueError:
pass
return x
clean_data = [convert(s) for s in src.split(',')]
print clean_data
Gives:
[161, datetime.time(0, 0), 8.1899999999999995, 1, 4.46, 4,
7.8700000000000001, 4, 6.54, None, 4.4500000000000002, 6,
datetime.date(2010, 4, 12)]
which should give a proper list for each row to pass to executemany.
-- Paul
|
Error when feeding a mysql db with a python-parsed data
|
I use this bit of code to feed some data i have parsed from a web page to a mysql database
c=db.cursor()
c.executemany(
"""INSERT INTO data (SID, Time, Value1, Level1, Value2, Level2, Value3, Level3, Value4, Level4, Value5, Level5, ObsDate)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
clean_data
)
The parsed data looks like this (there are several hundred such lines)
clean_data = [(161,00:00:00,8.19,1,4.46,4,7.87,4,6.54,null,4.45,6,2010-04-12),(162,00:00:00,7.55,1,9.52,1,1.90,1,4.76,null,0.14,1,2010-04-12),(164,00:00:00,8.01,1,8.09,1,0,null,8.49,null,0.20,2,2010-04-12),(166,00:00:00,8.30,1,4.77,4,10.99,5,9.11,null,0.36,2,2010-04-12)]
if i hard code the data as above mySQL accepts my request (except for some quibbles about formatting)
but if the variable clean_data is instead defined as the result of the parsing code, like this:
cleaner = [(""" $!!'""", ')]'),(' $!!', ') etc etc]
def processThis(str,lst):
for find, replace in lst:
str = str.replace(find, replace)
return str
clean_data = processThis(data,cleaner)
then i get the dreaded "TypeError: not enough arguments for format string"
After playing with formatting options for a few hours (I am very new to this) I am confused... what is the difference between the hard coded data and the result of the processThis function as fas as mySQL is concerned?
Any idea greatly appreciated...
|
[
"This is a guess...\nprocessThis returns a string. It doesn't return a list of tuples.\nWhat happens if you try repr(clean_data)? I think you will get something like the following:\n\"[(161,00:00:00,8.19,1,4.46,4,7.87,4,6.54,null,4.45,6,2010-04-12)]\"\n\nThat is a single string. So you are passing in a single string parameter to the query, rather than 13 values.\nYour data parsing will need to be improved. You'll want to split the string and convert values into integers, floats, etc.\n",
"Here is a stab at parsing your string into separate values:\nimport datetime\nimport time\nsrc = \"161,00:00:00,8.19,1,4.46,4,7.87,4,6.54,null,4.45,6,2010-04-12\"\nasFloat = lambda x : float(x)\nasInt = lambda x : int(x)\nasTime = lambda x : datetime.datetime(*time.strptime(x,'%H:%M:%S')[:7]).time()\nasDate = lambda x : datetime.datetime(*time.strptime(x,'%Y-%m-%d')[:3]).date()\nasNone = lambda x : None if x=='null' else int('ValueError')\nconverters = (asDate,asTime,asInt,asFloat,asNone,)\ndef convert(x):\n for cnv in converters:\n try:\n return cnv(x)\n except ValueError:\n pass\n return x\n\nclean_data = [convert(s) for s in src.split(',')]\nprint clean_data\n\nGives:\n[161, datetime.time(0, 0), 8.1899999999999995, 1, 4.46, 4, \n 7.8700000000000001, 4, 6.54, None, 4.4500000000000002, 6, \n datetime.date(2010, 4, 12)]\n\nwhich should give a proper list for each row to pass to executemany.\n-- Paul\n"
] |
[
1,
0
] |
[] |
[] |
[
"mysql",
"parsing",
"python"
] |
stackoverflow_0002618030_mysql_parsing_python.txt
|
Q:
Safest python code running
How can I protect my web server, if I run custom users code on server. If any user can submit his python source on my server and run it.
Maybe some modules or linux tools for close any network and hardware activity for this script.
Thank's all for help!
A:
The concept you're thinking of is sandboxing. Check out the Python wiki page about it:
http://wiki.python.org/moin/SandboxedPython
A:
In general, python is not the best language choice if you want to allow the execution of untrusted code. The JVM and .NET have much better support for sandboxing, so Jython and IronPython would be better choices.
|
Safest python code running
|
How can I protect my web server, if I run custom users code on server. If any user can submit his python source on my server and run it.
Maybe some modules or linux tools for close any network and hardware activity for this script.
Thank's all for help!
|
[
"The concept you're thinking of is sandboxing. Check out the Python wiki page about it:\nhttp://wiki.python.org/moin/SandboxedPython\n",
"In general, python is not the best language choice if you want to allow the execution of untrusted code. The JVM and .NET have much better support for sandboxing, so Jython and IronPython would be better choices.\n"
] |
[
9,
0
] |
[] |
[] |
[
"python",
"system"
] |
stackoverflow_0002618862_python_system.txt
|
Q:
socket server framework like Tcl "socket -server"
I'm looking to reimplement some Tcl code that uses the socket -server construct [1].
What's the best option in Python for a small, industrial strength multi-user network-based server that includes event loop processing/integration?
[1] http://www.tcl.tk/man/tcl8.4/TclCmd/socket.htm
A:
Sounds like Python's socketserver module.
There are more advanced frameworks too, asyncore is included in the stdlib and twisted is a huge networking framework.
|
socket server framework like Tcl "socket -server"
|
I'm looking to reimplement some Tcl code that uses the socket -server construct [1].
What's the best option in Python for a small, industrial strength multi-user network-based server that includes event loop processing/integration?
[1] http://www.tcl.tk/man/tcl8.4/TclCmd/socket.htm
|
[
"Sounds like Python's socketserver module. \nThere are more advanced frameworks too, asyncore is included in the stdlib and twisted is a huge networking framework.\n"
] |
[
2
] |
[] |
[] |
[
"event_loop",
"python",
"socketserver"
] |
stackoverflow_0002619192_event_loop_python_socketserver.txt
|
Q:
Difference between cellPressed and cellClicked signals of PyQt4 QTableWidget
The PyQt4 QTableWidget has both cellPressed and cellClicked signals. From the name, and the little experimentation I did with them, they appear to do exactly the same thing. Is there a difference between the two?
A:
These signals on cells are not sharply documented (that I can find) but I'd interpret them by analogy with the pressed, clicked, and released signals on buttons:
pressed means the mouse's left button's been pressed down inside the widget,
released means the mouse's left button's been released (let up) inside the widget,
clicked means the mouse's left button's been pressed, then released (let up), both inside the widget
So if you press the button down inside the widget, hold it down, move the mouse elsewhere, and only then release the mouse's button, then you should only see the pressed signal, but neither of the other two; while any clicked signal always implies both pressed and released have also been signaled.
I believe that normal UI behavior should be to respond to clicked only, unless you want to do something special if the button's pressed and not released for a certain time (i.e., held down for a prolonged time).
|
Difference between cellPressed and cellClicked signals of PyQt4 QTableWidget
|
The PyQt4 QTableWidget has both cellPressed and cellClicked signals. From the name, and the little experimentation I did with them, they appear to do exactly the same thing. Is there a difference between the two?
|
[
"These signals on cells are not sharply documented (that I can find) but I'd interpret them by analogy with the pressed, clicked, and released signals on buttons:\npressed means the mouse's left button's been pressed down inside the widget,\nreleased means the mouse's left button's been released (let up) inside the widget,\nclicked means the mouse's left button's been pressed, then released (let up), both inside the widget\nSo if you press the button down inside the widget, hold it down, move the mouse elsewhere, and only then release the mouse's button, then you should only see the pressed signal, but neither of the other two; while any clicked signal always implies both pressed and released have also been signaled.\nI believe that normal UI behavior should be to respond to clicked only, unless you want to do something special if the button's pressed and not released for a certain time (i.e., held down for a prolonged time).\n"
] |
[
3
] |
[] |
[] |
[
"pyqt4",
"python"
] |
stackoverflow_0002619446_pyqt4_python.txt
|
Q:
Getting last insert id with SQLAlchemy
I'm using SQLAlchemy
import hashlib
import sqlalchemy as sa
from sqlalchemy import orm
from allsun.model import meta
t_user = sa.Table("users",meta.metadata,autoload=True)
class Duplicat(Exception):
pass
class LoginExistsException(Exception):
pass
class EmailExistsException(Exception):
pass
class User(object):
"""
def __setattr__(self, key, value):
if key=='password' :
value=unicode(hashlib.sha512(value).hexdigset())
object.__setattr__(self,key,value)
"""
def loginExists(self):
try:
meta.Session.query(User).filter(User.login==self.login).one()
except orm.exc.NoResultFound:
pass
else:
raise LoginExistsException()
def emailExists(self):
try:
meta.Session.query(User).filter(User.email==self.email).one()
except orm.exc.NoResultFound:
pass
else:
raise EmailExistsException()
def save(self):
meta.Session.begin()
meta.Session.save(self)
try:
meta.Session.commit()
except sa.exc.IntegrityError:
raise Duplicat()
How can I get the last inserted id when I call:
user = User()
user.login = request.params['login']
user.password = hashlib.sha512(request.params['password']).hexdigest()
user.email = request.params['email']
user.save()
A:
You can access user.id (or whatever name you use for autoincremeted primary key field) after saving user object. SQLAlchemy automatically fills fields assigned by database.
|
Getting last insert id with SQLAlchemy
|
I'm using SQLAlchemy
import hashlib
import sqlalchemy as sa
from sqlalchemy import orm
from allsun.model import meta
t_user = sa.Table("users",meta.metadata,autoload=True)
class Duplicat(Exception):
pass
class LoginExistsException(Exception):
pass
class EmailExistsException(Exception):
pass
class User(object):
"""
def __setattr__(self, key, value):
if key=='password' :
value=unicode(hashlib.sha512(value).hexdigset())
object.__setattr__(self,key,value)
"""
def loginExists(self):
try:
meta.Session.query(User).filter(User.login==self.login).one()
except orm.exc.NoResultFound:
pass
else:
raise LoginExistsException()
def emailExists(self):
try:
meta.Session.query(User).filter(User.email==self.email).one()
except orm.exc.NoResultFound:
pass
else:
raise EmailExistsException()
def save(self):
meta.Session.begin()
meta.Session.save(self)
try:
meta.Session.commit()
except sa.exc.IntegrityError:
raise Duplicat()
How can I get the last inserted id when I call:
user = User()
user.login = request.params['login']
user.password = hashlib.sha512(request.params['password']).hexdigest()
user.email = request.params['email']
user.save()
|
[
"You can access user.id (or whatever name you use for autoincremeted primary key field) after saving user object. SQLAlchemy automatically fills fields assigned by database.\n"
] |
[
21
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002618714_python_sqlalchemy.txt
|
Q:
Finding inline style with lxml.cssselector
New to this library (no more familiar with BeautifulSoup either, sadly), trying to do something very simple (search by inline style):
<td style="padding: 20px">blah blah </td>
I just want to select all tds where style="padding: 20px", but I can't seem to figure it out. All the examples show how to select td, such as:
for col in page.cssselect('td'):
but that doesn't help me much.
A:
Well, there's a better way: XPath.
import lxml.html
data = """<td style="padding: 20px">blah blah </td>
<td style="padding: 21px">bow bow</td>
<td style="padding: 20px">buh buh</td>
"""
doc = lxml.html.document_fromstring(data)
for col in doc.xpath("//td[@style='padding: 20px']"):
print col.text
That is neater and also faster.
A:
If you prefer to use CSS selectors:
import lxml.html
data = """<td style="padding: 20px">blah blah </td>
<td style="padding: 21px">bow bow</td>
<td style="padding: 20px">buh buh</td>
"""
doc = lxml.html.document_fromstring(data)
for td in doc.cssselect('td[style="padding: 20px"]'):
print td.text
A:
Note that both Ruslan Spivak and nosklo have given better answers below.
import lxml.html
data = """<td style="padding: 20px">blah blah </td>
<td style="padding: 21px">bow bow</td>
<td style="padding: 20px">buh buh</td>
"""
doc = lxml.html.document_fromstring(data)
for col in doc.cssselect('td'):
style = col.attrib['style']
if style=='padding: 20px':
print(col.text.strip())
prints
blah blah
buh buh
and manages to skip bow bow.
|
Finding inline style with lxml.cssselector
|
New to this library (no more familiar with BeautifulSoup either, sadly), trying to do something very simple (search by inline style):
<td style="padding: 20px">blah blah </td>
I just want to select all tds where style="padding: 20px", but I can't seem to figure it out. All the examples show how to select td, such as:
for col in page.cssselect('td'):
but that doesn't help me much.
|
[
"Well, there's a better way: XPath.\nimport lxml.html\ndata = \"\"\"<td style=\"padding: 20px\">blah blah </td>\n<td style=\"padding: 21px\">bow bow</td>\n<td style=\"padding: 20px\">buh buh</td>\n\"\"\"\ndoc = lxml.html.document_fromstring(data)\nfor col in doc.xpath(\"//td[@style='padding: 20px']\"):\n print col.text\n\nThat is neater and also faster.\n",
"If you prefer to use CSS selectors:\nimport lxml.html\ndata = \"\"\"<td style=\"padding: 20px\">blah blah </td>\n<td style=\"padding: 21px\">bow bow</td>\n<td style=\"padding: 20px\">buh buh</td>\n\"\"\"\ndoc = lxml.html.document_fromstring(data)\nfor td in doc.cssselect('td[style=\"padding: 20px\"]'):\n print td.text\n\n",
"Note that both Ruslan Spivak and nosklo have given better answers below.\n\nimport lxml.html\ndata = \"\"\"<td style=\"padding: 20px\">blah blah </td>\n<td style=\"padding: 21px\">bow bow</td>\n<td style=\"padding: 20px\">buh buh</td>\n\"\"\"\ndoc = lxml.html.document_fromstring(data)\nfor col in doc.cssselect('td'):\n style = col.attrib['style']\n if style=='padding: 20px':\n print(col.text.strip())\n\nprints\nblah blah\nbuh buh\n\nand manages to skip bow bow.\n"
] |
[
4,
3,
2
] |
[] |
[] |
[
"lxml",
"python"
] |
stackoverflow_0002619536_lxml_python.txt
|
Q:
how python http request and response works
I'm newbie for python, I'm having task so I need to scan wifi and send the data to the server, the below is the format which i have to send, this work fine when enter manually in browser url text box,
http://223.56.124.58:8080/ppod-web/ProcessRawData?data={"userId":"2220081127-14","timestamp":"2010-04-12 10:54:24","wifi":{"ssid":"guest","rssi":"80"}}
here is my code:
import httplib
import urllib
params = urllib.urlencode('{\"userId\":\"20081127-14\",\"timestamp\":\"2010-04-12 10:54:24\",\"wifi\":{\"ssid\":\"guest\",\"rssi\":\"80\"}}')
headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
conn = httplib.HTTPConnection("http://223.56.124.58:8080")
conn.request("POST","ppod-web/ProcessRawData?data=",params,headers)
response = conn.getresponse()
print response.status
print "-----"
print response.reason
data = response.read()
print data
conn.close()
thanks
A:
Most likely, the issue with the script you posted in the question is you cannot directly do:
conn=httplib.HTTPConnection("http://223.56.124.58:8080/wireless")
The exception is triggered in getaddrinfo(), which calls the C function getaddrinfo() which returns EAI_NONAME:
The node or service is not known; or both node and service are NULL; or AI_NUMERICSERV was specified in hints.ai_flags and service was not a numeric port-number string."
There obviously is a problem with the parameters passed to getaddrinfo, and most likely you are trying to get information for the "223.56.124.58:8080/wireless" host. Ooops!
Indeed, you cannot directly connect to an URL address. As the documentation clearly states and shows, you connect to the server:
conn = httplib.HTTPConnection("223.56.124.58", 8080)
Then you can do:
conn.request("POST", "wireless", params, headers)
What about the script you are actually using?
conn.request("POST","http://202.45.139.58:8080/ppod-web",params,headers)
Even if the connection was correctly formed, that would have you POSTing to http://202.45.139.58:8080/http://202.45.139.58:8080/ppod-web. What you really want probably is:
conn = httplib.HTTPConnection("202.45.139.58", 8080)
conn.request("POST", "ppod-web", params, headers)
The error is shown for this line because most likely HTTPConnection is a lazy object and only attempts to actually connect to the server when you call request().
After you're done fixing the above, you'll need to fix params.
>>> urllib.urlencode({"wifi":{"ssid":"guest","rssi","80"}})
SyntaxError: invalid syntax
>>> urllib.urlencode({"wifi":{"ssid":"guest","rssi":"80"}})
'wifi=%7B%27rssi%27%3A+%2780%27%2C+%27ssid%27%3A+%27guest%27%7D'
To get what you think you want to get, you should do:
>>> urllib.urlencode({"data": {"wifi":{"ssid":"guest","rssi":"80"}}})
'data=%7B%27wifi%27%3A+%7B%27rssi%27%3A+%2780%27%2C+%27ssid%27%3A+%27guest%27%7D%7D'
A:
Instead of:
conn = httplib.HTTPConnection("http://223.56.124.58:8080/wireless")
conn.request("POST", "data", params, headers)
try:
conn = httplib.HTTPConnection("223.56.124.58", port=8080)
conn.request("POST", "/wireless", params, headers)
Not sure if it will resolve all your problems, but at least your code will conform to the method/constructor signatures.
A:
The traceback doesn't come from the same code you pasted.
On the error traceback there's a line:
conn.request("POST","http://202.45.139.58:8080/ppod-web",params,headers)
It is the line 9 of http.py however it is not on the code you pasted.
Please paste the actual code.
|
how python http request and response works
|
I'm newbie for python, I'm having task so I need to scan wifi and send the data to the server, the below is the format which i have to send, this work fine when enter manually in browser url text box,
http://223.56.124.58:8080/ppod-web/ProcessRawData?data={"userId":"2220081127-14","timestamp":"2010-04-12 10:54:24","wifi":{"ssid":"guest","rssi":"80"}}
here is my code:
import httplib
import urllib
params = urllib.urlencode('{\"userId\":\"20081127-14\",\"timestamp\":\"2010-04-12 10:54:24\",\"wifi\":{\"ssid\":\"guest\",\"rssi\":\"80\"}}')
headers = {"Content-type":"application/x-www-form-urlencoded","Accept":"text/plain"}
conn = httplib.HTTPConnection("http://223.56.124.58:8080")
conn.request("POST","ppod-web/ProcessRawData?data=",params,headers)
response = conn.getresponse()
print response.status
print "-----"
print response.reason
data = response.read()
print data
conn.close()
thanks
|
[
"Most likely, the issue with the script you posted in the question is you cannot directly do:\nconn=httplib.HTTPConnection(\"http://223.56.124.58:8080/wireless\") \n\nThe exception is triggered in getaddrinfo(), which calls the C function getaddrinfo() which returns EAI_NONAME:\n\nThe node or service is not known; or both node and service are NULL; or AI_NUMERICSERV was specified in hints.ai_flags and service was not a numeric port-number string.\"\n\nThere obviously is a problem with the parameters passed to getaddrinfo, and most likely you are trying to get information for the \"223.56.124.58:8080/wireless\" host. Ooops!\nIndeed, you cannot directly connect to an URL address. As the documentation clearly states and shows, you connect to the server:\nconn = httplib.HTTPConnection(\"223.56.124.58\", 8080)\n\nThen you can do:\nconn.request(\"POST\", \"wireless\", params, headers)\n\n\nWhat about the script you are actually using?\nconn.request(\"POST\",\"http://202.45.139.58:8080/ppod-web\",params,headers)\n\nEven if the connection was correctly formed, that would have you POSTing to http://202.45.139.58:8080/http://202.45.139.58:8080/ppod-web. What you really want probably is:\nconn = httplib.HTTPConnection(\"202.45.139.58\", 8080)\nconn.request(\"POST\", \"ppod-web\", params, headers)\n\nThe error is shown for this line because most likely HTTPConnection is a lazy object and only attempts to actually connect to the server when you call request().\n\nAfter you're done fixing the above, you'll need to fix params.\n>>> urllib.urlencode({\"wifi\":{\"ssid\":\"guest\",\"rssi\",\"80\"}})\nSyntaxError: invalid syntax\n>>> urllib.urlencode({\"wifi\":{\"ssid\":\"guest\",\"rssi\":\"80\"}})\n'wifi=%7B%27rssi%27%3A+%2780%27%2C+%27ssid%27%3A+%27guest%27%7D'\n\nTo get what you think you want to get, you should do:\n>>> urllib.urlencode({\"data\": {\"wifi\":{\"ssid\":\"guest\",\"rssi\":\"80\"}}})\n'data=%7B%27wifi%27%3A+%7B%27rssi%27%3A+%2780%27%2C+%27ssid%27%3A+%27guest%27%7D%7D'\n\n",
"Instead of:\nconn = httplib.HTTPConnection(\"http://223.56.124.58:8080/wireless\")\nconn.request(\"POST\", \"data\", params, headers) \n\ntry:\nconn = httplib.HTTPConnection(\"223.56.124.58\", port=8080)\nconn.request(\"POST\", \"/wireless\", params, headers)\n\nNot sure if it will resolve all your problems, but at least your code will conform to the method/constructor signatures.\n",
"The traceback doesn't come from the same code you pasted.\nOn the error traceback there's a line:\nconn.request(\"POST\",\"http://202.45.139.58:8080/ppod-web\",params,headers)\n\nIt is the line 9 of http.py however it is not on the code you pasted.\nPlease paste the actual code.\n"
] |
[
10,
1,
0
] |
[] |
[] |
[
"http",
"python"
] |
stackoverflow_0002620228_http_python.txt
|
Q:
unit test for proxy checking
Proxy configuration of a machine can be easily fetched using
def check_proxy():
import urllib2
http_proxy = urllib2.getproxies().get('http')
I need to write a test for the above written function. In order to do that I need to:-
Set the system-wide proxy to an
invalid URL during the test(sounds
like a bad idea).
Supply an invalid
URL to http_proxy.
How can I achieve either of the above?
A:
Looking at the question tags I see you want to write unit-tests for the function. And where is your unit here? Where is your business logic? getproxies and get are functions of the standard Python library. You shouldn't test others' code in your unit-tests. Furthermore it enough to test only Things That Could Possibly Break.
If I've misunderstood your question and indeed your function looks like this:
def check_proxy():
import urllib
http_proxy = urllib.getproxies().get('http')
# some “complex” code that uses http_proxy
and you don't know how to test the “complex” code due to dependency on proxy, I recommend to split the function in two:
def check_proxy():
import urllib
http_proxy = urllib.getproxies().get('http')
_check_proxy(http_proxy)
def _check_proxy(http_proxy):
# some “complex” code that uses http_proxy
Now you're able to test _check_proxy alone, using any mock/stub you specially prepared for the role of http_proxy. Write few tests for _check_proxy and leave original check_proxy untested (in sense of unit-tests). It is OK.
A:
The exact behaviour of getproxies varies according the the system you're on, but I believe that in all cases it looks first in the environment then checks the system specific place for proxy settings (such as the registry on windows).
So try:
os.environ['HTTP_PROXY'] = 'whatever invalid URL you want'
|
unit test for proxy checking
|
Proxy configuration of a machine can be easily fetched using
def check_proxy():
import urllib2
http_proxy = urllib2.getproxies().get('http')
I need to write a test for the above written function. In order to do that I need to:-
Set the system-wide proxy to an
invalid URL during the test(sounds
like a bad idea).
Supply an invalid
URL to http_proxy.
How can I achieve either of the above?
|
[
"Looking at the question tags I see you want to write unit-tests for the function. And where is your unit here? Where is your business logic? getproxies and get are functions of the standard Python library. You shouldn't test others' code in your unit-tests. Furthermore it enough to test only Things That Could Possibly Break.\nIf I've misunderstood your question and indeed your function looks like this:\ndef check_proxy(): \n import urllib\n http_proxy = urllib.getproxies().get('http')\n # some “complex” code that uses http_proxy\n\nand you don't know how to test the “complex” code due to dependency on proxy, I recommend to split the function in two:\ndef check_proxy(): \n import urllib\n http_proxy = urllib.getproxies().get('http')\n _check_proxy(http_proxy)\n\ndef _check_proxy(http_proxy):\n # some “complex” code that uses http_proxy\n\nNow you're able to test _check_proxy alone, using any mock/stub you specially prepared for the role of http_proxy. Write few tests for _check_proxy and leave original check_proxy untested (in sense of unit-tests). It is OK.\n",
"The exact behaviour of getproxies varies according the the system you're on, but I believe that in all cases it looks first in the environment then checks the system specific place for proxy settings (such as the registry on windows).\nSo try:\nos.environ['HTTP_PROXY'] = 'whatever invalid URL you want'\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"proxy",
"python",
"unit_testing"
] |
stackoverflow_0002616999_proxy_python_unit_testing.txt
|
Q:
pb with callback in the python optparse module
I'm playing with Python 2.6 and its optparse module. I would like to convert one of my arguments to a datetime through a callback but it fails.
Here is the code:
def parsedate(option, opt_str, value, parser):
option.date = datetime.strptime(value, "%Y/%m/%d")
def parse_options(args):
parser = OptionParser(usage="%prog -l LOGFOLDER [-e]", version="%prog 1.0")
parser.add_option("-d", "--date", action="callback", callback="parsedate", dest="date")
global options
(options, args) = parser.parse_args(args)
print options.date.strftime()
if __name__ == "__main__":
parse_options(sys.argv[1:])
I get an error File: optparse.py in _check_callback "callback not callable". I guess I'm doing something wrong in the way I define my callback but what ? and why ? Can anyone help ?
UPDATE: As I said in my comment, I think the best way to have a datetime in the options of a command line script is by extending optparse as suggested in the python doc
the following class really works fine for that:
from copy import copy
from optparse import Option, OptionValueError
from datetime import datetime
def check_date(option, opt, value):
try:
return datetime.strptime(value, "%Y/%m/%d")
except ValueError:
raise OptionValueError(
"option %s: invalid date value: %r. Should have a format like \"YYYY/MM/DD\"" % (opt, value))
class dateOption (Option):
TYPES = Option.TYPES + ("date",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["date"] = check_date
Anyway, many thanks for the help!
A:
You have parsedate in quotes. It should not be.
|
pb with callback in the python optparse module
|
I'm playing with Python 2.6 and its optparse module. I would like to convert one of my arguments to a datetime through a callback but it fails.
Here is the code:
def parsedate(option, opt_str, value, parser):
option.date = datetime.strptime(value, "%Y/%m/%d")
def parse_options(args):
parser = OptionParser(usage="%prog -l LOGFOLDER [-e]", version="%prog 1.0")
parser.add_option("-d", "--date", action="callback", callback="parsedate", dest="date")
global options
(options, args) = parser.parse_args(args)
print options.date.strftime()
if __name__ == "__main__":
parse_options(sys.argv[1:])
I get an error File: optparse.py in _check_callback "callback not callable". I guess I'm doing something wrong in the way I define my callback but what ? and why ? Can anyone help ?
UPDATE: As I said in my comment, I think the best way to have a datetime in the options of a command line script is by extending optparse as suggested in the python doc
the following class really works fine for that:
from copy import copy
from optparse import Option, OptionValueError
from datetime import datetime
def check_date(option, opt, value):
try:
return datetime.strptime(value, "%Y/%m/%d")
except ValueError:
raise OptionValueError(
"option %s: invalid date value: %r. Should have a format like \"YYYY/MM/DD\"" % (opt, value))
class dateOption (Option):
TYPES = Option.TYPES + ("date",)
TYPE_CHECKER = copy(Option.TYPE_CHECKER)
TYPE_CHECKER["date"] = check_date
Anyway, many thanks for the help!
|
[
"You have parsedate in quotes. It should not be.\n"
] |
[
3
] |
[] |
[] |
[
"callback",
"optparse",
"python"
] |
stackoverflow_0002620637_callback_optparse_python.txt
|
Q:
Django 1.1 equivalent of the 'in' operator
I need to display a piece of HTML only if a variable value appears in a list. I know that Django 1.2 has an 'in' operator. But I am working on a Google App Engine app. Is there a workaround I can use?
A:
You can use your own template tag to achieve it or put it in your controller's logic.
Have a look at this snippet: http://www.djangosnippets.org/snippets/302/
A:
If what you need to know is whether you should render a piece of HTML, and you are going to reuse this rule in other templates, you may try to use django.template.RequestContext and make it an accessable status variable in templates in need.
def context(request):
return {'render_a_panel' : request.user.username in ('Jim', 'Tom')}
Of course, this only works if your rule is based on request.
|
Django 1.1 equivalent of the 'in' operator
|
I need to display a piece of HTML only if a variable value appears in a list. I know that Django 1.2 has an 'in' operator. But I am working on a Google App Engine app. Is there a workaround I can use?
|
[
"You can use your own template tag to achieve it or put it in your controller's logic. \nHave a look at this snippet: http://www.djangosnippets.org/snippets/302/\n",
"If what you need to know is whether you should render a piece of HTML, and you are going to reuse this rule in other templates, you may try to use django.template.RequestContext and make it an accessable status variable in templates in need.\ndef context(request):\n return {'render_a_panel' : request.user.username in ('Jim', 'Tom')}\n\nOf course, this only works if your rule is based on request.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0002620967_django_django_templates_python.txt
|
Q:
Convert a python numpy array to c++ stl vector
I'm looking for a way to read in c++ a text file containing numpy arrays and put the data into vector< vector< ... > > , can anyone help me out please ?
Thanks a lot.
Archy
EDIT: format of the text file
[[[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9]] [[10 11] [12 13] [14 15] [16 17] [18 19]] [[20 21] [22 23] [24 25] [26 27] [28 29]] [[30 31] [32 33] [34 35] [36 37] [38 39]]]
Perhaps more readably:
[
[
[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9]
]
[
[10 11] [12 13] [14 15] [16 17] [18 19]
]
[
[20 21] [22 23] [24 25] [26 27] [28 29]
]
[
[30 31] [32 33] [34 35] [36 37] [38 39]
]
]
A:
float val;
::std::vector<float> vals;
ifstream stream("c:/file.txt");
while(stream >> val) {
vals.push_back(val);
}
A:
It's going to depend on your level of expertise.
If you are experienced, I would suggest something like Boost.Spirit.Qi, which is a true parser library. However it might take some time to get used to.
Otherwise it depends on what information you have at your disposal... I'll edit my answer when you provide us with more details since it's hairy enough to potentially get quite complicated :)
|
Convert a python numpy array to c++ stl vector
|
I'm looking for a way to read in c++ a text file containing numpy arrays and put the data into vector< vector< ... > > , can anyone help me out please ?
Thanks a lot.
Archy
EDIT: format of the text file
[[[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9]] [[10 11] [12 13] [14 15] [16 17] [18 19]] [[20 21] [22 23] [24 25] [26 27] [28 29]] [[30 31] [32 33] [34 35] [36 37] [38 39]]]
Perhaps more readably:
[
[
[ 0 1] [ 2 3] [ 4 5] [ 6 7] [ 8 9]
]
[
[10 11] [12 13] [14 15] [16 17] [18 19]
]
[
[20 21] [22 23] [24 25] [26 27] [28 29]
]
[
[30 31] [32 33] [34 35] [36 37] [38 39]
]
]
|
[
"float val;\n::std::vector<float> vals;\nifstream stream(\"c:/file.txt\");\nwhile(stream >> val) {\n vals.push_back(val);\n}\n\n",
"It's going to depend on your level of expertise.\nIf you are experienced, I would suggest something like Boost.Spirit.Qi, which is a true parser library. However it might take some time to get used to.\nOtherwise it depends on what information you have at your disposal... I'll edit my answer when you provide us with more details since it's hairy enough to potentially get quite complicated :)\n"
] |
[
0,
0
] |
[] |
[] |
[
"arrays",
"c++",
"numpy",
"python",
"vector"
] |
stackoverflow_0002620722_arrays_c++_numpy_python_vector.txt
|
Q:
SQLAlchemy: who is in charge of the "session"? ( and how to unit-test with sessions )
I need some guidance on how to use session objects with SQLAlchemy, and how to organize Unit Tests of my mapped objects.
What I would like to able to do is something like this:
thing = BigThing() # mapped object
child = thing.new_child() # create and return a related object
thing.save() # will also save the child object
In order to achieve this, I was thinking of having the BigThing actually add itself ( and it's children ) to the database -- but maybe this not a good idea?
One reason to add objects as soon as possible is Automatic id values that are assigned by the database -- the sooner they are available, the fewer problems there are ( right? )
What is the best way to manage session objects?
Who is in charge of the session?
Should it be created only when required? or saved for a long time?
What about Unit Tests for my mapped objects?...how should the session be handled?
Is it ever OK to have mapped objects just automatically add themselves to a database? or is that going to lead to trouble?
A:
Session is like a box where you store objects. Sure you can write __init__ method to automatically add object to it, but this implies that it's there is some global (the only) session. Sure this will cause problems in a lot of cases, but also this will simplify writing code a bit. It's explicit vs. implicit dilemma. Some people follow Zen of Python, and some don't. I prefer to specify a box to store explicitly.
Note, that there is no need to add children to session explicitly as far as it is associated with object already in session via relation. That's what cascading rules are for. The default 'save-update' does exactly what you request. You might be also interested in 'all, delete-orphan' to implement "private" objects, which should be deleted along with their parent.
I see some problems to implement save() method. There is no way to say "save this objects" in SQLAlchemy in current version. There was such ability earlier, but it was never reliable. Session.flush() (it's called from Session.commit()) flushes all changes to the database. This is probably the most annoying feature of SQLAlchemy that prevents me from using it in certain projects.
Unit testing is very easy (at least when you specify session explicitly), see the sample code in other question.
|
SQLAlchemy: who is in charge of the "session"? ( and how to unit-test with sessions )
|
I need some guidance on how to use session objects with SQLAlchemy, and how to organize Unit Tests of my mapped objects.
What I would like to able to do is something like this:
thing = BigThing() # mapped object
child = thing.new_child() # create and return a related object
thing.save() # will also save the child object
In order to achieve this, I was thinking of having the BigThing actually add itself ( and it's children ) to the database -- but maybe this not a good idea?
One reason to add objects as soon as possible is Automatic id values that are assigned by the database -- the sooner they are available, the fewer problems there are ( right? )
What is the best way to manage session objects?
Who is in charge of the session?
Should it be created only when required? or saved for a long time?
What about Unit Tests for my mapped objects?...how should the session be handled?
Is it ever OK to have mapped objects just automatically add themselves to a database? or is that going to lead to trouble?
|
[
"Session is like a box where you store objects. Sure you can write __init__ method to automatically add object to it, but this implies that it's there is some global (the only) session. Sure this will cause problems in a lot of cases, but also this will simplify writing code a bit. It's explicit vs. implicit dilemma. Some people follow Zen of Python, and some don't. I prefer to specify a box to store explicitly.\nNote, that there is no need to add children to session explicitly as far as it is associated with object already in session via relation. That's what cascading rules are for. The default 'save-update' does exactly what you request. You might be also interested in 'all, delete-orphan' to implement \"private\" objects, which should be deleted along with their parent.\nI see some problems to implement save() method. There is no way to say \"save this objects\" in SQLAlchemy in current version. There was such ability earlier, but it was never reliable. Session.flush() (it's called from Session.commit()) flushes all changes to the database. This is probably the most annoying feature of SQLAlchemy that prevents me from using it in certain projects.\nUnit testing is very easy (at least when you specify session explicitly), see the sample code in other question.\n"
] |
[
2
] |
[] |
[] |
[
"orm",
"python",
"session",
"sqlalchemy",
"unit_testing"
] |
stackoverflow_0002611517_orm_python_session_sqlalchemy_unit_testing.txt
|
Q:
random() in python
In python the function random() generates a random float uniformly in the semi-open range [0.0, 1.0). In principle can it ever generate 0.0 (i.e. zero) and 1.0 (i.e. unity)? What is the scenario in practicality?
A:
0.0 can be generated; 1.0 cannot (since it isn't within the range, hence the ) as opposed to [).
The probability of generating 0.0 is equal to the probability of generating any other number within that range, namely, 1/X where X is the number of different possible results. For a standard unsigned double-precision floating point, this usually means 53 bits of fractional component, for 2^53 possible combinations, leading to a 1/(2^53) chance of generating exactly 0.0.
So while it's possible for it to return exactly 0.0, it's unlikely that you'll see it any time soon - but it's just as unlikely that you'd see exactly any other particular value you might choose in advance.
A:
The [ indicates that 0.0 is included in the range of valid outputs. The ) indicates 1.0 is not in the range of valid outputs.
|
random() in python
|
In python the function random() generates a random float uniformly in the semi-open range [0.0, 1.0). In principle can it ever generate 0.0 (i.e. zero) and 1.0 (i.e. unity)? What is the scenario in practicality?
|
[
"0.0 can be generated; 1.0 cannot (since it isn't within the range, hence the ) as opposed to [).\nThe probability of generating 0.0 is equal to the probability of generating any other number within that range, namely, 1/X where X is the number of different possible results. For a standard unsigned double-precision floating point, this usually means 53 bits of fractional component, for 2^53 possible combinations, leading to a 1/(2^53) chance of generating exactly 0.0.\nSo while it's possible for it to return exactly 0.0, it's unlikely that you'll see it any time soon - but it's just as unlikely that you'd see exactly any other particular value you might choose in advance.\n",
"The [ indicates that 0.0 is included in the range of valid outputs. The ) indicates 1.0 is not in the range of valid outputs.\n"
] |
[
13,
11
] |
[] |
[] |
[
"python",
"random"
] |
stackoverflow_0002621055_python_random.txt
|
Q:
Starter question of declarative style SQLAlchemy relation()
I am quite new to SQLAlchemy, or even database programming, maybe my question is too simple.
Now I have two class/table:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(40))
...
class Computer(Base):
__tablename__ = 'comps'
id = Column(Integer, primary_key=True)
buyer_id = Column(None, ForeignKey('users.id'))
user_id = Column(None, ForeignKey('users.id'))
buyer = relation(User, backref=backref('buys', order_by=id))
user = relation(User, backref=backref('usings', order_by=id))
Of course, it cannot run. This is the backtrace:
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/state.py", line 71, in initialize_instance
fn(self, instance, args, kwargs)
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 1829, in _event_on_init
instrumenting_mapper.compile()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 687, in compile
mapper._post_configure_properties()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 716, in _post_configure_properties
prop.init()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/interfaces.py", line 408, in init
self.do_init()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/properties.py", line 716, in do_init
self._determine_joins()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/properties.py", line 806, in _determine_joins
"many-to-many relation, 'secondaryjoin' is needed as well." % (self))
sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/child tables on relation Package.maintainer. Specify a 'primaryjoin' expression. If this is a many-to-many relation, 'secondaryjoin' is needed as well.
There's two foreign keys in class Computer, so the relation() callings cannot determine which one should be used. I think I must use extra arguments to specify it, right?
And howto? Thanks
A:
The correct syntax should be:
buyer = relation(User, backref=backref('buys', order_by=id))
user = relation(User, backref=backref('usings', order_by=id))
P.S. Next time please specify what do you mean by "cannot run" by posting a traceback.
Update: the traceback in updated question says exactly what you need: specify primaryjoin condition:
buyer = relation(User, primaryjoin=(buyer_id==User.id),
backref=backref('buys', order_by=id))
user = relation(User, primaryjoin=(user_id==User.id),
backref=backref('usings', order_by=id))
|
Starter question of declarative style SQLAlchemy relation()
|
I am quite new to SQLAlchemy, or even database programming, maybe my question is too simple.
Now I have two class/table:
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String(40))
...
class Computer(Base):
__tablename__ = 'comps'
id = Column(Integer, primary_key=True)
buyer_id = Column(None, ForeignKey('users.id'))
user_id = Column(None, ForeignKey('users.id'))
buyer = relation(User, backref=backref('buys', order_by=id))
user = relation(User, backref=backref('usings', order_by=id))
Of course, it cannot run. This is the backtrace:
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/state.py", line 71, in initialize_instance
fn(self, instance, args, kwargs)
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 1829, in _event_on_init
instrumenting_mapper.compile()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 687, in compile
mapper._post_configure_properties()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/mapper.py", line 716, in _post_configure_properties
prop.init()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/interfaces.py", line 408, in init
self.do_init()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/properties.py", line 716, in do_init
self._determine_joins()
File "/Library/Python/2.6/site-packages/SQLAlchemy-0.5.8-py2.6.egg/sqlalchemy/orm/properties.py", line 806, in _determine_joins
"many-to-many relation, 'secondaryjoin' is needed as well." % (self))
sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/child tables on relation Package.maintainer. Specify a 'primaryjoin' expression. If this is a many-to-many relation, 'secondaryjoin' is needed as well.
There's two foreign keys in class Computer, so the relation() callings cannot determine which one should be used. I think I must use extra arguments to specify it, right?
And howto? Thanks
|
[
"The correct syntax should be:\nbuyer = relation(User, backref=backref('buys', order_by=id))\nuser = relation(User, backref=backref('usings', order_by=id))\n\nP.S. Next time please specify what do you mean by \"cannot run\" by posting a traceback.\nUpdate: the traceback in updated question says exactly what you need: specify primaryjoin condition:\nbuyer = relation(User, primaryjoin=(buyer_id==User.id),\n backref=backref('buys', order_by=id))\nuser = relation(User, primaryjoin=(user_id==User.id),\n backref=backref('usings', order_by=id))\n\n"
] |
[
10
] |
[] |
[] |
[
"orm",
"python",
"relation",
"sqlalchemy"
] |
stackoverflow_0002621042_orm_python_relation_sqlalchemy.txt
|
Q:
the error "invalid literal for int() with base 10:" keeps coming up
I'm trying to write a very simple program, I want to print out the sum of all the multiples of 3 and 5 below 100, but, an error keeps accuring, saying "invalid literal for int() with base 10:" my program is as follows:
sum = ""
sum_int = int(sum)
for i in range(1, 101):
if i % 5 == 0:
sum += i
elif i % 3 == 0:
sum += i
else:
sum += ""
print sum
Any help would be much appreciated.
A:
The "" are the cause of these problems.
Change
sum = ""
to
sum = 0
and get rid of
else:
sum += ""
A:
Python is not JavaScript: "" does not automatically convert to 0, and 0 does not automatically convert to "0".
Your program also seems to be confused between printing the sum of all the multiples of three and five and printing a list of all the numbers which are multiples of three and five.
A:
Ok, I'm new to Python so I was doing quite a few silly things; anyway, I think I've worked it out now.
sum = 0
for i in range(1, 1001):
if i % 5 == 0:
sum += i
elif i % 3 == 0:
sum += i
print sum
|
the error "invalid literal for int() with base 10:" keeps coming up
|
I'm trying to write a very simple program, I want to print out the sum of all the multiples of 3 and 5 below 100, but, an error keeps accuring, saying "invalid literal for int() with base 10:" my program is as follows:
sum = ""
sum_int = int(sum)
for i in range(1, 101):
if i % 5 == 0:
sum += i
elif i % 3 == 0:
sum += i
else:
sum += ""
print sum
Any help would be much appreciated.
|
[
"The \"\" are the cause of these problems.\nChange \nsum = \"\"\n\nto\nsum = 0\n\nand get rid of \nelse:\n sum += \"\"\n\n",
"Python is not JavaScript: \"\" does not automatically convert to 0, and 0 does not automatically convert to \"0\".\nYour program also seems to be confused between printing the sum of all the multiples of three and five and printing a list of all the numbers which are multiples of three and five.\n",
"Ok, I'm new to Python so I was doing quite a few silly things; anyway, I think I've worked it out now.\nsum = 0\nfor i in range(1, 1001):\n if i % 5 == 0:\n sum += i \n elif i % 3 == 0:\n sum += i\n\nprint sum\n\n"
] |
[
10,
7,
3
] |
[] |
[] |
[
"int",
"python",
"string",
"syntax"
] |
stackoverflow_0002621243_int_python_string_syntax.txt
|
Q:
Run unittest in a Class
I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests)
from alltests import SmokeTests
class CallTests(SmokeTests):
def integration(self):
self.suite()
if __name__ == '__main__':
run = CallTests()
run.integration()
And the test suite:
class SmokeTests():
def suite(self): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity') # This is the name of the file
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
unittest.main(defaultTest='suite')
So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so:
class TestInternalSanity(unittest.TestCase):
def setUp(self):
setUp script ....
def tearDown(self):
script ....
class BasicInternalSanity(TestInternalSanity):
def runTest(self):
test script ....
class InternalSanityTestSuite(unittest.TestSuite):
# Tests to be tested by test suite
def makeInternalSanityTestSuite():
suite = unittest.TestSuite()
suite.addTest(TestInternalSanity("BasicInternalSanity"))
suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail"))
return suite
def suite():
return unittest.makeSuite(TestInternalSanity)
If I have def suite() inside the class SmokeTests the script executes but the tests don't run but if I remove the class the tests run. I run this as a script and call in variables into the tests. I do not want to have to run the tests by os.system('python tests.py'). I was hoping to call the tests through the class I have like any other function. This need's to be called from a class as the script that I'm calling it from is Object Oriented. If anyone can get the code to be run using Call Tests I would appreciate it alot.
This work's:
def suite(): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity')
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
unittest.main(defaultTest='suite')
This does not work:
class SmokeTests():
def suite(self): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity')
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
unittest.main(defaultTest='suite')
I can't seem to get this to run in the class, can anyone see the solution.
Thanks
A:
Got it working, sorry for wasting everyones time, the answer was to change the default test name.
class SmokeTests():
def suite(self): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity')
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
Smoke = SmokeTests()
unittest.main(defaultTest='Smoke.suite')
Thanks for any help.
A:
It looks like you are making unittests much more complicated than they actually are. Perhaps your implementation should look more like this:
import unittest
class MyClass(object):
def add(self, val, other):
return val + other
def subtract(self, val, other):
return val - other
class TestClass(unittest.TestCase):
def test_add(self):
myclass = MyClass()
self.assert_(myclass.add(1, 2) == 3)
def test_subtract(self):
myclass = MyClass()
self.assert_(myclass.subtract(2, 1) == 1)
if __name__ == '__main__':
unittest.main()
|
Run unittest in a Class
|
I have a test suite to perform smoke tests. I have all my script stored in various classes but when I try and run the test suite I can't seem to get it working if it is in a class. The code is below: (a class to call the tests)
from alltests import SmokeTests
class CallTests(SmokeTests):
def integration(self):
self.suite()
if __name__ == '__main__':
run = CallTests()
run.integration()
And the test suite:
class SmokeTests():
def suite(self): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity') # This is the name of the file
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
unittest.main(defaultTest='suite')
So I can see how to call a normal function defined but I'm finding it difficult calling in the suite. In one of the tests the suite is set up like so:
class TestInternalSanity(unittest.TestCase):
def setUp(self):
setUp script ....
def tearDown(self):
script ....
class BasicInternalSanity(TestInternalSanity):
def runTest(self):
test script ....
class InternalSanityTestSuite(unittest.TestSuite):
# Tests to be tested by test suite
def makeInternalSanityTestSuite():
suite = unittest.TestSuite()
suite.addTest(TestInternalSanity("BasicInternalSanity"))
suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail"))
return suite
def suite():
return unittest.makeSuite(TestInternalSanity)
If I have def suite() inside the class SmokeTests the script executes but the tests don't run but if I remove the class the tests run. I run this as a script and call in variables into the tests. I do not want to have to run the tests by os.system('python tests.py'). I was hoping to call the tests through the class I have like any other function. This need's to be called from a class as the script that I'm calling it from is Object Oriented. If anyone can get the code to be run using Call Tests I would appreciate it alot.
This work's:
def suite(): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity')
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
unittest.main(defaultTest='suite')
This does not work:
class SmokeTests():
def suite(self): #Function stores all the modules to be tested
modules_to_test = ('external_sanity', 'internal_sanity')
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
unittest.main(defaultTest='suite')
I can't seem to get this to run in the class, can anyone see the solution.
Thanks
|
[
"Got it working, sorry for wasting everyones time, the answer was to change the default test name.\nclass SmokeTests(): \n\n def suite(self): #Function stores all the modules to be tested \n modules_to_test = ('external_sanity', 'internal_sanity') \n alltests = unittest.TestSuite() \n for module in map(__import__, modules_to_test): \n alltests.addTest(unittest.findTestCases(module)) \n return alltests \nif __name__ == '__main__':\n Smoke = SmokeTests() \n unittest.main(defaultTest='Smoke.suite') \n\nThanks for any help.\n",
"It looks like you are making unittests much more complicated than they actually are. Perhaps your implementation should look more like this:\nimport unittest\n\nclass MyClass(object):\n\n def add(self, val, other):\n return val + other\n\n def subtract(self, val, other):\n return val - other\n\n\nclass TestClass(unittest.TestCase):\n\n def test_add(self):\n myclass = MyClass()\n self.assert_(myclass.add(1, 2) == 3)\n\n def test_subtract(self):\n myclass = MyClass()\n self.assert_(myclass.subtract(2, 1) == 1)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"automated_tests",
"class",
"oop",
"python",
"unit_testing"
] |
stackoverflow_0002620837_automated_tests_class_oop_python_unit_testing.txt
|
Q:
how to make fillable forms with reportlab in python
can anyone please help me with creating forms in python using the reportlab lib.
i am totally new to this and i would appreciate sample code
thanks
A:
Apparently reportlab does not support creating fillable pdf forms. The only thing I found about it being present in the API dates from 2003, afterwards all statements clearly say no.
I'm answering this so late because this is one of the highest hits when you enter 'reportlab forms' in google. I do agree with Travis you should google easy questions yourself, but this isn't really clearly answered anywhere.
|
how to make fillable forms with reportlab in python
|
can anyone please help me with creating forms in python using the reportlab lib.
i am totally new to this and i would appreciate sample code
thanks
|
[
"Apparently reportlab does not support creating fillable pdf forms. The only thing I found about it being present in the API dates from 2003, afterwards all statements clearly say no.\nI'm answering this so late because this is one of the highest hits when you enter 'reportlab forms' in google. I do agree with Travis you should google easy questions yourself, but this isn't really clearly answered anywhere.\n"
] |
[
7
] |
[] |
[] |
[
"pdf_generation",
"python",
"reportlab"
] |
stackoverflow_0002021764_pdf_generation_python_reportlab.txt
|
Q:
Using PyQt signals correctly
A while ago I did some work in Qt for C++; now I'm working with PyQt.
I have a subclass of QStackedWidget, and inside that a subclass of QWidget. In the QWidget I want to click a button that goes to the next page of the QStackedWidget. My (simplified) approach is as follows:
class Stacked(QtGui.QStackedWidget):
def __init__(self, parent=None):
QtGui.QStackedWidget.__init__(self, parent)
self.widget1 = EventsPage()
self.widget1.nextPage.connect(self.nextPage)
self.widget2 = MyWidget()
self.addWidget(self.widget1)
self.addWidget(self.widget2)
def nextPage(self):
self.setCurrentIndex(self.currentIndex() + 1)
class EventsPage(QtGui.QWidget):
nextPage = QtCore.pyqtSignal()
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.continueButton = QtGui.QPushButton('Continue')
self.continueButton.clicked.connect(self.nextPage)
So, basically, I'm connecting the continueButton clicked signal to the EventsPage nextPage signal, which I'm then connecting in Stacked to the nextPage method. I could just delve into the internals of EventsPage in Stacked and connect self.widget1.continueButton.clicked, but that seemed to completely defeat the purpose of signals and slots.
So does this approach make sense, or is there a better way?
A:
No, this makes perfect sense. Think of signals as people waving from the top of buildings. They don't want to cross the street (all those staircases ...), so they watch what other people on other buildings are doing. This way, no one has to care what's going on inside the buildings.
|
Using PyQt signals correctly
|
A while ago I did some work in Qt for C++; now I'm working with PyQt.
I have a subclass of QStackedWidget, and inside that a subclass of QWidget. In the QWidget I want to click a button that goes to the next page of the QStackedWidget. My (simplified) approach is as follows:
class Stacked(QtGui.QStackedWidget):
def __init__(self, parent=None):
QtGui.QStackedWidget.__init__(self, parent)
self.widget1 = EventsPage()
self.widget1.nextPage.connect(self.nextPage)
self.widget2 = MyWidget()
self.addWidget(self.widget1)
self.addWidget(self.widget2)
def nextPage(self):
self.setCurrentIndex(self.currentIndex() + 1)
class EventsPage(QtGui.QWidget):
nextPage = QtCore.pyqtSignal()
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.continueButton = QtGui.QPushButton('Continue')
self.continueButton.clicked.connect(self.nextPage)
So, basically, I'm connecting the continueButton clicked signal to the EventsPage nextPage signal, which I'm then connecting in Stacked to the nextPage method. I could just delve into the internals of EventsPage in Stacked and connect self.widget1.continueButton.clicked, but that seemed to completely defeat the purpose of signals and slots.
So does this approach make sense, or is there a better way?
|
[
"No, this makes perfect sense. Think of signals as people waving from the top of buildings. They don't want to cross the street (all those staircases ...), so they watch what other people on other buildings are doing. This way, no one has to care what's going on inside the buildings.\n"
] |
[
6
] |
[] |
[] |
[
"pyqt",
"python",
"signals_slots"
] |
stackoverflow_0002622210_pyqt_python_signals_slots.txt
|
Q:
A python random function acts differently when assigned to a list or called directly
I have a python function that randomize a dictionary representing a position specific scoring matrix.
for example:
mat = {
'A' : [ 0.53, 0.66, 0.67, 0.05, 0.01, 0.86, 0.03, 0.97, 0.33, 0.41, 0.26 ]
'C' : [ 0.14, 0.04, 0.13, 0.92, 0.99, 0.04, 0.94, 0.00, 0.07, 0.23, 0.35 ]
'T' : [ 0.25, 0.07, 0.01, 0.01, 0.00, 0.04, 0.00, 0.03, 0.06, 0.12, 0.14 ]
'G' : [ 0.08, 0.23, 0.20, 0.02, 0.00, 0.06, 0.04, 0.00, 0.54, 0.24, 0.25 ]
}
The scambling function:
def scramble_matrix(matrix, iterations):
mat_len = len(matrix["A"])
pos1 = pos2 = 0
for count in range(iterations):
pos1,pos2 = random.sample(range(mat_len), 2)
#suffle the matrix:
for nuc in matrix.keys():
matrix[nuc][pos1],matrix[nuc][pos2] = matrix[nuc][pos2],matrix[nuc][pos1]
return matrix
def print_matrix(matrix):
for nuc in matrix.keys():
print nuc+"[",
for count in matrix[nuc]:
print "%.2f"%count,
print "]"
now to the problem...
When I try to scramble a matrix directly, It's works fine:
print_matrix(mat)
print ""
print_matrix(scramble_matrix(mat,10))
gives:
A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ]
C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ]
T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ]
G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ]
A[ 0.41 0.97 0.03 0.86 0.53 0.66 0.33.05 0.67 0.26 0.01 ]
C[ 0.23 0.00 0.94 0.04 0.14 0.04 0.07 0.92 0.13 0.35 0.99 ]
T[ 0.12 0.03 0.00 0.04 0.25 0.07 0.06 0.01 0.01 0.14 0.00 ]
G[ 0.24 0.00 0.04 0.06 0.08 0.23 0.54 0.02 0.20 0.25 0.00 ]
but when I try to assign this scrambling to a list , it does not work!!! ...
print_matrix(mat)
s=[]
for x in range(3):
s.append(scramble_matrix(mat,10))
for matrix in s:
print ""
print_matrix(matrix)
result:
A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ]
C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ]
T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ]
G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ]
A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ]
C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ]
T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ]
G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ]
A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ]
C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ]
T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ]
G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ]
A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ]
C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ]
T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ]
G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ]
What is the problem???
Why the scrambling do not work after the first time, and all the list filled with the same matrix?!
A:
Your scrambling function is modifying the existing matrix, it is not creating a new one.
You create a matrix, scramble it and add it to a list. Then you scramble it again and add it again to the list. Both elements of the list contain now the same matrix object, which got scrambled twice.
A:
You are shuffling the same matrix in-place for 3 times. But you really want to shuffle 3 copies of original matrix. So you should do:
from copy import deepcopy
print_matrix(mat)
s=[]
for x in range(3):
s.append(scramble_matrix(deepcopy(mat),10)) # note the deepcopy()
for matrix in s:
print ""
print_matrix(matrix)
|
A python random function acts differently when assigned to a list or called directly
|
I have a python function that randomize a dictionary representing a position specific scoring matrix.
for example:
mat = {
'A' : [ 0.53, 0.66, 0.67, 0.05, 0.01, 0.86, 0.03, 0.97, 0.33, 0.41, 0.26 ]
'C' : [ 0.14, 0.04, 0.13, 0.92, 0.99, 0.04, 0.94, 0.00, 0.07, 0.23, 0.35 ]
'T' : [ 0.25, 0.07, 0.01, 0.01, 0.00, 0.04, 0.00, 0.03, 0.06, 0.12, 0.14 ]
'G' : [ 0.08, 0.23, 0.20, 0.02, 0.00, 0.06, 0.04, 0.00, 0.54, 0.24, 0.25 ]
}
The scambling function:
def scramble_matrix(matrix, iterations):
mat_len = len(matrix["A"])
pos1 = pos2 = 0
for count in range(iterations):
pos1,pos2 = random.sample(range(mat_len), 2)
#suffle the matrix:
for nuc in matrix.keys():
matrix[nuc][pos1],matrix[nuc][pos2] = matrix[nuc][pos2],matrix[nuc][pos1]
return matrix
def print_matrix(matrix):
for nuc in matrix.keys():
print nuc+"[",
for count in matrix[nuc]:
print "%.2f"%count,
print "]"
now to the problem...
When I try to scramble a matrix directly, It's works fine:
print_matrix(mat)
print ""
print_matrix(scramble_matrix(mat,10))
gives:
A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ]
C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ]
T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ]
G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ]
A[ 0.41 0.97 0.03 0.86 0.53 0.66 0.33.05 0.67 0.26 0.01 ]
C[ 0.23 0.00 0.94 0.04 0.14 0.04 0.07 0.92 0.13 0.35 0.99 ]
T[ 0.12 0.03 0.00 0.04 0.25 0.07 0.06 0.01 0.01 0.14 0.00 ]
G[ 0.24 0.00 0.04 0.06 0.08 0.23 0.54 0.02 0.20 0.25 0.00 ]
but when I try to assign this scrambling to a list , it does not work!!! ...
print_matrix(mat)
s=[]
for x in range(3):
s.append(scramble_matrix(mat,10))
for matrix in s:
print ""
print_matrix(matrix)
result:
A[ 0.53 0.66 0.67 0.05 0.01 0.86 0.03 0.97 0.33 0.41 0.26 ]
C[ 0.14 0.04 0.13 0.92 0.99 0.04 0.94 0.00 0.07 0.23 0.35 ]
T[ 0.25 0.07 0.01 0.01 0.00 0.04 0.00 0.03 0.06 0.12 0.14 ]
G[ 0.08 0.23 0.20 0.02 0.00 0.06 0.04 0.00 0.54 0.24 0.25 ]
A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ]
C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ]
T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ]
G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ]
A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ]
C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ]
T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ]
G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ]
A[ 0.01 0.66 0.97 0.67 0.03 0.05 0.33 0.53 0.26 0.41 0.86 ]
C[ 0.99 0.04 0.00 0.13 0.94 0.92 0.07 0.14 0.35 0.23 0.04 ]
T[ 0.00 0.07 0.03 0.01 0.00 0.01 0.06 0.25 0.14 0.12 0.04 ]
G[ 0.00 0.23 0.00 0.20 0.04 0.02 0.54 0.08 0.25 0.24 0.06 ]
What is the problem???
Why the scrambling do not work after the first time, and all the list filled with the same matrix?!
|
[
"Your scrambling function is modifying the existing matrix, it is not creating a new one.\nYou create a matrix, scramble it and add it to a list. Then you scramble it again and add it again to the list. Both elements of the list contain now the same matrix object, which got scrambled twice.\n",
"You are shuffling the same matrix in-place for 3 times. But you really want to shuffle 3 copies of original matrix. So you should do:\nfrom copy import deepcopy\n\nprint_matrix(mat)\ns=[]\nfor x in range(3):\n s.append(scramble_matrix(deepcopy(mat),10)) # note the deepcopy()\nfor matrix in s:\n print \"\"\n print_matrix(matrix)\n\n"
] |
[
4,
3
] |
[] |
[] |
[
"function",
"mutable",
"python"
] |
stackoverflow_0002622395_function_mutable_python.txt
|
Q:
python mechanize.browser submit() related problem
im making some script with mechanize.browser module.
one of problem is all other thing is ok, but when submit() form,it not working,
so i was found some suspicion source part.
in the html source i was found such like following.
<form method="post" onsubmit="return loginCheck(this)" name="FRMLOGIN"/>
im thinking, loginCheck(this) making problem when submit form.
but how to handle this kind of javascript function with mechanize module ,so i can
successfully submit form and can receive result?
folloing is my current script source.
if anyone can help me ..much appreciate!!
# -*- coding: cp949-*-
import sys,os
import mechanize, urllib
import cookielib
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
import datetime, time, socket
import re,sys,os,mechanize,urllib,time
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open('http://user.buddybuddy.co.kr/Login/LoginForm.asp?URL=')
html = br.response().read()
print html
br.select_form(name='FRMLOGIN')
print br.viewing_html()
br.form['ID']='zero1zero2'
br.form['PWD']='012045'
br.submit()
print br.response().read()
A:
mechanize doesn't support Javascript at all. If you absolutely have to run that Javascript, look into Selenium. It offers python bindings to control a real, running browser like Firefox or IE.
A:
onsubmit is just ignored by mechanize, no javascript interpretation is done.
You need to verify what loginCheck(); in some limited case (Validation) you can do programmatically what javascript does.
A:
you will either need to make use of unmaintained module DOMForm and Spidermonkey (http://pypi.python.org/pypi/python-spidermonkey) to process javascript. Or you figure out what loginCheck() is doing and perform its work prior form submission in python. If loginCheck() just checks for obvious validity of login data, that should be pretty easy.
Please note, that the action parameter of the stated form tag is missing. It's probably given in the javascript part.
Depending on what you intend it might be easier to work with urllib2 only. You might assume a static appearance of that web page and just post data with urllib2's methods and get the results with it also.
|
python mechanize.browser submit() related problem
|
im making some script with mechanize.browser module.
one of problem is all other thing is ok, but when submit() form,it not working,
so i was found some suspicion source part.
in the html source i was found such like following.
<form method="post" onsubmit="return loginCheck(this)" name="FRMLOGIN"/>
im thinking, loginCheck(this) making problem when submit form.
but how to handle this kind of javascript function with mechanize module ,so i can
successfully submit form and can receive result?
folloing is my current script source.
if anyone can help me ..much appreciate!!
# -*- coding: cp949-*-
import sys,os
import mechanize, urllib
import cookielib
from BeautifulSoup import BeautifulSoup,BeautifulStoneSoup,Tag
import datetime, time, socket
import re,sys,os,mechanize,urllib,time
br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
br.set_debug_http(True)
br.set_debug_redirects(True)
br.set_debug_responses(True)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open('http://user.buddybuddy.co.kr/Login/LoginForm.asp?URL=')
html = br.response().read()
print html
br.select_form(name='FRMLOGIN')
print br.viewing_html()
br.form['ID']='zero1zero2'
br.form['PWD']='012045'
br.submit()
print br.response().read()
|
[
"mechanize doesn't support Javascript at all. If you absolutely have to run that Javascript, look into Selenium. It offers python bindings to control a real, running browser like Firefox or IE.\n",
"onsubmit is just ignored by mechanize, no javascript interpretation is done.\nYou need to verify what loginCheck(); in some limited case (Validation) you can do programmatically what javascript does.\n",
"you will either need to make use of unmaintained module DOMForm and Spidermonkey (http://pypi.python.org/pypi/python-spidermonkey) to process javascript. Or you figure out what loginCheck() is doing and perform its work prior form submission in python. If loginCheck() just checks for obvious validity of login data, that should be pretty easy.\nPlease note, that the action parameter of the stated form tag is missing. It's probably given in the javascript part.\nDepending on what you intend it might be easier to work with urllib2 only. You might assume a static appearance of that web page and just post data with urllib2's methods and get the results with it also.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"mechanize",
"python"
] |
stackoverflow_0002544430_mechanize_python.txt
|
Q:
Splitting a string using space delimiters and a maximum length
I'd like to split a string in a similar way to .split() (so resulting in a list) but in a more intelligent way: I'd like it to split it into chunks that are up to 15 characters, but are not split mid word so:
string = 'A string with words'
[splitting process takes place]
list = ('A string with','words')
The string in this example is split between 'with' and 'words' because that's the last place you can split it and the first bit be 15 characters or less.
A:
>>> import textwrap
>>> string = 'A string with words'
>>> textwrap.wrap(string,15)
['A string with', 'words']
A:
You can do this two different ways:
>>> import re, textwrap
>>> s = 'A string with words'
>>> textwrap.wrap(s, 15)
['A string with', 'words']
>>> re.findall(r'\b.{1,15}\b', s)
['A string with ', 'words']
Note the slight difference in space handling.
A:
You're probably looking to use a regex. The python re module has a split function, but I think you would be better served by simply matching groups.
>>> re.findall(r'(.{,15})\s(.*$)', 'A string wth words')
[('A string wth', 'words')]
[Edit] sorry, missed the point where you want multiple chunks. I was going to put a more complex regex in here, but the textwrap module cited above is made for this. I'll leave extending the regex as an exercise for you if you choose.
|
Splitting a string using space delimiters and a maximum length
|
I'd like to split a string in a similar way to .split() (so resulting in a list) but in a more intelligent way: I'd like it to split it into chunks that are up to 15 characters, but are not split mid word so:
string = 'A string with words'
[splitting process takes place]
list = ('A string with','words')
The string in this example is split between 'with' and 'words' because that's the last place you can split it and the first bit be 15 characters or less.
|
[
">>> import textwrap\n>>> string = 'A string with words'\n>>> textwrap.wrap(string,15)\n['A string with', 'words']\n\n",
"You can do this two different ways:\n>>> import re, textwrap\n>>> s = 'A string with words'\n>>> textwrap.wrap(s, 15)\n['A string with', 'words']\n>>> re.findall(r'\\b.{1,15}\\b', s)\n['A string with ', 'words']\n\nNote the slight difference in space handling.\n",
"You're probably looking to use a regex. The python re module has a split function, but I think you would be better served by simply matching groups.\n>>> re.findall(r'(.{,15})\\s(.*$)', 'A string wth words')\n[('A string wth', 'words')]\n\n[Edit] sorry, missed the point where you want multiple chunks. I was going to put a more complex regex in here, but the textwrap module cited above is made for this. I'll leave extending the regex as an exercise for you if you choose.\n"
] |
[
30,
6,
1
] |
[] |
[] |
[
"python",
"split",
"string"
] |
stackoverflow_0002622572_python_split_string.txt
|
Q:
Is there a standard lexer/parser tool for Python?
A volunteer job requires us to convert a large number of LaTeX documents into ePub file format. It's a series of open-source fiction book which has so far only been produced only on paper via a print on demand service. We'd like to be able to offer the book to users of book-reader devices (such as Kindle) which require the ePub format for best results.
Fortunately, ePub is a very simple format, however there's no trivial way for LaTeX to produce the XHTML output required.
We experimented with alternative LaTeX compilers (e.g. plastex) but in the end we figured that it would probably be a lot easier to simply write our own compiler which understands a tiny subset of the LaTeX language and compiles directly to XHTML / ePub.
Previously I used a tool on Windows called GOLD. This allowed me to go directly from BNF grammars to a stub parser. It also alllowed me to implement the parser in any language I liked. (I'd choose Python).
This product has to work on Linux, so I'm wondering if there's an equivalent toolchain that works as well under Ubutnu / Eclipse / Python. The idea is that we will take the grammar of TeX and just implement a teeny subset of that, but we do not want to spend a huge amount of time worrying about grammar and parsing. A parser generator would obviously save us a great deal of time.
Sal
UPDATE 1: Bonus marks for a solution with excellent documentation or tutorials.
UPDATE 2: Extra bonus if there is grammar file for TeX already available, since all I'd have to do is implement the functions we care about.
A:
Try pyparsing.
Se http://pyparsing.wikispaces.com/WhosUsingPyparsing, search for TeX. There's a project where pyparsing is used to parse a subset of TeX syntax mentioned on that page.
For documentation, I recommend the "Getting started with pyparsing" e-book, by pyparsing's author.
EDIT: According to PaulMcG, Pyparsing is no longer hosted on wikispaces.com. Go to the new GitHub site
A:
Try PLY.
A:
I once used tex4ht to convert LaTeX to XHTML+MathML. Worked quite nice. From that on, you could use the output HTML as base for the ePub.
Of course, this breaks the Python toolchain, so it might not become your favorite method...
|
Is there a standard lexer/parser tool for Python?
|
A volunteer job requires us to convert a large number of LaTeX documents into ePub file format. It's a series of open-source fiction book which has so far only been produced only on paper via a print on demand service. We'd like to be able to offer the book to users of book-reader devices (such as Kindle) which require the ePub format for best results.
Fortunately, ePub is a very simple format, however there's no trivial way for LaTeX to produce the XHTML output required.
We experimented with alternative LaTeX compilers (e.g. plastex) but in the end we figured that it would probably be a lot easier to simply write our own compiler which understands a tiny subset of the LaTeX language and compiles directly to XHTML / ePub.
Previously I used a tool on Windows called GOLD. This allowed me to go directly from BNF grammars to a stub parser. It also alllowed me to implement the parser in any language I liked. (I'd choose Python).
This product has to work on Linux, so I'm wondering if there's an equivalent toolchain that works as well under Ubutnu / Eclipse / Python. The idea is that we will take the grammar of TeX and just implement a teeny subset of that, but we do not want to spend a huge amount of time worrying about grammar and parsing. A parser generator would obviously save us a great deal of time.
Sal
UPDATE 1: Bonus marks for a solution with excellent documentation or tutorials.
UPDATE 2: Extra bonus if there is grammar file for TeX already available, since all I'd have to do is implement the functions we care about.
|
[
"Try pyparsing.\nSe http://pyparsing.wikispaces.com/WhosUsingPyparsing, search for TeX. There's a project where pyparsing is used to parse a subset of TeX syntax mentioned on that page.\nFor documentation, I recommend the \"Getting started with pyparsing\" e-book, by pyparsing's author.\nEDIT: According to PaulMcG, Pyparsing is no longer hosted on wikispaces.com. Go to the new GitHub site \n",
"Try PLY.\n",
"I once used tex4ht to convert LaTeX to XHTML+MathML. Worked quite nice. From that on, you could use the output HTML as base for the ePub.\nOf course, this breaks the Python toolchain, so it might not become your favorite method...\n"
] |
[
5,
3,
3
] |
[] |
[] |
[
"bnf",
"compiler_construction",
"parsing",
"python",
"tex"
] |
stackoverflow_0002622038_bnf_compiler_construction_parsing_python_tex.txt
|
Q:
How to send raw XML in Python?
I am trying to send raw xml to a service in Python. I have a the address of the service and my question is how would I wrap XML in python and send it to the service. The address is in the format below.
192.1100.2.2:54239
And say the XML is:
<xml version="1.0" encoding="UTF-8"><header/><body><code><body/>
Anyone know what to do?
A:
This should do the trick.
import socket
import time
command = '<xml version="1.0" encoding="UTF-8"><header/><body><code><body/>'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.1100.2.2", 54239))
s.send(command)
time.sleep(2)
resp = s.recv(3000)
print resp
A:
pydoc socket
... should get you started.
PS. Your example IP address looks a bit strange (1100 is greater than 255), but maybe that's just so nobody tries to use it ...
|
How to send raw XML in Python?
|
I am trying to send raw xml to a service in Python. I have a the address of the service and my question is how would I wrap XML in python and send it to the service. The address is in the format below.
192.1100.2.2:54239
And say the XML is:
<xml version="1.0" encoding="UTF-8"><header/><body><code><body/>
Anyone know what to do?
|
[
"This should do the trick.\nimport socket\nimport time\n\ncommand = '<xml version=\"1.0\" encoding=\"UTF-8\"><header/><body><code><body/>'\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((\"192.1100.2.2\", 54239))\n\ns.send(command)\n\ntime.sleep(2)\nresp = s.recv(3000)\n\nprint resp\n\n",
"pydoc socket\n\n... should get you started.\nPS. Your example IP address looks a bit strange (1100 is greater than 255), but maybe that's just so nobody tries to use it ...\n"
] |
[
7,
1
] |
[] |
[] |
[
"python",
"xml"
] |
stackoverflow_0002623054_python_xml.txt
|
Q:
Python: how to enclose strings in a list with < and >
i would like to enclose strings inside of list into <> (formatted like <%s>). The current code does the following:
def create_worker (general_logger, general_config):
arguments = ["worker_name", "worker_module", "worker_class"]
__check_arguments(arguments)
def __check_arguments(arguments):
if len(sys.argv) < 2 + len(arguments):
print "Usage: %s delete-project %s" % (__file__," ".join(arguments))
sys.exit(10)
The current output looks like this:
Usage: ...\handler_scripts.py delete-project worker_name worker_module worker_class
and should look like this:
Usage: ...\handler_scripts.py delete-project <worker_name> <worker_module> <worker_class>
Is there any short way to do this ?
Greetings,
Michael
A:
What about:
print "Usage: %s delete-project %s" % (__file__," ".join('<%s>'% arg for arg in arguments))
A:
Use a list comprehension: ['<%s>' % s for s in arguments].
A:
Replace your join bit with:
' '.join('<%s>' % s for s in arguments)
A:
Replace
(__file__," ".join(arguments))
with
(__file__," ".join("<%s>" % a for a in arguments))
|
Python: how to enclose strings in a list with < and >
|
i would like to enclose strings inside of list into <> (formatted like <%s>). The current code does the following:
def create_worker (general_logger, general_config):
arguments = ["worker_name", "worker_module", "worker_class"]
__check_arguments(arguments)
def __check_arguments(arguments):
if len(sys.argv) < 2 + len(arguments):
print "Usage: %s delete-project %s" % (__file__," ".join(arguments))
sys.exit(10)
The current output looks like this:
Usage: ...\handler_scripts.py delete-project worker_name worker_module worker_class
and should look like this:
Usage: ...\handler_scripts.py delete-project <worker_name> <worker_module> <worker_class>
Is there any short way to do this ?
Greetings,
Michael
|
[
"What about:\nprint \"Usage: %s delete-project %s\" % (__file__,\" \".join('<%s>'% arg for arg in arguments))\n\n",
"Use a list comprehension: ['<%s>' % s for s in arguments].\n",
"Replace your join bit with:\n' '.join('<%s>' % s for s in arguments)\n\n",
"Replace\n(__file__,\" \".join(arguments))\n\nwith\n(__file__,\" \".join(\"<%s>\" % a for a in arguments))\n\n"
] |
[
5,
1,
0,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0002623247_python_string.txt
|
Q:
Why is Standard Input is not displayed as I type in Mac OS X Terminal application?
I'm confused by some behavior of my Mac OS X Terminal and my Django manage.py shell and pdb.
When I start a new terminal, the Standard Input is displayed as I type. However, if there is an error, suddenly Standard Input does not appear on the screen. This error continues until I shut down that terminal window.
The Input is still being captured as I can see the Standard Output.
E.g. in pdb.set_trace() I can 'l' to display where I'm at in the code. However, the 'l' will not be displayed, just an empty prompt.
This makes it hard to debug because I can't determine what I'm typing in.
What could be going wrong and what can I do to fix it?
A:
Maybe this is because there was an error while running Django. Sometimes it happens that the std input disappears because stty was used. You can manually hide your input by typing:
$ stty -echo
Now you won't see what you typed. To restore this and solve your problem just type
$ stty echo
This could help.
A:
If you exit pdb you can type reset and standard input echo will return. I'm not sure if you can execute something similar within pdb. It will erase what is currently displayed however.
|
Why is Standard Input is not displayed as I type in Mac OS X Terminal application?
|
I'm confused by some behavior of my Mac OS X Terminal and my Django manage.py shell and pdb.
When I start a new terminal, the Standard Input is displayed as I type. However, if there is an error, suddenly Standard Input does not appear on the screen. This error continues until I shut down that terminal window.
The Input is still being captured as I can see the Standard Output.
E.g. in pdb.set_trace() I can 'l' to display where I'm at in the code. However, the 'l' will not be displayed, just an empty prompt.
This makes it hard to debug because I can't determine what I'm typing in.
What could be going wrong and what can I do to fix it?
|
[
"Maybe this is because there was an error while running Django. Sometimes it happens that the std input disappears because stty was used. You can manually hide your input by typing:\n$ stty -echo\nNow you won't see what you typed. To restore this and solve your problem just type\n$ stty echo\nThis could help.\n",
"If you exit pdb you can type reset and standard input echo will return. I'm not sure if you can execute something similar within pdb. It will erase what is currently displayed however.\n"
] |
[
26,
3
] |
[
"Try installing readline on Mac OS X:\n$ sudo easy_install readline\n\nThis is a blind guess, but perhaps it solves your problem.\n"
] |
[
-1
] |
[
"django",
"macos",
"python",
"shell",
"terminal"
] |
stackoverflow_0001301887_django_macos_python_shell_terminal.txt
|
Q:
How do I insert data from a Python dictionary to MySQL?
I manipulated some data from MySQL and the resulting dictionary "data" (print data) displays something like this :
{'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],
'2': ['2', 'K', efg, 'xyz', None, None, None, None],
'3': ['3', 'K', ijk, 'xyz', None, None, None, datetime.date(2010, 2, 5, 16, 31, 2)]}
How do I create a table and insert these values in a MySQL table? In other words, how do I dump them to MySQL or CSV? Not sure how to deal with datetime.date and None values. Any help is appreciated.
A:
datetime.date matches DATE fields, and None becomes NULL. Use .executemany() in conjunction with dict.values() in order to perform the INSERT.
A:
Most dbapi-compliant connectors to MySQL will automatically convert Python's None to SQL's NULL and Python's datetime objects to SQL TIMESTAMPs.
Really, you just need to open a connection to your database, get a cursor, and iterate over the dictionary doing the insert. Without knowing your schema, it's impossible to give you sample code, though.
A:
Here is some basic code to create a MySQL database, and insert some data.
import MySQLdb
import datetime
THEHOST="localhost"
THEUSER="user"
THEPASSWD="passwd"
THEDB="database"
connection=MySQLdb.connect(
host=THEHOST,user=THEUSER,passwd=THEPASSWD,db=THEDB)
cursor=connection.cursor()
abc,efg,ijk=1,2,3
data={'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],
'2': ['2', 'K', efg, 'xyz', None, None, None, None],
'3': ['3', 'K', ijk, 'xyz', None, None, None,
datetime.datetime(2010, 2, 5, 16, 31, 2)]}
sql='''\
CREATE TABLE IF NOT EXISTS temp (id int auto_increment primary key,
field1 varchar(8),
field2 int,
field3 varchar(8),
field4 bool,
field5 varchar(8),
field6 varchar(8),
field7 datetime )'''
cursor.execute(sql)
sql='''\
INSERT INTO temp (id, field1, field2, field3, field4, field5, field6, field7)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
'''
cursor.executemany(sql, data.values())
|
How do I insert data from a Python dictionary to MySQL?
|
I manipulated some data from MySQL and the resulting dictionary "data" (print data) displays something like this :
{'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],
'2': ['2', 'K', efg, 'xyz', None, None, None, None],
'3': ['3', 'K', ijk, 'xyz', None, None, None, datetime.date(2010, 2, 5, 16, 31, 2)]}
How do I create a table and insert these values in a MySQL table? In other words, how do I dump them to MySQL or CSV? Not sure how to deal with datetime.date and None values. Any help is appreciated.
|
[
"datetime.date matches DATE fields, and None becomes NULL. Use .executemany() in conjunction with dict.values() in order to perform the INSERT.\n",
"Most dbapi-compliant connectors to MySQL will automatically convert Python's None to SQL's NULL and Python's datetime objects to SQL TIMESTAMPs.\nReally, you just need to open a connection to your database, get a cursor, and iterate over the dictionary doing the insert. Without knowing your schema, it's impossible to give you sample code, though.\n",
"Here is some basic code to create a MySQL database, and insert some data.\nimport MySQLdb\nimport datetime\n\nTHEHOST=\"localhost\"\nTHEUSER=\"user\"\nTHEPASSWD=\"passwd\"\nTHEDB=\"database\"\n\nconnection=MySQLdb.connect(\n host=THEHOST,user=THEUSER,passwd=THEPASSWD,db=THEDB)\ncursor=connection.cursor()\n\nabc,efg,ijk=1,2,3\n\ndata={'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],\n '2': ['2', 'K', efg, 'xyz', None, None, None, None],\n '3': ['3', 'K', ijk, 'xyz', None, None, None,\n datetime.datetime(2010, 2, 5, 16, 31, 2)]}\n\nsql='''\\\nCREATE TABLE IF NOT EXISTS temp (id int auto_increment primary key,\n field1 varchar(8),\n field2 int,\n field3 varchar(8),\n field4 bool,\n field5 varchar(8),\n field6 varchar(8),\n field7 datetime )'''\n\ncursor.execute(sql)\n\nsql='''\\\nINSERT INTO temp (id, field1, field2, field3, field4, field5, field6, field7)\nVALUES (%s, %s, %s, %s, %s, %s, %s, %s)\n'''\ncursor.executemany(sql, data.values())\n\n"
] |
[
1,
1,
1
] |
[] |
[] |
[
"dictionary",
"mysql",
"python"
] |
stackoverflow_0002623418_dictionary_mysql_python.txt
|
Q:
Creating multiple csv files from data within a csv file
System OSX or Linux
I'm trying to automate my work flow at work, each week I receive an excel file, which I convert to a csv.
An example is:
,,L1,,,L2,,,L3,,,L4,,,L5,,,L6,,,L7,,,L8,,,L9,,,L10,,,L11,
Title,r/t,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,neede d,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst
EXAMPLEfoo,60,6,6,6,0,0,0,0,0,0,6,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EXAMPLEbar,30,6,6,12,6,7,14,6,6,12,6,6,12,6,8,16,6,7,14,6,7.5,15,6,6,12,6,8,16,6,0,0,6,7,14
EXAMPLE1,60,3,3,3,3,5,5,3,4,4,3,3,3,3,6,6,3,4,4,3,3,3,3,4,4,3,8,8,3,0,0,3,4,4
EXAMPLE2,120,6,6,3,0,0,0,6,8,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EXAMPLE3,60,6,6,6,6,8,8,6,6,6,6,6,6,0,0,0,0,0,0,6,8,8,6,6,6,0,0,0,0,0,0,0,10,10
EXAMPLE4,30,6,6,12,6,7,14,6,6,12,6,6,12,3,5.5,11,6,7.5,15,6,6,12,6,0,0,6,9,18,6,0,0,6,6.5,13
And so you can get a picture of how it looks in excel:
What I need to do, is create multiple csv files for each instance in row 1, so L1, L2, L3, L4...
And within that each csv file it needs to contain the title, r/t, needed
So for L1 an example out put would look like:
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
And for L2:
EXAMPLEfoo,60,0
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,0
EXAMPLE3,60,6
EXAMPLE4,30,6
And so on.
I have tried playing around with sed and awk and hit google but I have found nothing that really solves the issue.
I'd imagine perl would be particular suited to this or maybe python, so I would be more than happy to accept suggestions from users.
So, any suggestions?
Thanks in advance.
A:
Perl "one-liner"
perl -MText::CSV_XS -e'$c=Text::CSV_XS->new({binary=>1,eol=>"\n"});%a=map{$i++;/^L\d+$/?($_=>$i):()}@{$c->getline(*ARGV)};open$b{$_},">$_"for keys%a;while($f=$c->getline(*ARGV)){$c->print($b{$_},[@$f[0,1,$a{$_}]])for keys%a}'
For ones which have problem with reading:
$ echo '$c=Te...' | perltidy
$c = Text::CSV_XS->new( { binary => 1, eol => "\n" } );
%a = map { $i++; /^L\d+$/ ? ( $_ => $i ) : () } @{ $c->getline(*ARGV) };
open $b{$_}, ">$_" for keys %a;
while ( $f = $c->getline(*ARGV) ) {
$c->print( $b{$_}, [ @$f[ 0, 1, $a{$_} ] ] )
for keys %a;
}
A:
Using only AWK:
awk -F, -vOFS=, -vc=1 '
NR == 1 {
for (i=1; i<NF; i++) {
if ($i != "") {
g[c]=i;
f[c++]=$i
}
}
}
NR>2 {
for (i=1; i < c; i++) {
print $1,$2, $g[i] > "output_"f[i]".csv"
}
}' data.csv
As a one-liner:
awk -F, -vOFS=, -vc=1 'NR == 1 {for (i=1; i<NF; i++) {if ($i != "") {g[c]=i; f[c++]=$i}}} NR>2 { for (i=1; i < c; i++) {print $1,$2, $g[i] > "file_"f[i]".csv" }}' data.csv
Example output:
$ cat file_L1.csv
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
$ cat file_L2.csv
EXAMPLEfoo,60,0
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,0
EXAMPLE3,60,6
EXAMPLE4,30,6
$ cat file_L11.csv
EXAMPLEfoo,60,0
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,0
EXAMPLE3,60,0
EXAMPLE4,30,6
A:
use strict;
use warnings;
use Text::CSV;
my $csv = Text::CSV->new;
sub parse_line {
$csv->parse(shift) or die $!;
return $csv->fields;
}
my @metadata;
my @files = parse_line(scalar <>);
my @header = parse_line(scalar <>); # Ignore.
for my $i (0 .. $#files){
next unless length $files[$i];
open(my $h, '>', "$files[$i].csv") or die $!;
push @metadata, {column => $i, handle => $h};
}
while (my $line = <>){
my @fields = parse_line($line);
for my $m (@metadata){
$csv->print($m->{handle}, [ @fields[0, 1, $m->{column}] ]);
print {$m->{handle}} "\n";
}
}
A:
try this
#!/bin/bash
awk 'BEGIN{ OFS=FS="," }
NR==1{
for(i=1;i<=NF;i++){
if($i){ f[i]=$i }
}
}
NR>2{ for(o in f){ print $1,$2, $o > "file_"f[o]".csv" } } ' file
output
$ cat file_L1.csv
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
$ cat file_L2.csv
EXAMPLEfoo,60,0
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,0
EXAMPLE3,60,6
EXAMPLE4,30,6
A:
Have a look at perl module Text::CSV_XS - comma-separated values manipulation routines. I found this module very helpful while manipulating with CSV files.
A:
In Python, slightly hacky and untested, but should do the job:
import csv
r = csv.reader(open(r'file.csv'), dialect='excel')
topline = r.next()
headerline = r.next()
lastcell = ''
for i, cell in enumerate(topline): #Copy cells forwards in the top line, so L1 for example goes across all cells
if cell == '':
topline[i] = lastcell
else:
lastcell = cell
for i in range(len(headerline)): #Copy the topline cells into the header line, so the headerline cells should be unique
headerline[i] = '-'.join((topline[i], headerline[i]))
rows = [dict(zip(headerline, line)) for line in r]
# Rows should now consist of dicts of the form {'Title': 'EXAMPLEfoo', 'r/t': '60', 'L1-needed': '6' ...}
for lval in frozenset(topline): #Use frozenset to ensure we only have unique values.
if lval != '': #Make sure we don't look at the blank value
w = csv.writer(open(r'%s.csv' % lval, 'w'), dialect='excel')
for row in rows:
line = [row['Title'], row['r/t'], row['-'.join((lval, 'needed'))]]
w.writerow(line)
|
Creating multiple csv files from data within a csv file
|
System OSX or Linux
I'm trying to automate my work flow at work, each week I receive an excel file, which I convert to a csv.
An example is:
,,L1,,,L2,,,L3,,,L4,,,L5,,,L6,,,L7,,,L8,,,L9,,,L10,,,L11,
Title,r/t,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,neede d,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst,needed,actual,Inst
EXAMPLEfoo,60,6,6,6,0,0,0,0,0,0,6,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EXAMPLEbar,30,6,6,12,6,7,14,6,6,12,6,6,12,6,8,16,6,7,14,6,7.5,15,6,6,12,6,8,16,6,0,0,6,7,14
EXAMPLE1,60,3,3,3,3,5,5,3,4,4,3,3,3,3,6,6,3,4,4,3,3,3,3,4,4,3,8,8,3,0,0,3,4,4
EXAMPLE2,120,6,6,3,0,0,0,6,8,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
EXAMPLE3,60,6,6,6,6,8,8,6,6,6,6,6,6,0,0,0,0,0,0,6,8,8,6,6,6,0,0,0,0,0,0,0,10,10
EXAMPLE4,30,6,6,12,6,7,14,6,6,12,6,6,12,3,5.5,11,6,7.5,15,6,6,12,6,0,0,6,9,18,6,0,0,6,6.5,13
And so you can get a picture of how it looks in excel:
What I need to do, is create multiple csv files for each instance in row 1, so L1, L2, L3, L4...
And within that each csv file it needs to contain the title, r/t, needed
So for L1 an example out put would look like:
EXAMPLEfoo,60,6
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,6
EXAMPLE3,60,6
EXAMPLE4,30,6
And for L2:
EXAMPLEfoo,60,0
EXAMPLEbar,30,6
EXAMPLE1,60,3
EXAMPLE2,120,0
EXAMPLE3,60,6
EXAMPLE4,30,6
And so on.
I have tried playing around with sed and awk and hit google but I have found nothing that really solves the issue.
I'd imagine perl would be particular suited to this or maybe python, so I would be more than happy to accept suggestions from users.
So, any suggestions?
Thanks in advance.
|
[
"Perl \"one-liner\"\nperl -MText::CSV_XS -e'$c=Text::CSV_XS->new({binary=>1,eol=>\"\\n\"});%a=map{$i++;/^L\\d+$/?($_=>$i):()}@{$c->getline(*ARGV)};open$b{$_},\">$_\"for keys%a;while($f=$c->getline(*ARGV)){$c->print($b{$_},[@$f[0,1,$a{$_}]])for keys%a}'\n\nFor ones which have problem with reading:\n$ echo '$c=Te...' | perltidy\n$c = Text::CSV_XS->new( { binary => 1, eol => \"\\n\" } );\n%a = map { $i++; /^L\\d+$/ ? ( $_ => $i ) : () } @{ $c->getline(*ARGV) };\nopen $b{$_}, \">$_\" for keys %a;\nwhile ( $f = $c->getline(*ARGV) ) {\n $c->print( $b{$_}, [ @$f[ 0, 1, $a{$_} ] ] )\n for keys %a;\n}\n\n",
"Using only AWK:\nawk -F, -vOFS=, -vc=1 '\n NR == 1 {\n for (i=1; i<NF; i++) {\n if ($i != \"\") {\n g[c]=i;\n f[c++]=$i\n }\n }\n }\n NR>2 {\n for (i=1; i < c; i++) {\n print $1,$2, $g[i] > \"output_\"f[i]\".csv\"\n }\n }' data.csv\n\nAs a one-liner:\nawk -F, -vOFS=, -vc=1 'NR == 1 {for (i=1; i<NF; i++) {if ($i != \"\") {g[c]=i; f[c++]=$i}}} NR>2 { for (i=1; i < c; i++) {print $1,$2, $g[i] > \"file_\"f[i]\".csv\" }}' data.csv\n\nExample output:\n$ cat file_L1.csv\nEXAMPLEfoo,60,6\nEXAMPLEbar,30,6\nEXAMPLE1,60,3\nEXAMPLE2,120,6\nEXAMPLE3,60,6\nEXAMPLE4,30,6\n$ cat file_L2.csv\nEXAMPLEfoo,60,0\nEXAMPLEbar,30,6\nEXAMPLE1,60,3\nEXAMPLE2,120,0\nEXAMPLE3,60,6\nEXAMPLE4,30,6\n$ cat file_L11.csv\nEXAMPLEfoo,60,0\nEXAMPLEbar,30,6\nEXAMPLE1,60,3\nEXAMPLE2,120,0\nEXAMPLE3,60,0\nEXAMPLE4,30,6\n\n",
"use strict;\nuse warnings;\n\nuse Text::CSV;\nmy $csv = Text::CSV->new;\n\nsub parse_line {\n $csv->parse(shift) or die $!;\n return $csv->fields;\n}\n\nmy @metadata;\nmy @files = parse_line(scalar <>);\nmy @header = parse_line(scalar <>); # Ignore.\nfor my $i (0 .. $#files){\n next unless length $files[$i];\n open(my $h, '>', \"$files[$i].csv\") or die $!;\n push @metadata, {column => $i, handle => $h};\n}\n\nwhile (my $line = <>){\n my @fields = parse_line($line);\n for my $m (@metadata){\n $csv->print($m->{handle}, [ @fields[0, 1, $m->{column}] ]);\n print {$m->{handle}} \"\\n\";\n }\n}\n\n",
"try this\n#!/bin/bash\nawk 'BEGIN{ OFS=FS=\",\" }\nNR==1{\n for(i=1;i<=NF;i++){\n if($i){ f[i]=$i }\n }\n}\nNR>2{ for(o in f){ print $1,$2, $o > \"file_\"f[o]\".csv\" } } ' file\n\noutput\n$ cat file_L1.csv\nEXAMPLEfoo,60,6\nEXAMPLEbar,30,6\nEXAMPLE1,60,3\nEXAMPLE2,120,6\nEXAMPLE3,60,6\nEXAMPLE4,30,6\n\n$ cat file_L2.csv\nEXAMPLEfoo,60,0\nEXAMPLEbar,30,6\nEXAMPLE1,60,3\nEXAMPLE2,120,0\nEXAMPLE3,60,6\nEXAMPLE4,30,6\n\n",
"Have a look at perl module Text::CSV_XS - comma-separated values manipulation routines. I found this module very helpful while manipulating with CSV files.\n",
"In Python, slightly hacky and untested, but should do the job:\nimport csv\nr = csv.reader(open(r'file.csv'), dialect='excel')\ntopline = r.next()\nheaderline = r.next()\n\nlastcell = ''\nfor i, cell in enumerate(topline): #Copy cells forwards in the top line, so L1 for example goes across all cells\n if cell == '':\n topline[i] = lastcell\n else:\n lastcell = cell\n\nfor i in range(len(headerline)): #Copy the topline cells into the header line, so the headerline cells should be unique\n headerline[i] = '-'.join((topline[i], headerline[i]))\n\nrows = [dict(zip(headerline, line)) for line in r]\n\n# Rows should now consist of dicts of the form {'Title': 'EXAMPLEfoo', 'r/t': '60', 'L1-needed': '6' ...}\n\nfor lval in frozenset(topline): #Use frozenset to ensure we only have unique values.\n if lval != '': #Make sure we don't look at the blank value\n w = csv.writer(open(r'%s.csv' % lval, 'w'), dialect='excel')\n for row in rows:\n line = [row['Title'], row['r/t'], row['-'.join((lval, 'needed'))]]\n w.writerow(line)\n\n"
] |
[
3,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"awk",
"bash",
"perl",
"python",
"sed"
] |
stackoverflow_0002621549_awk_bash_perl_python_sed.txt
|
Q:
Python ReportLab use of splitfirst/splitlast
I'm trying to use Python with ReportLab 2.2 to create a PDF report.
According to the user guide,
Special TableStyle Indeces [sic]
In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.
I've tried using several style elements, including:
('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
and none of these seems to work. The first generates a TypeError with the message:
TypeError: cannot concatenate 'str' and 'int' objects
and the latter two generate TypeErrors with the message:
TypeError: an integer is required
Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?
A:
Well, it looks as if I will be answering my own question.
First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.
My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.
However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:
class XTable(Table):
def onSplit(self, T, byRow=1):
T.setStyle(TableStyle([
('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))
What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.
A:
This seems to be a bug in the ReportLab Table class. Another fix for this in addition to DLJessup's own answer is to modify the ReportLab code that's causing the error, in Table._drawBkgrnd(), around line 1301. For 'splitlast', change:
y0 = rowpositions[sr]
to:
if sr == 'splitlast':
y0 = rowpositions[-2] # last value is 0. Second last is the one we want.
else:
y0 = rowpositions[sr]
This is easily done in your own code without hacking ReportLab by subclassing Table and overwriting this method. I've not had need to use 'splitfirst'; if I do I'll post the rest of the hack here.
A:
[...] In any style command the first row
index may be set to one of the special strings [...]
In your first example you're setting the second row index to a special string as well.
Not sure why the other two don't work... Are you sure this is where the exception is coming from?
|
Python ReportLab use of splitfirst/splitlast
|
I'm trying to use Python with ReportLab 2.2 to create a PDF report.
According to the user guide,
Special TableStyle Indeces [sic]
In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.
I've tried using several style elements, including:
('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black)
('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black)
and none of these seems to work. The first generates a TypeError with the message:
TypeError: cannot concatenate 'str' and 'int' objects
and the latter two generate TypeErrors with the message:
TypeError: an integer is required
Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?
|
[
"Well, it looks as if I will be answering my own question.\nFirst, the documentation flat out lies where it reads \"In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation.\" In the current release, the \"splitlast\" and \"splitfirst\" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.\nMy suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.\nHowever, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:\nclass XTable(Table):\n def onSplit(self, T, byRow=1):\n T.setStyle(TableStyle([\n ('TEXTCOLOR', (0, 1), (1, 1), colors.black)]))\n\nWhat this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.\n",
"This seems to be a bug in the ReportLab Table class. Another fix for this in addition to DLJessup's own answer is to modify the ReportLab code that's causing the error, in Table._drawBkgrnd(), around line 1301. For 'splitlast', change:\ny0 = rowpositions[sr]\n\nto: \nif sr == 'splitlast':\n y0 = rowpositions[-2] # last value is 0. Second last is the one we want.\nelse:\n y0 = rowpositions[sr]\n\nThis is easily done in your own code without hacking ReportLab by subclassing Table and overwriting this method. I've not had need to use 'splitfirst'; if I do I'll post the rest of the hack here.\n",
"\n[...] In any style command the first row\n index may be set to one of the special strings [...]\n\nIn your first example you're setting the second row index to a special string as well.\nNot sure why the other two don't work... Are you sure this is where the exception is coming from?\n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"python",
"reportlab"
] |
stackoverflow_0000078450_python_reportlab.txt
|
Q:
Can't import obj in Python on OS X 10.6.3 Snow Leopard - libiconv.2.dylib?
on OS X 10.6.3 Snow Leopard
% python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import objc
Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/__init__.py", line 22, in
_update()
File "/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/__init__.py", line 19, in _update
import _objc
ImportError: dlopen(/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/_objc.so, 2): Library not loaded: /opt/local/lib/libiconv.2.dylib
Referenced from: /Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/_objc.so
Reason: Incompatible library version: _objc.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0
>>>
--
what do I need to do?
A:
First I'd try to temporary move /Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/ to somewhere else and try the import statement again. This will enable the OS to import the version of objc that came with the OS by default (this is in /System/Library). By using the version in /System/Library, it works for me:
>>> import objc
>>> print objc.__file__
/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/objc/__init__.pyc
You might also consider moving /opt/local/lib/libiconv.2.dylib to somewhere else. It looks outdated and OS X Snow Leopard has its own copy of libiconv.2.dylib in /usr/lib IIRC.
|
Can't import obj in Python on OS X 10.6.3 Snow Leopard - libiconv.2.dylib?
|
on OS X 10.6.3 Snow Leopard
% python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import objc
Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/__init__.py", line 22, in
_update()
File "/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/__init__.py", line 19, in _update
import _objc
ImportError: dlopen(/Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/_objc.so, 2): Library not loaded: /opt/local/lib/libiconv.2.dylib
Referenced from: /Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/objc/_objc.so
Reason: Incompatible library version: _objc.so requires version 8.0.0 or later, but libiconv.2.dylib provides version 7.0.0
>>>
--
what do I need to do?
|
[
"First I'd try to temporary move /Library/Python/2.6/site-packages/pyobjc_core-2.2-py2.6-macosx-10.6-universal.egg/ to somewhere else and try the import statement again. This will enable the OS to import the version of objc that came with the OS by default (this is in /System/Library). By using the version in /System/Library, it works for me:\n>>> import objc\n>>> print objc.__file__ \n/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC/objc/__init__.pyc\n\nYou might also consider moving /opt/local/lib/libiconv.2.dylib to somewhere else. It looks outdated and OS X Snow Leopard has its own copy of libiconv.2.dylib in /usr/lib IIRC.\n"
] |
[
2
] |
[
"You more than likely screwed with the OS's Python installation, so you'll more than likely need to reinstall your OS. \n"
] |
[
-3
] |
[
"osx_snow_leopard",
"pyobjc",
"python"
] |
stackoverflow_0002624100_osx_snow_leopard_pyobjc_python.txt
|
Q:
Deleting rows in a text file
A sample of the following text file i have is:
> 1 -4.6 -4.6 -7.6
>
> 2 -1.7 -3.8 -3.1
>
> 3 -1.6 -1.6 -3.1
the data is separated by tabs in the text file and the first column indicates the position.
I need to iterate through every value in the text file apart from column 0 and find the lowest value.
once the lowest value has been found that value needs to be written to a new text file along with the column name and position. Column 0 has the name "position" Column 1 "fifteen", column 2 "sixteen" and column 3 "seventeen"
for example the lowest value in the above data is "-7.6" and is in column 3 which has the name "seventeen". Therefore "7.6", "seventeen" and its position value which in this case is 1 need to be written to the new text file.
I then need a number of rows deleted from the above text file.
E.G. the lowest value above is "-7.6" and is found at position "1" and is found in column 3 which as the name "seventeen". I therefore need seventeen rows deleted from the text file starting from and including position 1
so the the column in which the lowest value is found denotes the amount of rows that needs to be deleted and the position it is found at states the start point of the deletion
A:
Open this file for reading, another file for writing, and copy all the lines that don't match the filter:
readfile = open('somefile', 'r')
writefile = open('otherfile', 'w')
for line in readfile:
if not somepredicate(line):
writefile.write(line)
readfile.close()
writefile.close()
A:
Here's a stab at what I think you wanted (though your requirements were kind of difficult to follow):
def extract_bio_data(input_path, output_path):
#open the output file and write it's headers
output_file = open(output_path, 'w')
output_file.write('\t'.join(('position', 'min_value', 'rows_skipped')) + '\n')
#map column indexes (after popping the row number) to the number of rows to skip
col_index = { 0: 15,
1: 16,
2: 17 }
skip_to_position = 0
for line in open(input_path, 'r'):
#remove the '> ' from the beginning of the line and strip newline characters off the end
line = line[2:].strip()
#if the line contains no data, skip it
if line == '':
continue
#split the columns on whitespace (change this to split('\t') for splitting only on tabs)
columns = line.split()
#extract the row number/position of this data
position = int(columns.pop(0))
#this is where we skip rows/positions
if position < skip_to_position:
continue
#if two columns share the minimum value, this will be the first encountered in the list
min_index = columns.index(min(columns, key=float))
#this is an integer version of the 'column name' which corresponds to the number of rows that need to be skipped
rows_to_skip = col_index[min_index]
#write data to your new file (row number, minimum value, number of rows skipped)
output_file.write('\t'.join(str(x) for x in (position, columns[min_index], rows_to_skip)) + '\n')
#set the number of data rows to skip from this position
skip_to_position = position + rows_to_skip
if __name__ == '__main__':
in_path = r'c:\temp\test_input.txt'
out_path = r'c:\temp\test_output.txt'
extract_bio_data(in_path, out_path)
Things that weren't clear to me:
Is there really "> " at the beginning of each line or is that a copy/paste error?
I assumed it wasn't an error.
Did you want "7.6" or "-7.6" written to the new file?
I assumed you wanted the original value.
Did you want to skip rows in the file? or positions based on the first column?
I assumed you wanted to skip positions.
You say you want to delete data from the original file.
I assumed that skipping positions was sufficient.
|
Deleting rows in a text file
|
A sample of the following text file i have is:
> 1 -4.6 -4.6 -7.6
>
> 2 -1.7 -3.8 -3.1
>
> 3 -1.6 -1.6 -3.1
the data is separated by tabs in the text file and the first column indicates the position.
I need to iterate through every value in the text file apart from column 0 and find the lowest value.
once the lowest value has been found that value needs to be written to a new text file along with the column name and position. Column 0 has the name "position" Column 1 "fifteen", column 2 "sixteen" and column 3 "seventeen"
for example the lowest value in the above data is "-7.6" and is in column 3 which has the name "seventeen". Therefore "7.6", "seventeen" and its position value which in this case is 1 need to be written to the new text file.
I then need a number of rows deleted from the above text file.
E.G. the lowest value above is "-7.6" and is found at position "1" and is found in column 3 which as the name "seventeen". I therefore need seventeen rows deleted from the text file starting from and including position 1
so the the column in which the lowest value is found denotes the amount of rows that needs to be deleted and the position it is found at states the start point of the deletion
|
[
"Open this file for reading, another file for writing, and copy all the lines that don't match the filter:\nreadfile = open('somefile', 'r')\nwritefile = open('otherfile', 'w')\n\nfor line in readfile:\n if not somepredicate(line):\n writefile.write(line)\n\nreadfile.close()\nwritefile.close()\n\n",
"Here's a stab at what I think you wanted (though your requirements were kind of difficult to follow):\ndef extract_bio_data(input_path, output_path):\n #open the output file and write it's headers\n output_file = open(output_path, 'w')\n output_file.write('\\t'.join(('position', 'min_value', 'rows_skipped')) + '\\n')\n\n #map column indexes (after popping the row number) to the number of rows to skip\n col_index = { 0: 15, \n 1: 16, \n 2: 17 }\n\n skip_to_position = 0\n for line in open(input_path, 'r'):\n #remove the '> ' from the beginning of the line and strip newline characters off the end\n line = line[2:].strip()\n\n #if the line contains no data, skip it\n if line == '':\n continue\n\n #split the columns on whitespace (change this to split('\\t') for splitting only on tabs)\n columns = line.split()\n\n #extract the row number/position of this data\n position = int(columns.pop(0))\n\n #this is where we skip rows/positions\n if position < skip_to_position: \n continue\n\n #if two columns share the minimum value, this will be the first encountered in the list\n min_index = columns.index(min(columns, key=float))\n\n #this is an integer version of the 'column name' which corresponds to the number of rows that need to be skipped\n rows_to_skip = col_index[min_index]\n\n #write data to your new file (row number, minimum value, number of rows skipped)\n output_file.write('\\t'.join(str(x) for x in (position, columns[min_index], rows_to_skip)) + '\\n')\n\n #set the number of data rows to skip from this position\n skip_to_position = position + rows_to_skip\n\n\nif __name__ == '__main__':\n in_path = r'c:\\temp\\test_input.txt'\n out_path = r'c:\\temp\\test_output.txt'\n extract_bio_data(in_path, out_path)\n\nThings that weren't clear to me:\n\nIs there really \"> \" at the beginning of each line or is that a copy/paste error?\n\n\nI assumed it wasn't an error.\n\nDid you want \"7.6\" or \"-7.6\" written to the new file?\n\n\nI assumed you wanted the original value.\n\nDid you want to skip rows in the file? or positions based on the first column?\n\n\nI assumed you wanted to skip positions.\n\nYou say you want to delete data from the original file.\n\n\nI assumed that skipping positions was sufficient.\n\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"text_files"
] |
stackoverflow_0002623475_python_text_files.txt
|
Q:
Serialize Dictionary with a string key and List[] value to JSON
How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])
if request.is_ajax() and request.method == 'GET':
groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"]))
groups = groupSet.groups.all()
group_items = [] #list
groups_and_items = {} #dictionary
for group in groups:
group_items.extend([group_item for group_item in group.group_items.all()])
#use group as Key name and group_items (LIST) as the value
groups_and_items[group] = group_items
data = serializers.serialize("json", groups_and_items)
return HttpResponse(data, mimetype="application/json")
the result:
[{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}]
while the group_items should have many group_item and each group_item should have "name", rather than only the Id, in this case the Id is 13.
I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to javascript.
I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)
A:
Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.
import json
groups_and_items = {}
for group in groups:
group_items = []
for item in group.group_items.all():
group_items.append( {'id': item.id, 'name': item.name} )
# <OR> if you just want a list of the group_item names
#group_items = group.group_items.all().values_list('name', flat=True)
groups_and_items[group.name] = group_items
data = json.dumps(groups_and_items)
What exactly did you want you want your data to look like? The above should give you data like this :
[{ 'groupA': [{'id': 1, 'name': 'item-1'}],
'groupB': [{'id': 2, 'name': 'item-2'}, ...],
'groupC': []
}]
Or this if you just want the list of group_item names:
[{ 'groupA': ['item-1'],
'groupB': ['item-2', ...],
'groupC': []
}]
A:
You should use Python's json module to encode your JSON.
Also, what indentation level do you have data = serializers at? It looks like it could be inside the for loop?
|
Serialize Dictionary with a string key and List[] value to JSON
|
How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. [])
if request.is_ajax() and request.method == 'GET':
groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"]))
groups = groupSet.groups.all()
group_items = [] #list
groups_and_items = {} #dictionary
for group in groups:
group_items.extend([group_item for group_item in group.group_items.all()])
#use group as Key name and group_items (LIST) as the value
groups_and_items[group] = group_items
data = serializers.serialize("json", groups_and_items)
return HttpResponse(data, mimetype="application/json")
the result:
[{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}]
while the group_items should have many group_item and each group_item should have "name", rather than only the Id, in this case the Id is 13.
I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to javascript.
I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)
|
[
"Your 'groups' variable is a QuerySet object, not a dict. You will want to be more explicit with the data that you want to return.\nimport json\ngroups_and_items = {}\nfor group in groups:\n group_items = []\n for item in group.group_items.all():\n group_items.append( {'id': item.id, 'name': item.name} )\n # <OR> if you just want a list of the group_item names\n #group_items = group.group_items.all().values_list('name', flat=True) \n groups_and_items[group.name] = group_items\ndata = json.dumps(groups_and_items)\n\nWhat exactly did you want you want your data to look like? The above should give you data like this :\n[{ 'groupA': [{'id': 1, 'name': 'item-1'}],\n 'groupB': [{'id': 2, 'name': 'item-2'}, ...],\n 'groupC': []\n}]\n\nOr this if you just want the list of group_item names:\n[{ 'groupA': ['item-1'],\n 'groupB': ['item-2', ...],\n 'groupC': []\n}]\n\n",
"You should use Python's json module to encode your JSON.\nAlso, what indentation level do you have data = serializers at? It looks like it could be inside the for loop?\n"
] |
[
1,
0
] |
[] |
[] |
[
"ajax",
"django",
"json",
"python",
"serialization"
] |
stackoverflow_0002622866_ajax_django_json_python_serialization.txt
|
Q:
Installing Django/Python on IIS6
We are currently installing the latest version of Django and Python on IIS6. We have followed the instructions on the following site:
http://code.djangoproject.com/wiki/DjangoOnWindowsWithIISAndSQLServer
We are receiving a 403 error when trying to access our Django application via the IIS server.
We have verified the python installation on IIS6 and it is working properly.
We have also verified the Django installation. Our application runs fine under the built-in Django server, but we are having difficulties getting it to run under IIS.
We presume we could be getting errors from "Linking Django to PyISAPIe" section of the instructions provided on the link above.
Thanks.
A:
Did you create a separate Application Pool to run PyISAPI (i.e. not the DefaultAppPool)? If so, what user/group does the pool run under? It's possible that you need to assign that user the proper rights. For example, see this page:
http://support.asimo.nl/activekb/questions.php?questionid=6
UPDATE: Here's another link with more detailed steps to check that your user permissions are set correctly:
http://forum.dotnetpanel.com/forums/t/602.aspx
|
Installing Django/Python on IIS6
|
We are currently installing the latest version of Django and Python on IIS6. We have followed the instructions on the following site:
http://code.djangoproject.com/wiki/DjangoOnWindowsWithIISAndSQLServer
We are receiving a 403 error when trying to access our Django application via the IIS server.
We have verified the python installation on IIS6 and it is working properly.
We have also verified the Django installation. Our application runs fine under the built-in Django server, but we are having difficulties getting it to run under IIS.
We presume we could be getting errors from "Linking Django to PyISAPIe" section of the instructions provided on the link above.
Thanks.
|
[
"Did you create a separate Application Pool to run PyISAPI (i.e. not the DefaultAppPool)? If so, what user/group does the pool run under? It's possible that you need to assign that user the proper rights. For example, see this page:\nhttp://support.asimo.nl/activekb/questions.php?questionid=6\nUPDATE: Here's another link with more detailed steps to check that your user permissions are set correctly:\nhttp://forum.dotnetpanel.com/forums/t/602.aspx\n"
] |
[
0
] |
[] |
[] |
[
"django",
"iis_6",
"linker",
"pyisapie",
"python"
] |
stackoverflow_0002624343_django_iis_6_linker_pyisapie_python.txt
|
Q:
What's the __repr__ equivalence in ruby?
The __repr__ function of python is fancy as it is called when print OBJECT is used automatically.
Is there a ruby equivalence for it? I thought it was to_s, but, I had p OBJECT doesn't seem to call the to_s method.
Added
I got something wrong, p OBJECT seems to call to_s method as follows.
I got some hints from my the answers to my other question. - Ruby's to_s method question (from Axe book 2nd edition)
# Sample code from Programing Ruby, page 24
class Song
def to_s
"Song"
end
end
class Songson < Song
def to_s
super + "<Songson>"
end
end
song = Songson.new()
p song
A:
obj.inspect => string
Returns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.
[ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]"
Time.new.inspect #=> "Wed Apr 09 08:54:39 CDT 2003"
obj.to_s => string
Returns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘
source
A:
p object uses #inspect.
|
What's the __repr__ equivalence in ruby?
|
The __repr__ function of python is fancy as it is called when print OBJECT is used automatically.
Is there a ruby equivalence for it? I thought it was to_s, but, I had p OBJECT doesn't seem to call the to_s method.
Added
I got something wrong, p OBJECT seems to call to_s method as follows.
I got some hints from my the answers to my other question. - Ruby's to_s method question (from Axe book 2nd edition)
# Sample code from Programing Ruby, page 24
class Song
def to_s
"Song"
end
end
class Songson < Song
def to_s
super + "<Songson>"
end
end
song = Songson.new()
p song
|
[
" obj.inspect => string\n\nReturns a string containing a human-readable representation of obj. If not overridden, uses the to_s method to generate the string.\n [ 1, 2, 3..4, 'five' ].inspect #=> \"[1, 2, 3..4, \\\"five\\\"]\"\n Time.new.inspect #=> \"Wed Apr 09 08:54:39 CDT 2003\"\n\n\n obj.to_s => string\n\nReturns a string representing obj. The default to_s prints the object‘s class and an encoding of the object id. As a special case, the top-level object that is the initial execution context of Ruby programs returns ``main.’‘\nsource\n",
"p object uses #inspect.\n"
] |
[
17,
3
] |
[] |
[] |
[
"python",
"ruby"
] |
stackoverflow_0002625132_python_ruby.txt
|
Q:
Python soap using soaplib (server) and suds (client)
This question is related to:
Python SOAP server / client
In the case of soap with python, there are recommendation to use soaplib (http://wiki.github.com/jkp/soaplib) as soap server and suds (https://fedorahosted.org/suds/) as soap client.
My target is to create soap services in python that can be consumed by several clients (java, etc).
I tried the HelloWorld example from soaplib (http://trac.optio.webfactional.com/wiki/HelloWorld).
It works well when the client is also using soaplib.
Then, I tried to use suds as client consuming the HelloWorld services and it fail.
-Why this is happening? Does soaplib server has problems to consumed by different clients?
Here the code for the server:
from soaplib.wsgi_soap import SimpleWSGISoapApp
from soaplib.service import soapmethod
from soaplib.serializers.primitive import String, Integer, Arraycode
class HelloWorldService(SimpleWSGISoapApp):
@soapmethod(String,Integer,_returns=Array(String))
def say_hello(self,name,times):
results = []
for i in range(0,times):
results.append('Hello, %s'%name)
return results
if __name__=='__main__':
from cherrypy.wsgiserver import CherryPyWSGIServer
#from cherrypy._cpwsgiserver import CherryPyWSGIServer
# this example uses CherryPy2.2, use cherrypy.wsgiserver.CherryPyWSGIServer for CherryPy 3.0
server = CherryPyWSGIServer(('localhost',7789),HelloWorldService())
server.start()
This is the soaplib client:
from soaplib.client import make_service_client
from SoapServerTest_1 import HelloWorldService
client = make_service_client('http://localhost:7789/',HelloWorldService())
print client.say_hello("Dave",5)
Results:
>>> ['Hello, Dave', 'Hello, Dave', 'Hello, Dave', 'Hello, Dave', 'Hello, Dave']
This is the suds client:
from suds.client import Client
url = 'http://localhost:7789/HelloWordService?wsdl'
client1 = Client(url)
client1.service.say_hello("Dave",5)
Results:
>>> Unhandled exception while debugging...
Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\RTEP\Sequencing\SoapClientTest_1.py", line 10, in <module>
client1.service.say_hello("Dave",5)
File "c:\python25\lib\site-packages\suds\client.py", line 537, in __call__
return client.invoke(args, kwargs)
File "c:\python25\lib\site-packages\suds\client.py", line 597, in invoke
result = self.send(msg)
File "c:\python25\lib\site-packages\suds\client.py", line 626, in send
result = self.succeeded(binding, reply.message)
File "c:\python25\lib\site-packages\suds\client.py", line 658, in succeeded
r, p = binding.get_reply(self.method, reply)
File "c:\python25\lib\site-packages\suds\bindings\binding.py", line 158, in get_reply
result = unmarshaller.process(nodes[0], resolved)
File "c:\python25\lib\site-packages\suds\umx\typed.py", line 66, in process
return Core.process(self, content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 48, in process
return self.append(content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 63, in append
self.append_children(content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 140, in append_children
cval = self.append(cont)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 61, in append
self.start(content)
File "c:\python25\lib\site-packages\suds\umx\typed.py", line 77, in start
found = self.resolver.find(content.node)
File "c:\python25\lib\site-packages\suds\resolver.py", line 341, in find
frame = Frame(result, resolved=known, ancestry=ancestry)
File "c:\python25\lib\site-packages\suds\resolver.py", line 473, in __init__
resolved = type.resolve()
File "c:\python25\lib\site-packages\suds\xsd\sxbasic.py", line 63, in resolve
raise TypeNotFound(qref)
TypeNotFound: Type not found: '(string, HelloWorldService.HelloWorldService, )'
A:
try to import primitives into your class:
class HelloWorldService(SimpleWSGISoapApp):
from soaplib.serializers.primitive import String, Integer, Arraycode
@soapmethod(String,Integer,_returns=Array(String))
A:
this bug is fixed if you get the latest sources from the trunk, see https://github.com/soaplib/soaplib/pull/12 for details
|
Python soap using soaplib (server) and suds (client)
|
This question is related to:
Python SOAP server / client
In the case of soap with python, there are recommendation to use soaplib (http://wiki.github.com/jkp/soaplib) as soap server and suds (https://fedorahosted.org/suds/) as soap client.
My target is to create soap services in python that can be consumed by several clients (java, etc).
I tried the HelloWorld example from soaplib (http://trac.optio.webfactional.com/wiki/HelloWorld).
It works well when the client is also using soaplib.
Then, I tried to use suds as client consuming the HelloWorld services and it fail.
-Why this is happening? Does soaplib server has problems to consumed by different clients?
Here the code for the server:
from soaplib.wsgi_soap import SimpleWSGISoapApp
from soaplib.service import soapmethod
from soaplib.serializers.primitive import String, Integer, Arraycode
class HelloWorldService(SimpleWSGISoapApp):
@soapmethod(String,Integer,_returns=Array(String))
def say_hello(self,name,times):
results = []
for i in range(0,times):
results.append('Hello, %s'%name)
return results
if __name__=='__main__':
from cherrypy.wsgiserver import CherryPyWSGIServer
#from cherrypy._cpwsgiserver import CherryPyWSGIServer
# this example uses CherryPy2.2, use cherrypy.wsgiserver.CherryPyWSGIServer for CherryPy 3.0
server = CherryPyWSGIServer(('localhost',7789),HelloWorldService())
server.start()
This is the soaplib client:
from soaplib.client import make_service_client
from SoapServerTest_1 import HelloWorldService
client = make_service_client('http://localhost:7789/',HelloWorldService())
print client.say_hello("Dave",5)
Results:
>>> ['Hello, Dave', 'Hello, Dave', 'Hello, Dave', 'Hello, Dave', 'Hello, Dave']
This is the suds client:
from suds.client import Client
url = 'http://localhost:7789/HelloWordService?wsdl'
client1 = Client(url)
client1.service.say_hello("Dave",5)
Results:
>>> Unhandled exception while debugging...
Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\RTEP\Sequencing\SoapClientTest_1.py", line 10, in <module>
client1.service.say_hello("Dave",5)
File "c:\python25\lib\site-packages\suds\client.py", line 537, in __call__
return client.invoke(args, kwargs)
File "c:\python25\lib\site-packages\suds\client.py", line 597, in invoke
result = self.send(msg)
File "c:\python25\lib\site-packages\suds\client.py", line 626, in send
result = self.succeeded(binding, reply.message)
File "c:\python25\lib\site-packages\suds\client.py", line 658, in succeeded
r, p = binding.get_reply(self.method, reply)
File "c:\python25\lib\site-packages\suds\bindings\binding.py", line 158, in get_reply
result = unmarshaller.process(nodes[0], resolved)
File "c:\python25\lib\site-packages\suds\umx\typed.py", line 66, in process
return Core.process(self, content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 48, in process
return self.append(content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 63, in append
self.append_children(content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 140, in append_children
cval = self.append(cont)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 61, in append
self.start(content)
File "c:\python25\lib\site-packages\suds\umx\typed.py", line 77, in start
found = self.resolver.find(content.node)
File "c:\python25\lib\site-packages\suds\resolver.py", line 341, in find
frame = Frame(result, resolved=known, ancestry=ancestry)
File "c:\python25\lib\site-packages\suds\resolver.py", line 473, in __init__
resolved = type.resolve()
File "c:\python25\lib\site-packages\suds\xsd\sxbasic.py", line 63, in resolve
raise TypeNotFound(qref)
TypeNotFound: Type not found: '(string, HelloWorldService.HelloWorldService, )'
|
[
"try to import primitives into your class:\nclass HelloWorldService(SimpleWSGISoapApp):\n from soaplib.serializers.primitive import String, Integer, Arraycode\n @soapmethod(String,Integer,_returns=Array(String))\n\n",
"this bug is fixed if you get the latest sources from the trunk, see https://github.com/soaplib/soaplib/pull/12 for details\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"soap",
"suds"
] |
stackoverflow_0001992239_python_soap_suds.txt
|
Q:
How do I prepare myself for a summer of working on Python using Linux environment?
I have used just Windows for programming so far. Now, I have an internship starting in two weeks and I will be using just Linux environment with Python programming language. I've installed Ubuntu on my system but have no exposure to shell scripting.
I need some advice on how I can quickly learn to use the Linux terminal quickly. Any books or web resources that you can suggest?
Also, is there a particular IDE that is generally preferred for Python programming on Linux, or is Vim preferred? How can I best prepare myself for the internship ahead?
Thanks for taking the time.
A:
As an intern you'll want to use the tools your mentor is most comfortable with. If you get stuck you'll be able to ask for advice quickly.
Learning your way around either vi, vim, or emacs to start with will help. The basic concepts used in one will transfer to the other. You'll need to be able to open and read files, search through files, edit and save files, and learn how to apply any python formatting helpers correctly.
You should also familiarize yourself with version control if you haven't already. Again any one will do, you need to focus on concepts and etiquette rather than the specific tool.
The goal of the internship (and really your entire time at university) should be used to learn concepts rather than specific tools. If you learn the concepts you'll be well placed to apply those concepts using any tool. You will also "learn how to learn" a new tool, which is really valuable.
A:
Your lack of shell scripting knowledge shouldn't matter in this case, although it won't be hard to learn. I read over some shell tutorials and put them into practice. Try doing everything from the command line, including find (grep), find/replace all (sed), finding files (find), automating things using python scripts etc. Basically, don't cheat. You'll pick up a lot this way. You'll also probably end up wondering how you ever managed with Windows.
What I use depends on the project. I really like Eclipse+PyDev but that's my personal preference, I also use Vim depending on where I am/what I'm doing. Remember you can just type python from the command line and it drops you into the python environment.
A:
I recommend Eclipse + PyDev too. You can get started quickly with this develop environment. I also recommend the website Dive Into Python. It provides you a online free version of Dive Into Python book, which is very easy to read, easy to understand, and very suitable for Python beginners. If you really want a paper book at hand, Learning Python, a.k.a. The Animal Guide, is simply the best.
A:
Learn to understand man(ual) pages.
For almost any old linux command/program there is a man page which usually explains the command in good detail.
So basics for filesystem navigation:
Show directory contents (list)
ls
Show hidden files
ls -a
Show details
ls -l
Change directory
cd /full/path/name
Print current directory
pwd
Delete a file
rm file
Delete a directory (recursive)
rm -r directoryName
Make a directory
mkdir directoryName
Move (or rename) a file
mv /path/to/file /new/path/to/file
Show the man page for mv
man mv
Learning vim might be necessary, depending on your intern environment. I do my Python (and everything that isn't simple text editing) in Eclipse. You should in any case learn enough to open a file, makes some changes and save the changes in Vim.
Keep in mind, Ubuntu is very easy. To make things harder on yourself, use the command line for every conceivable thing. Open programs by typing their names into a terminal. Browse your files with the terminal. Do simple editing with vim. That should provide good practice for the day you need to SSH into a computer in Neverland and download and install a local copy of your favorite interpreter from source in order to set up a cron job to run a script to play a clock noise.
A:
In addition to the great advice already written, I'd suggest you install IPython (Open a terminal with Applications>Accessories>Terminal and type):
sudo apt-get install ipython
Also at the terminal, you can then type ipython to start the Python interpreter.
Unlike the built in python interpreter, ipython gives you tab completion.
For example, if you type the name of an object followed by a period and TAB (e.g. sys.[TAB]), ipython will show you (almost) all of object's attributes.
Type a question mark after an object name (e.g. sys?), and you get documentation on that object.
This is a great way to explore Python.
A:
have no exposure to shell scripting
Good! You've got Python so hopefully there should be no need to resort to writing actual scripts with the shell. It may be more powerful than DOS batch files, but it's just as ugly.
I need some advice on how I can quickly learn to use the Linux terminal quickly.
Something like this?
As well as learning the commands, you'll want to get used to using tab-completion and arrow key command recall (if you don't already do that with the Windows Command Prompt), scrolling with shift-arrows, and so on. Also useful to know the & (perform in background) command suffix, ctrl-C-to-stop, ctrl-Z-to-pause, jobs, and screen.
Incidentally if you will be spending any amount of time in the interactive Python interpreter it is well worth adding tab completion there, too. (This is just as much the case on Windows, but on Win you tend not to get pyreadline by default.)
is there a particular IDE that is generally preferred for Python programming on Linux
Just like on Windows, there are IDEs available if you want them but many people just use a normal text editor. vim is fine if that's what you like. nano is another in-terminal text editor you usually get that's relatively simple. Ubuntu's default desktop-based editor gedit is also fine. It's a matter of personal taste.
(If you are interning at a particular company they might have their own development environment they'd prefer you to use.)
A:
For a Python IDE, I recommend using either IDLE or Eclipse with PyDev.
Keep in mind you can also just use python on the linux command-line. It supports loading code from files, and if you use two command windows then one of them will be your "REPL" where you will be running python and dynamically loading code - and the other window can run your editor.
Regarding linux command line, I cannot recommend any great resources. However, you will be off to a great start if you immerse yourself in this environment and only use linux for the next 2 weeks. Just keep learning, and when you do not know how to do something, read a manpage or google it to find the answer.
A:
for a very beginner intro to the command line, check out: http://en.flossmanuals.net/CommandLineIntro/GettingStarted
A:
As far as a Python editor goes, I personally prefer to use SciTE. It's just a programmer's text editor with syntax highlighting for various languages. I prefer a lightweight editor over a more complicated environment, but if you want a full-fledged IDE you can always try out NetBeans, IDLE, or Komodo (all of which are available in both Windows and Linux).
A:
as for terminall and quick way to understand it's and learn it there are a nice cheat sheets on net like this:
http://fosswire.com/post/2007/8/unixlinux-command-cheat-sheet/
|
How do I prepare myself for a summer of working on Python using Linux environment?
|
I have used just Windows for programming so far. Now, I have an internship starting in two weeks and I will be using just Linux environment with Python programming language. I've installed Ubuntu on my system but have no exposure to shell scripting.
I need some advice on how I can quickly learn to use the Linux terminal quickly. Any books or web resources that you can suggest?
Also, is there a particular IDE that is generally preferred for Python programming on Linux, or is Vim preferred? How can I best prepare myself for the internship ahead?
Thanks for taking the time.
|
[
"As an intern you'll want to use the tools your mentor is most comfortable with. If you get stuck you'll be able to ask for advice quickly. \nLearning your way around either vi, vim, or emacs to start with will help. The basic concepts used in one will transfer to the other. You'll need to be able to open and read files, search through files, edit and save files, and learn how to apply any python formatting helpers correctly.\nYou should also familiarize yourself with version control if you haven't already. Again any one will do, you need to focus on concepts and etiquette rather than the specific tool.\nThe goal of the internship (and really your entire time at university) should be used to learn concepts rather than specific tools. If you learn the concepts you'll be well placed to apply those concepts using any tool. You will also \"learn how to learn\" a new tool, which is really valuable.\n",
"Your lack of shell scripting knowledge shouldn't matter in this case, although it won't be hard to learn. I read over some shell tutorials and put them into practice. Try doing everything from the command line, including find (grep), find/replace all (sed), finding files (find), automating things using python scripts etc. Basically, don't cheat. You'll pick up a lot this way. You'll also probably end up wondering how you ever managed with Windows.\nWhat I use depends on the project. I really like Eclipse+PyDev but that's my personal preference, I also use Vim depending on where I am/what I'm doing. Remember you can just type python from the command line and it drops you into the python environment.\n",
"I recommend Eclipse + PyDev too. You can get started quickly with this develop environment. I also recommend the website Dive Into Python. It provides you a online free version of Dive Into Python book, which is very easy to read, easy to understand, and very suitable for Python beginners. If you really want a paper book at hand, Learning Python, a.k.a. The Animal Guide, is simply the best.\n",
"Learn to understand man(ual) pages.\nFor almost any old linux command/program there is a man page which usually explains the command in good detail.\nSo basics for filesystem navigation:\nShow directory contents (list)\nls\n\nShow hidden files\nls -a\n\nShow details\nls -l\n\nChange directory\ncd /full/path/name\n\nPrint current directory\npwd\n\nDelete a file\nrm file\n\nDelete a directory (recursive)\nrm -r directoryName\n\nMake a directory\nmkdir directoryName\n\nMove (or rename) a file\nmv /path/to/file /new/path/to/file\n\nShow the man page for mv\nman mv\n\nLearning vim might be necessary, depending on your intern environment. I do my Python (and everything that isn't simple text editing) in Eclipse. You should in any case learn enough to open a file, makes some changes and save the changes in Vim.\nKeep in mind, Ubuntu is very easy. To make things harder on yourself, use the command line for every conceivable thing. Open programs by typing their names into a terminal. Browse your files with the terminal. Do simple editing with vim. That should provide good practice for the day you need to SSH into a computer in Neverland and download and install a local copy of your favorite interpreter from source in order to set up a cron job to run a script to play a clock noise.\n",
"In addition to the great advice already written, I'd suggest you install IPython (Open a terminal with Applications>Accessories>Terminal and type):\nsudo apt-get install ipython\n\nAlso at the terminal, you can then type ipython to start the Python interpreter.\nUnlike the built in python interpreter, ipython gives you tab completion. \nFor example, if you type the name of an object followed by a period and TAB (e.g. sys.[TAB]), ipython will show you (almost) all of object's attributes.\nType a question mark after an object name (e.g. sys?), and you get documentation on that object. \nThis is a great way to explore Python.\n",
"\nhave no exposure to shell scripting\n\nGood! You've got Python so hopefully there should be no need to resort to writing actual scripts with the shell. It may be more powerful than DOS batch files, but it's just as ugly.\n\nI need some advice on how I can quickly learn to use the Linux terminal quickly.\n\nSomething like this?\nAs well as learning the commands, you'll want to get used to using tab-completion and arrow key command recall (if you don't already do that with the Windows Command Prompt), scrolling with shift-arrows, and so on. Also useful to know the & (perform in background) command suffix, ctrl-C-to-stop, ctrl-Z-to-pause, jobs, and screen.\nIncidentally if you will be spending any amount of time in the interactive Python interpreter it is well worth adding tab completion there, too. (This is just as much the case on Windows, but on Win you tend not to get pyreadline by default.)\n\nis there a particular IDE that is generally preferred for Python programming on Linux\n\nJust like on Windows, there are IDEs available if you want them but many people just use a normal text editor. vim is fine if that's what you like. nano is another in-terminal text editor you usually get that's relatively simple. Ubuntu's default desktop-based editor gedit is also fine. It's a matter of personal taste.\n(If you are interning at a particular company they might have their own development environment they'd prefer you to use.)\n",
"For a Python IDE, I recommend using either IDLE or Eclipse with PyDev. \nKeep in mind you can also just use python on the linux command-line. It supports loading code from files, and if you use two command windows then one of them will be your \"REPL\" where you will be running python and dynamically loading code - and the other window can run your editor.\nRegarding linux command line, I cannot recommend any great resources. However, you will be off to a great start if you immerse yourself in this environment and only use linux for the next 2 weeks. Just keep learning, and when you do not know how to do something, read a manpage or google it to find the answer.\n",
"for a very beginner intro to the command line, check out: http://en.flossmanuals.net/CommandLineIntro/GettingStarted\n",
"As far as a Python editor goes, I personally prefer to use SciTE. It's just a programmer's text editor with syntax highlighting for various languages. I prefer a lightweight editor over a more complicated environment, but if you want a full-fledged IDE you can always try out NetBeans, IDLE, or Komodo (all of which are available in both Windows and Linux).\n",
"as for terminall and quick way to understand it's and learn it there are a nice cheat sheets on net like this: \nhttp://fosswire.com/post/2007/8/unixlinux-command-cheat-sheet/\n"
] |
[
5,
2,
2,
1,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"development_environment",
"linux",
"python",
"shell"
] |
stackoverflow_0002624968_development_environment_linux_python_shell.txt
|
Q:
In Django, I want to insert a database record by sending myself an email?
I'm looking into a possible feature for my little to-do application... I like the idea that I can send an email to a particular email address, containing a to-do task I need to complete, and this will be read by my web application and be put in the database... So, when I come to log into my application, the to-do task I emailed will be there as a entry in the app.
Is this possible? I have a slice with SliceHost (basically a dedicated server) so I have total control on what to install etc. I'm using Python/Django/MySQL for this.
Any ideas on what steps to take to make this happen?
A:
If I were to implement this, I'd use a scheduler and a job to be scheduled.
That job would connect to the mail server (be it POP3 or IMAP) and parse the unread messages (or messages unread by the job). Based on that I would insert that record.
You'd get 2 types of records that way. A list of mail message ids which have been processed (so you don't reprocess mails) and a list of tasks.
Disadvantage is that it takes some time before you see the task, as the job only executes every X minutes, or seconds.
If that is not good enough I'd go for a permanent IMAP connection, but you'd have to implement more error handling; you don't just retry automatically every X minutes.
Googling for Django +scheduler will get you started.
also have a look at this StackOverflow thread, no need to reinvent the wheel :)
A:
I needed the exact same thing. I use the Lamson project (which is written in python) to transform email, forward email based on rules to my www.evernote.com and thinking rock www.trgtd.com.au accounts, update firewall web filtering rules, update allow/deny lists for my spam filter, read and write databases etc....
I like to think of it as email server automation and email application development.
www.lamsonproject.org
Troy
A:
One way that I've solved this in the past was using qmail's .qmail files (docs).
Basically you set up qmail and point your email address (for ease of use, lets assume proc@whatever.com is your email address) to your home directory. In that directory you set up a .qmail-proc file to handle the mail.
This allows you to use a full-fledged SMTP server on your server, including spam filtering, forwarding, aliases, all that fun stuff. You can then pipe the data from an email into an application. In your case, I would suggest making a Mangement Command in Django to process the email (I'll call it proc_email). Thus your .qmail-proc may look like:
/var/spool/mail/proc
| /www/django/myproject/manage.py proc_email
This stores a copy of the email in /var/spool/mail/proc, then passes the email to the script in the second line. The email itself is passed to proc_email via sys.stdin. Simply read the email from there, and store it through your Django Models.
If you need to process email for different addresses later, you can also set up aliases which point to your home directory, and use .qmail-<username> files for each alias. Allowing you to pass other flags (such as the username for each alias) to proc_email if needed.
I should note that this isn't the simplest solution, but it can scale, and is pretty darn bullet proof.
A:
I would not focus on Django for this.
I would create a mail server to catch these emails. Use http://docs.python.org/library/smtpd.html.
I would then use just the Django ORM to update the database based on the emails received.
|
In Django, I want to insert a database record by sending myself an email?
|
I'm looking into a possible feature for my little to-do application... I like the idea that I can send an email to a particular email address, containing a to-do task I need to complete, and this will be read by my web application and be put in the database... So, when I come to log into my application, the to-do task I emailed will be there as a entry in the app.
Is this possible? I have a slice with SliceHost (basically a dedicated server) so I have total control on what to install etc. I'm using Python/Django/MySQL for this.
Any ideas on what steps to take to make this happen?
|
[
"If I were to implement this, I'd use a scheduler and a job to be scheduled.\nThat job would connect to the mail server (be it POP3 or IMAP) and parse the unread messages (or messages unread by the job). Based on that I would insert that record.\nYou'd get 2 types of records that way. A list of mail message ids which have been processed (so you don't reprocess mails) and a list of tasks.\nDisadvantage is that it takes some time before you see the task, as the job only executes every X minutes, or seconds.\nIf that is not good enough I'd go for a permanent IMAP connection, but you'd have to implement more error handling; you don't just retry automatically every X minutes.\nGoogling for Django +scheduler will get you started.\nalso have a look at this StackOverflow thread, no need to reinvent the wheel :)\n",
"I needed the exact same thing. I use the Lamson project (which is written in python) to transform email, forward email based on rules to my www.evernote.com and thinking rock www.trgtd.com.au accounts, update firewall web filtering rules, update allow/deny lists for my spam filter, read and write databases etc....\nI like to think of it as email server automation and email application development.\nwww.lamsonproject.org\nTroy\n",
"One way that I've solved this in the past was using qmail's .qmail files (docs).\nBasically you set up qmail and point your email address (for ease of use, lets assume proc@whatever.com is your email address) to your home directory. In that directory you set up a .qmail-proc file to handle the mail. \nThis allows you to use a full-fledged SMTP server on your server, including spam filtering, forwarding, aliases, all that fun stuff. You can then pipe the data from an email into an application. In your case, I would suggest making a Mangement Command in Django to process the email (I'll call it proc_email). Thus your .qmail-proc may look like:\n/var/spool/mail/proc\n| /www/django/myproject/manage.py proc_email\n\nThis stores a copy of the email in /var/spool/mail/proc, then passes the email to the script in the second line. The email itself is passed to proc_email via sys.stdin. Simply read the email from there, and store it through your Django Models. \nIf you need to process email for different addresses later, you can also set up aliases which point to your home directory, and use .qmail-<username> files for each alias. Allowing you to pass other flags (such as the username for each alias) to proc_email if needed.\nI should note that this isn't the simplest solution, but it can scale, and is pretty darn bullet proof.\n",
"I would not focus on Django for this.\nI would create a mail server to catch these emails. Use http://docs.python.org/library/smtpd.html. \nI would then use just the Django ORM to update the database based on the emails received. \n"
] |
[
5,
2,
1,
0
] |
[] |
[] |
[
"django",
"email",
"mysql",
"python"
] |
stackoverflow_0002616896_django_email_mysql_python.txt
|
Q:
Decoding not reversing unicode encoding in Django/Python
Ok, I have a hardcoded string I declare like this
name = u"Par Catégorie"
I have a # -- coding: utf-8 -- magic header, so I am guessing it's converted to utf-8
Down the road it's outputted to xml through
xml_output.toprettyxml(indent='....', encoding='utf-8')
And I get a
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)
Most of my data is in French and is ouputted correctly in CDATA nodes, but that one harcoded string keep ... I don't see why an ascii codec is called.
what's wrong ?
A:
The coding header in your source file tells Python what encoding your source is in. It's the encoding Python uses to decode the source of the unicode string literal (u"Par Catégorie") into a unicode object. The unicode object itself has no encoding; it's raw unicode data. (Internally, Python will use one of two encodings, depending on how it was configured, but Python code shouldn't worry about that.)
The UnicodeDecodeError you get means that somewhere, you are mixing unicode strings and bytestrings (normal strings.) When mixing them together (concatenating, performing string interpolation, et cetera) Python will try to convert the bytestring into a unicode string by decoding the bytestring using the default encoding, ASCII. If the bytestring contains non-ASCII data, this will fail with the error you see. The operation being done may be in a library somewhere, but it still means you're mixing inputs of different types.
Unfortunately the fact that it'll work just fine as long as the bytestrings contain just ASCII data means this type of error is all too frequent even in library code. Python 3.x solves that problem by getting rid of the implicit conversion between unicode strings (just str in 3.x) and bytestrings (the bytes type in 3.x.)
A:
Wrong parameter name? From the doc, I can see the keyword argument name is supposed to be encoding and not coding.
|
Decoding not reversing unicode encoding in Django/Python
|
Ok, I have a hardcoded string I declare like this
name = u"Par Catégorie"
I have a # -- coding: utf-8 -- magic header, so I am guessing it's converted to utf-8
Down the road it's outputted to xml through
xml_output.toprettyxml(indent='....', encoding='utf-8')
And I get a
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)
Most of my data is in French and is ouputted correctly in CDATA nodes, but that one harcoded string keep ... I don't see why an ascii codec is called.
what's wrong ?
|
[
"The coding header in your source file tells Python what encoding your source is in. It's the encoding Python uses to decode the source of the unicode string literal (u\"Par Catégorie\") into a unicode object. The unicode object itself has no encoding; it's raw unicode data. (Internally, Python will use one of two encodings, depending on how it was configured, but Python code shouldn't worry about that.)\nThe UnicodeDecodeError you get means that somewhere, you are mixing unicode strings and bytestrings (normal strings.) When mixing them together (concatenating, performing string interpolation, et cetera) Python will try to convert the bytestring into a unicode string by decoding the bytestring using the default encoding, ASCII. If the bytestring contains non-ASCII data, this will fail with the error you see. The operation being done may be in a library somewhere, but it still means you're mixing inputs of different types.\nUnfortunately the fact that it'll work just fine as long as the bytestrings contain just ASCII data means this type of error is all too frequent even in library code. Python 3.x solves that problem by getting rid of the implicit conversion between unicode strings (just str in 3.x) and bytestrings (the bytes type in 3.x.)\n",
"Wrong parameter name? From the doc, I can see the keyword argument name is supposed to be encoding and not coding.\n"
] |
[
4,
1
] |
[] |
[] |
[
"character_encoding",
"django",
"encoding",
"minidom",
"python"
] |
stackoverflow_0002625297_character_encoding_django_encoding_minidom_python.txt
|
Q:
For-loops in Python
What is the best way of doing this in Python?
for (v = n / 2 - 1; v >= 0; v--)
I actually tried Google first, but as far as I can see the only solution would be to use while.
A:
I would do this:
for i in reversed(range(n // 2)):
# Your code
pass
It's a bit clearer that this is a reverse sequence, what the lower limit is, and what the upper limit is.
A:
The way to do it is with xrange():
for v in xrange(n // 2 - 1, -1, -1):
(Or, in Python 3.x, with range() instead of xrange().) // is flooring division, which makes sure the result is a whole number.
A:
for v in range(n//2, -1, -1)
However, in 90% of the cases when you would have used a for loop in C/Java/C#/VB, what you really want is list comprehension:
listOfStuff = [doSomethingWith(v) for v in range(n//2, -1, -1)]
A:
for v in xrange(n/2 - 1, 0, -1):
#your code here
Where v and n are ints or treated as ints. This means that the division will be an integer division, i.e., 1/2 == 0 is True.
Note: This is for Python 2.x .
|
For-loops in Python
|
What is the best way of doing this in Python?
for (v = n / 2 - 1; v >= 0; v--)
I actually tried Google first, but as far as I can see the only solution would be to use while.
|
[
"I would do this:\nfor i in reversed(range(n // 2)):\n # Your code\n pass\n\nIt's a bit clearer that this is a reverse sequence, what the lower limit is, and what the upper limit is.\n",
"The way to do it is with xrange():\nfor v in xrange(n // 2 - 1, -1, -1):\n\n(Or, in Python 3.x, with range() instead of xrange().) // is flooring division, which makes sure the result is a whole number.\n",
"for v in range(n//2, -1, -1)\n\nHowever, in 90% of the cases when you would have used a for loop in C/Java/C#/VB, what you really want is list comprehension:\nlistOfStuff = [doSomethingWith(v) for v in range(n//2, -1, -1)]\n\n",
"for v in xrange(n/2 - 1, 0, -1):\n #your code here\n\nWhere v and n are ints or treated as ints. This means that the division will be an integer division, i.e., 1/2 == 0 is True. \nNote: This is for Python 2.x . \n"
] |
[
15,
13,
5,
0
] |
[] |
[] |
[
"for_loop",
"python"
] |
stackoverflow_0002625540_for_loop_python.txt
|
Q:
Python module seeing a full list as empty in another module
I'm working on a pygame project and have the main engine layed out. The problem is I hit a bug that I just can not seem to figure out. What happens is one module can't read a variable from another module.
It's not that the variable can't be read, it just sees an empty list instead of what it really is.
Instead of posting the entire source code I reproduced the bug in two small snippets that hopefully a skillful python-ist can interpret in his\her head.
Code:
main.py (This is the file that gets run)
import screen
screens = [] #A stack for all the game screens
def current_screen():
#return a reference to the current screen
return screens[-1]
def play():
print'play called'
current_screen().update()
if __name__=='__main__':
screens.append(screen.Screen())
play()
screen.py
import main
class Screen:
def __init__(self):
print'screen made'
def update(self):
print main.screens
#Should have a reference to itself in there
Thanks!
A:
Don't import the main script. When you run the main.py file directly, it becomes the __main__ module. When you then import main, it will find the same file (main.py) but load it a second time, under a different module object (main instead of __main__.)
The solution is to not do this. Don't put things you want to 'export' to other modules in the main script. It won't work right. Put them in a third module. Or, pass them as arguments to the functions and classes you're calling.
A:
The whole point of if __name__=='__main__': is to prevent code from being run when a module is imported. So when you import main from screen, that part isn't run and the list stays empt and play() is never called either.
|
Python module seeing a full list as empty in another module
|
I'm working on a pygame project and have the main engine layed out. The problem is I hit a bug that I just can not seem to figure out. What happens is one module can't read a variable from another module.
It's not that the variable can't be read, it just sees an empty list instead of what it really is.
Instead of posting the entire source code I reproduced the bug in two small snippets that hopefully a skillful python-ist can interpret in his\her head.
Code:
main.py (This is the file that gets run)
import screen
screens = [] #A stack for all the game screens
def current_screen():
#return a reference to the current screen
return screens[-1]
def play():
print'play called'
current_screen().update()
if __name__=='__main__':
screens.append(screen.Screen())
play()
screen.py
import main
class Screen:
def __init__(self):
print'screen made'
def update(self):
print main.screens
#Should have a reference to itself in there
Thanks!
|
[
"Don't import the main script. When you run the main.py file directly, it becomes the __main__ module. When you then import main, it will find the same file (main.py) but load it a second time, under a different module object (main instead of __main__.)\nThe solution is to not do this. Don't put things you want to 'export' to other modules in the main script. It won't work right. Put them in a third module. Or, pass them as arguments to the functions and classes you're calling.\n",
"The whole point of if __name__=='__main__': is to prevent code from being run when a module is imported. So when you import main from screen, that part isn't run and the list stays empt and play() is never called either.\n"
] |
[
4,
0
] |
[] |
[] |
[
"import",
"module",
"python"
] |
stackoverflow_0002626003_import_module_python.txt
|
Q:
Where is Python support for PEM + RSA + DES3?
I need a Python library that supports PEM files and both RSA signing and DES3 encryption. pycrypto doesn't seem to support PEM, and its mechanism for loading existing keys is undocumented and cryptic. m2crypto doesn't seem to support DES/DES3, oddly.
I've been running an openssl subprocess, but I'd rather have something built in and preferably fast. Does this exist?
(Failing that, I hesitate to ask, but are there high-level enough C apis available for this that I could write a special-purpose extension without killing myself/introducing vulns?)
A:
Check out the libraries mentioned in this overview: Comparison of Python cryptography modules
|
Where is Python support for PEM + RSA + DES3?
|
I need a Python library that supports PEM files and both RSA signing and DES3 encryption. pycrypto doesn't seem to support PEM, and its mechanism for loading existing keys is undocumented and cryptic. m2crypto doesn't seem to support DES/DES3, oddly.
I've been running an openssl subprocess, but I'd rather have something built in and preferably fast. Does this exist?
(Failing that, I hesitate to ask, but are there high-level enough C apis available for this that I could write a special-purpose extension without killing myself/introducing vulns?)
|
[
"Check out the libraries mentioned in this overview: Comparison of Python cryptography modules\n"
] |
[
6
] |
[] |
[] |
[
"cryptography",
"m2crypto",
"pycrypto",
"python"
] |
stackoverflow_0002626084_cryptography_m2crypto_pycrypto_python.txt
|
Q:
web2py error while using distinct in the queries
I am using web2py with GAE. While using some of the queries which has a distinct clause, GAE throws out an error.I have pasted the Traceback. Can someone please help me out with this.
In FILE: /base/data/home/apps/panneersoda/1.341206242889687944/applications/init/controllers/default.py
Traceback (most recent call last):
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/restricted.py", line 173, in restricted
exec ccode in environment
File "/base/data/home/apps/panneersoda/1.341206242889687944/applications/init/controllers/default.py:profileview", line 263, in <module>
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/globals.py", line 96, in <lambda>
self._caller = lambda f: f()
File "/base/data/home/apps/panneersoda/1.341206242889687944/applications/init/controllers/default.py:profileview", line 97, in profileview
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/contrib/gql.py", line 675, in select
(items, tablename, fields) = self._select(*fields, **attributes)
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/contrib/gql.py", line 624, in _select
raise SyntaxError, 'invalid select attribute: %s' % key
SyntaxError: invalid select attribute: distinct
Thanks
A:
Sorry distinct does not work on GAE, only RDBS.
|
web2py error while using distinct in the queries
|
I am using web2py with GAE. While using some of the queries which has a distinct clause, GAE throws out an error.I have pasted the Traceback. Can someone please help me out with this.
In FILE: /base/data/home/apps/panneersoda/1.341206242889687944/applications/init/controllers/default.py
Traceback (most recent call last):
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/restricted.py", line 173, in restricted
exec ccode in environment
File "/base/data/home/apps/panneersoda/1.341206242889687944/applications/init/controllers/default.py:profileview", line 263, in <module>
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/globals.py", line 96, in <lambda>
self._caller = lambda f: f()
File "/base/data/home/apps/panneersoda/1.341206242889687944/applications/init/controllers/default.py:profileview", line 97, in profileview
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/contrib/gql.py", line 675, in select
(items, tablename, fields) = self._select(*fields, **attributes)
File "/base/data/home/apps/panneersoda/1.341206242889687944/gluon/contrib/gql.py", line 624, in _select
raise SyntaxError, 'invalid select attribute: %s' % key
SyntaxError: invalid select attribute: distinct
Thanks
|
[
"Sorry distinct does not work on GAE, only RDBS.\n"
] |
[
2
] |
[] |
[] |
[
"google_app_engine",
"python",
"web2py"
] |
stackoverflow_0002624117_google_app_engine_python_web2py.txt
|
Q:
Beautiful Soup Unicode encode error
I am trying the following code with a particular HTML file
from BeautifulSoup import BeautifulSoup
import re
import codecs
import sys
f = open('test1.html')
html = f.read()
soup = BeautifulSoup(html)
body = soup.body.contents
para = soup.findAll('p')
print str(para).encode('utf-8')
I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 9: ordinal not in range(128)
How do I debug this?
I do not get any error when I remove the call to print function.
A:
The str(para) builtin is trying to use the default (ascii) encoding for the unicode in para.
This is done before the encode() call:
>>> s=u'123\u2019'
>>> str(s)
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 3: ordinal not in range(128)
>>> s.encode("utf-8")
'123\xe2\x80\x99'
>>>
Try encoding para directly, maybe by applying encode("utf-8") to each list element.
|
Beautiful Soup Unicode encode error
|
I am trying the following code with a particular HTML file
from BeautifulSoup import BeautifulSoup
import re
import codecs
import sys
f = open('test1.html')
html = f.read()
soup = BeautifulSoup(html)
body = soup.body.contents
para = soup.findAll('p')
print str(para).encode('utf-8')
I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 9: ordinal not in range(128)
How do I debug this?
I do not get any error when I remove the call to print function.
|
[
"The str(para) builtin is trying to use the default (ascii) encoding for the unicode in para.\nThis is done before the encode() call:\n>>> s=u'123\\u2019'\n>>> str(s)\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\nUnicodeEncodeError: 'ascii' codec can't encode character u'\\u2019' in position 3: ordinal not in range(128)\n>>> s.encode(\"utf-8\")\n'123\\xe2\\x80\\x99'\n>>> \n\nTry encoding para directly, maybe by applying encode(\"utf-8\") to each list element.\n"
] |
[
2
] |
[] |
[] |
[
"beautifulsoup",
"python",
"unicode"
] |
stackoverflow_0002627071_beautifulsoup_python_unicode.txt
|
Q:
Adding python script to c++ project
How would I go about adding a script written in python to a c++ project? Thanks
Edit: Basically all the script does is email some data. I would like to pass the data and maybe the email address to a function written in python. Hope that clears things up..
A:
You could look at Boost.Python which is a "a C++ library which enables seamless interoperability between C++ and the Python programming language."
You have to be more specific, though.
A:
You may be interested in Boost.Python: Embedding the Interpreter, or Python/C API: Embedding the Python Interpreter. You can either use the Python C APIs directly or use the Boost.Python library as you so choose. You might also be interested in reading Embedding Python in Your C Programs which walks you through it.
A:
The most primitve solution would be to use the system command to call you script, but that does limit your control over it to setting environment variables and passing parameters.
system("myscript.py param1 param2")
|
Adding python script to c++ project
|
How would I go about adding a script written in python to a c++ project? Thanks
Edit: Basically all the script does is email some data. I would like to pass the data and maybe the email address to a function written in python. Hope that clears things up..
|
[
"You could look at Boost.Python which is a \"a C++ library which enables seamless interoperability between C++ and the Python programming language.\"\nYou have to be more specific, though.\n",
"You may be interested in Boost.Python: Embedding the Interpreter, or Python/C API: Embedding the Python Interpreter. You can either use the Python C APIs directly or use the Boost.Python library as you so choose. You might also be interested in reading Embedding Python in Your C Programs which walks you through it.\n",
"The most primitve solution would be to use the system command to call you script, but that does limit your control over it to setting environment variables and passing parameters.\nsystem(\"myscript.py param1 param2\") \n\n"
] |
[
3,
3,
1
] |
[] |
[] |
[
"boost_python",
"c++",
"python",
"visual_studio"
] |
stackoverflow_0002627173_boost_python_c++_python_visual_studio.txt
|
Q:
Get Cygwin installation path in a Python script
I'm writing a cross-platform python script that needs to know if and where Cygwin is installed if the platform is NT. Right now I'm just using a naive check for the existence of the default install path 'C:\Cygwin'. I would like to be able to determine the installation path programmatically.
The Windows registry doesn't appear to be an option since Cygwin no longer stores it's mount points in the registry. Because of this is it even possible to programmatically get a Cygwin installation path?
A:
Valid for Cygwin 1.7 only:
You need to check both HKEY_CURRENT_USER and HKEY_LOCAL_MAHINE for the Cygwin registry key. Depending on how Cygwin was installed it could be under either key.
The following is an example of how to query the value using the current user.
CYGWIN_KEY = "SOFTWARE\\Cygwin\\setup"
hk_user = winreg.HKEY_CURRENT_USER
key = winreg.OpenKey(hk_user, CYGWIN_KEY)
root = winreg.QueryValueEx(key, "rootdir")[0]
When writing a script you should probably check the global HKEY_LOCAL_MACHINE first. However, keep in mind that it is possible to have multiple installations of Cygwin on a single machine.
A:
That's what I'd do. There are registry entries for the cygwin drive mount points:
http://www.cygwin.com/ml/cygwin/2004-12/msg00200.html
You can use the _winreg (or winreg in python 3.0) module to look the values up:
http://docs.python.org/library/_winreg.html
A:
You can use the HKEY_LOCAL_MACHINE\SOFTWARE\Cygwin\setup\rootdir value for Cygwin 1.7
|
Get Cygwin installation path in a Python script
|
I'm writing a cross-platform python script that needs to know if and where Cygwin is installed if the platform is NT. Right now I'm just using a naive check for the existence of the default install path 'C:\Cygwin'. I would like to be able to determine the installation path programmatically.
The Windows registry doesn't appear to be an option since Cygwin no longer stores it's mount points in the registry. Because of this is it even possible to programmatically get a Cygwin installation path?
|
[
"Valid for Cygwin 1.7 only:\nYou need to check both HKEY_CURRENT_USER and HKEY_LOCAL_MAHINE for the Cygwin registry key. Depending on how Cygwin was installed it could be under either key.\nThe following is an example of how to query the value using the current user.\nCYGWIN_KEY = \"SOFTWARE\\\\Cygwin\\\\setup\"\nhk_user = winreg.HKEY_CURRENT_USER\nkey = winreg.OpenKey(hk_user, CYGWIN_KEY)\nroot = winreg.QueryValueEx(key, \"rootdir\")[0]\n\nWhen writing a script you should probably check the global HKEY_LOCAL_MACHINE first. However, keep in mind that it is possible to have multiple installations of Cygwin on a single machine. \n",
"That's what I'd do. There are registry entries for the cygwin drive mount points:\nhttp://www.cygwin.com/ml/cygwin/2004-12/msg00200.html\nYou can use the _winreg (or winreg in python 3.0) module to look the values up:\nhttp://docs.python.org/library/_winreg.html\n",
"You can use the HKEY_LOCAL_MACHINE\\SOFTWARE\\Cygwin\\setup\\rootdir value for Cygwin 1.7\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"cygwin",
"python",
"registry",
"windows"
] |
stackoverflow_0001925552_cygwin_python_registry_windows.txt
|
Q:
How do I sanitize LaTeX input?
I'd like to take user input (sometimes this will be large paragraphs) and generate a LaTeX document. I'm considering a couple of simple regular expressions that replaces all instances of \ with \textbackslash and all instances of { or } with \} or \{.
I doubt that this is sufficient. What else do I need to do? Note: In case there is a special library made for this, I'm using python.
To clarify, I do not wish anything to be parsed treated as LaTeX syntax: $a$ should be replaced with \$a\$.
A:
If your input is plain text and you are in a normal catcode regime, you must do the following substitutions:
\ → \textbackslash{} (note the empty group!)
{ → \{
} → \}
$ → \$
& → \&
# → \#
^ → \textasciicircum{} (requires the textcomp package)
_ → \_
~ → \textasciitilde{}
% → \%
In addition, the following substitutions are useful at least when using the OT1 encoding (and harmless in any case):
< → \textless{}
> → \textgreater{}
| → \textbar{}
And these three disable the curly quotes:
" → \textquotedbl{}
' → \textquotesingle{}
` → \textasciigrave{}
|
How do I sanitize LaTeX input?
|
I'd like to take user input (sometimes this will be large paragraphs) and generate a LaTeX document. I'm considering a couple of simple regular expressions that replaces all instances of \ with \textbackslash and all instances of { or } with \} or \{.
I doubt that this is sufficient. What else do I need to do? Note: In case there is a special library made for this, I'm using python.
To clarify, I do not wish anything to be parsed treated as LaTeX syntax: $a$ should be replaced with \$a\$.
|
[
"If your input is plain text and you are in a normal catcode regime, you must do the following substitutions:\n\n\\ → \\textbackslash{} (note the empty group!)\n{ → \\{\n} → \\}\n$ → \\$\n& → \\&\n# → \\#\n^ → \\textasciicircum{} (requires the textcomp package)\n_ → \\_\n~ → \\textasciitilde{}\n% → \\%\n\nIn addition, the following substitutions are useful at least when using the OT1 encoding (and harmless in any case):\n\n< → \\textless{}\n> → \\textgreater{}\n| → \\textbar{}\n\nAnd these three disable the curly quotes:\n\n\" → \\textquotedbl{}\n' → \\textquotesingle{}\n` → \\textasciigrave{}\n\n"
] |
[
16
] |
[] |
[] |
[
"latex",
"python",
"sanitization"
] |
stackoverflow_0002627135_latex_python_sanitization.txt
|
Q:
Help calling class from a class above
How to call from class oneThread: back to class fun:? As in, address a class written below. Is it possible?
class oneThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
print "1"
time.sleep(1)
print "2"
time.sleep(1)
print "3"
self.wTree.get_widget("entryResult").set_text("Done with One.") # How to call from here back to class fun, which of course is below...?
class fun:
wTree = None
def __init__( self ):
self.wTree = gtk.glade.XML( "main.glade" )
self.wTree.signal_autoconnect( {"on_buttonOne" : self.one} )
gtk.main()
def one(self, widget):
oneThread();
gtk.gdk.threads_init()
do=fun()
A:
You need to use the right references to the full object
or just a field of (the wTree).
self.fun.wTree if you pass self to the oneThread class
self.wTree if you pass the gtk.glade.XML Object
see the comments...
class oneThread(threading.Thread):
def __init__(self, reference):
self.fun = reference
#or self.wTree = reference
threading.Thread.__init__(self)
self.start()
def run(self):
print "1"
time.sleep(1)
print "2"
time.sleep(1)
print "3"
self.fun.wTree.get_widget("entryResult").set_text("Done with One.")
# or self.wTree.get_widget("entryResult").set_text("Done with One.")
class fun(object):
def __init__( self ):
self.wTree = gtk.glade.XML( "main.glade" )
self.wTree.signal_autoconnect( {"on_buttonOne" : self.one} )
gtk.main()
def one(self, widget):
oneThread(self)
# or oneThread(self.wTree)
A:
The elegant solution would be to pass the reference to class fun instance to the oneThread constructor, as other suggested, but you seem to be trying to do something else: making the fun class as singleton an accessing it as a global object. Is that right? That is usually a bad idea, but sometimes makes sense.
If that is the case, then you are making two mistakes:
you use self.fun in oneThread.run, although 'fun' is not part of the oneThread class or its instance. You should be using just 'fun' to access the class 'fun'. It doesn't matter it is defined below, as the code will be executed when the class is already defined.
in fun.__init__ you are not writting the class attribute fun.wTree, but creating a instance attribute wTree. The class attribute fun.wTree will stay None. To change it
use fun.wTree = gtk.glade.XML( "main.glade" ) instead (though, you may keep using self.wTree to access it later).
So the code would look like this:
class oneThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
print "1"
time.sleep(1)
print "2"
time.sleep(1)
print "3"
fun.wTree.get_widget("entryResult").set_text("Done with One.")
class fun:
wTree = None
def __init__( self ):
fun.wTree = gtk.glade.XML( "main.glade" )
self.wTree.signal_autoconnect( {"on_buttonOne" : self.one} )
gtk.main()
def one(self, widget):
oneThread();
gtk.gdk.threads_init()
do=fun()
I would also suggest renaming wTree attribute to instance in such case too.
And once more: this (using a singleton as a kind of global variable) is probably not the way to go.
A:
You would need to pass the fun instance to the oneThread constructor:
class oneThread(threading.Thread):
def __init__(self, fun):
self.fun = fun
...
class fun:
def one(self, widget):
oneThread(self):
|
Help calling class from a class above
|
How to call from class oneThread: back to class fun:? As in, address a class written below. Is it possible?
class oneThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
print "1"
time.sleep(1)
print "2"
time.sleep(1)
print "3"
self.wTree.get_widget("entryResult").set_text("Done with One.") # How to call from here back to class fun, which of course is below...?
class fun:
wTree = None
def __init__( self ):
self.wTree = gtk.glade.XML( "main.glade" )
self.wTree.signal_autoconnect( {"on_buttonOne" : self.one} )
gtk.main()
def one(self, widget):
oneThread();
gtk.gdk.threads_init()
do=fun()
|
[
"You need to use the right references to the full object\nor just a field of (the wTree).\nself.fun.wTree if you pass self to the oneThread class\nself.wTree if you pass the gtk.glade.XML Object\nsee the comments...\nclass oneThread(threading.Thread):\n def __init__(self, reference):\n self.fun = reference\n #or self.wTree = reference\n threading.Thread.__init__(self)\n self.start()\n\n def run(self):\n print \"1\"\n time.sleep(1)\n print \"2\"\n time.sleep(1)\n print \"3\"\n self.fun.wTree.get_widget(\"entryResult\").set_text(\"Done with One.\")\n # or self.wTree.get_widget(\"entryResult\").set_text(\"Done with One.\")\n\nclass fun(object):\n def __init__( self ):\n self.wTree = gtk.glade.XML( \"main.glade\" )\n self.wTree.signal_autoconnect( {\"on_buttonOne\" : self.one} )\n gtk.main()\n\n def one(self, widget):\n oneThread(self)\n # or oneThread(self.wTree)\n\n",
"The elegant solution would be to pass the reference to class fun instance to the oneThread constructor, as other suggested, but you seem to be trying to do something else: making the fun class as singleton an accessing it as a global object. Is that right? That is usually a bad idea, but sometimes makes sense.\nIf that is the case, then you are making two mistakes:\n\nyou use self.fun in oneThread.run, although 'fun' is not part of the oneThread class or its instance. You should be using just 'fun' to access the class 'fun'. It doesn't matter it is defined below, as the code will be executed when the class is already defined.\nin fun.__init__ you are not writting the class attribute fun.wTree, but creating a instance attribute wTree. The class attribute fun.wTree will stay None. To change it\nuse fun.wTree = gtk.glade.XML( \"main.glade\" ) instead (though, you may keep using self.wTree to access it later).\n\nSo the code would look like this:\nclass oneThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.start()\n\n def run(self): \n print \"1\"\n time.sleep(1)\n print \"2\"\n time.sleep(1)\n print \"3\"\n fun.wTree.get_widget(\"entryResult\").set_text(\"Done with One.\") \n\nclass fun:\n wTree = None\n def __init__( self ): \n fun.wTree = gtk.glade.XML( \"main.glade\" )\n self.wTree.signal_autoconnect( {\"on_buttonOne\" : self.one} ) \n gtk.main()\n\n def one(self, widget):\n oneThread();\n\ngtk.gdk.threads_init() \ndo=fun()\n\nI would also suggest renaming wTree attribute to instance in such case too.\nAnd once more: this (using a singleton as a kind of global variable) is probably not the way to go.\n",
"You would need to pass the fun instance to the oneThread constructor:\nclass oneThread(threading.Thread):\n def __init__(self, fun):\n self.fun = fun\n ...\n\nclass fun:\n def one(self, widget):\n oneThread(self):\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002625440_python.txt
|
Q:
What kind of client/server protocols python supports out of the box?
Without installing third party libraries, what kind of Client/Server protocols Python supports out of the box ?
A:
Basic Web Protocols:
Downloading from http, ftp and file: with urllib, but note that in python 3 that urllib.urlopen has moved to urllib2.urlopen and is deprecated from python 2.6
Downloading from https and http with basic proxy and authentication support with urllib2
http with httplib, and server modules BaseHTTPServer, SimpleHTTPServer and CGIHTTPServer, but note that the servers have been moved to http.server in python 3
ftp uploading/downloading with ftplib
telnet with telnetlib
Mail Protocols:
imap with imaplib
pop3 with poplib
smtp with smtplib and smtpd
XML-RPC:
XML RPC client with xmlrpclib and server modules SimpleXMLRPCServer and DocXMLRPCServer, but the servers have been moved to xmlrpc.server in python 3
News Reading Protocols:
NNTP with nntplib
|
What kind of client/server protocols python supports out of the box?
|
Without installing third party libraries, what kind of Client/Server protocols Python supports out of the box ?
|
[
"\nBasic Web Protocols:\n\n\nDownloading from http, ftp and file: with urllib, but note that in python 3 that urllib.urlopen has moved to urllib2.urlopen and is deprecated from python 2.6\nDownloading from https and http with basic proxy and authentication support with urllib2\nhttp with httplib, and server modules BaseHTTPServer, SimpleHTTPServer and CGIHTTPServer, but note that the servers have been moved to http.server in python 3\nftp uploading/downloading with ftplib\ntelnet with telnetlib\n\nMail Protocols:\n\n\nimap with imaplib\npop3 with poplib\nsmtp with smtplib and smtpd\n\nXML-RPC:\n\n\nXML RPC client with xmlrpclib and server modules SimpleXMLRPCServer and DocXMLRPCServer, but the servers have been moved to xmlrpc.server in python 3\n\nNews Reading Protocols:\n\n\nNNTP with nntplib\n\n\n"
] |
[
11
] |
[] |
[] |
[
"client_server",
"python"
] |
stackoverflow_0002627715_client_server_python.txt
|
Q:
Accessing Python module fails although its package is imported
My Django project's directory hierarchy looks like this:
+ pybsd
|---+ devices
|---+ templates
|---+ views
|---+ interaction
|---- __init__.py
|---- geraete.py
|---- geraetemodelle.py
|---- geraetegruppen.py
|---- __init__.py
|---- ajax.py
|---- html.py
|---- misc.py
|---- __init__.py
|---- urls.py
|---- __init__.py
|---- urls.py
(Please excuse the German names. I preferred not to replace them here since it would add yet another possible error source when trying out the solutions you'll hopefully suggest and answering your questions.)
Every request to http://URL/devices/.* is dispatched to the urls.py file living in /devices:
# ...
from views import html, ajax, misc, interaction
urlpatterns = patterns('',
# ...
(r'^ajax/update/(?P<table>[a-z_]+)$', ajax.update),
(r'^ajax/delete/(?P<table>[a-z_]+)$', ajax.delete),
(r'^ajax/select_options/(?P<table>[a-z_]+)$', ajax.select_options),
(r'^interaction/geraete/info/(?P<geraet>\d+)$', interaction.geraete.info),
(r'^interaction/geraete/delete/(?P<geraet>\d+)?$', interaction.geraete.delete),
(r'^interaction/geraetemodelle/delete/(?P<geraetemodell>\d+)?$', interaction.geraetemodelle.delete),
(r'^interaction/geraetegruppen/delete/(?P<geraetegruppe>\d+)?$', interaction.geraetegruppen.delete),
# ...
)
All URL definitions work except for those referencing the interaction package. I'm constantly getting the following error:
File "/home/simon/projekte/pybsd/../pybsd/devices/urls.py", line 33, in `<module>`
(r'^interaction/geraete/info/(?P<geraet>\d+)$', interaction.geraete.info),
AttributeError: 'module' object has no attribute 'geraete'
I double-checked that the __init__.py files don't contain anything.
Maybe you've already found the (Python- or Django-related?) mistake I made and am apparently unable to see. If not, read on. In any case, thanks for reading this long post!
Isolating the problem
1st test
It works if I provide the view functions as strings:
(r'^interaction/geraete/info/(?P<geraet>\d+)$', 'devices.views.interaction.geraete.info'),
(r'^interaction/geraete/delete/(?P<geraet>\d+)?$', 'devices.views.interaction.geraete.delete'),
(r'^interaction/geraetemodelle/delete/(?P<geraetemodell>\d+)?$', 'devices.views.interaction.geraetemodelle.delete'),
(r'^interaction/geraetegruppen/delete/(?P<geraetegruppe>\d+)?$', 'devices.views.interaction.geraetegruppen.delete'),
... or add yet another line to the imports:
from views.interaction import geraete, geraetemodelle, geraetegruppen
Using from views.interaction import *, however, doesn't work either and results in the same error message.
2nd test
I created a file test.py in /devices:
from views import interaction
print dir(interaction)
Output:
simon@bsd-simon:~/projekte/pybsd/devices$ python test.py
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
Again, no sign of the modules I created in the interaction package (geraete.py, geraetemodelle.py, geraetegruppen.py).
Unlike in urls.py, trying from view.interaction import geraete, geraetegruppen, geraetemodelle in test.py results in ImportError: No module named view.interaction this time.
3rd test
I started the Django shell:
$ python manage.py shell
>>> import devices.views.interaction.geraete
>>> dir(devices.views.interaction.geraete)
['Abteilung', 'Auftrag', 'Auftragsvorlage', 'Geraet', 'Geraetegruppe', 'Geraetemodell', 'HttpResponse', 'HttpResponseBadRequest', 'HttpResponseRedirect', 'Raum', 'Standort', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'delete', 'info', 'models', 'move', 'render_to_response']
>>>
$ python manage.py shell
>>> from devices.views.interaction import geraete
>>> dir(geraete)
['Abteilung', 'Auftrag', 'Auftragsvorlage', 'Geraet', 'Geraetegruppe', 'Geraetemodell', 'HttpResponse', 'HttpResponseBadRequest', 'HttpResponseRedirect', 'Raum', 'Standort', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'delete', 'info', 'models', 'move', 'render_to_response']
>>>
$ python manage.py shell
>>> import devices.views.interaction
>>> devices.views.interaction.geraete
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'geraete'
>>> dir(devices.views.interaction)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
A:
When modules live in packages, and you import the package, Python does not automatically import all the modules in the package. Something in your program needs to import the modules you want to use. That can either be your urls module:
import views.interaction.gaerete
or, if you want interaction.garaete to always be available when you import interaction, it can be interaction/__init__.py:
import gaerete
A:
When you say
import devices.views.interaction
and later
interaction.geraete
Python looks for geraete in the __init__.py module in the interaction package.
If you want to see this works, you may include import geraete explicitly in the __init__.py module.
A:
You should explicitly import the submodules if they are not imported in the __init__.py file:
import interaction.geraete
|
Accessing Python module fails although its package is imported
|
My Django project's directory hierarchy looks like this:
+ pybsd
|---+ devices
|---+ templates
|---+ views
|---+ interaction
|---- __init__.py
|---- geraete.py
|---- geraetemodelle.py
|---- geraetegruppen.py
|---- __init__.py
|---- ajax.py
|---- html.py
|---- misc.py
|---- __init__.py
|---- urls.py
|---- __init__.py
|---- urls.py
(Please excuse the German names. I preferred not to replace them here since it would add yet another possible error source when trying out the solutions you'll hopefully suggest and answering your questions.)
Every request to http://URL/devices/.* is dispatched to the urls.py file living in /devices:
# ...
from views import html, ajax, misc, interaction
urlpatterns = patterns('',
# ...
(r'^ajax/update/(?P<table>[a-z_]+)$', ajax.update),
(r'^ajax/delete/(?P<table>[a-z_]+)$', ajax.delete),
(r'^ajax/select_options/(?P<table>[a-z_]+)$', ajax.select_options),
(r'^interaction/geraete/info/(?P<geraet>\d+)$', interaction.geraete.info),
(r'^interaction/geraete/delete/(?P<geraet>\d+)?$', interaction.geraete.delete),
(r'^interaction/geraetemodelle/delete/(?P<geraetemodell>\d+)?$', interaction.geraetemodelle.delete),
(r'^interaction/geraetegruppen/delete/(?P<geraetegruppe>\d+)?$', interaction.geraetegruppen.delete),
# ...
)
All URL definitions work except for those referencing the interaction package. I'm constantly getting the following error:
File "/home/simon/projekte/pybsd/../pybsd/devices/urls.py", line 33, in `<module>`
(r'^interaction/geraete/info/(?P<geraet>\d+)$', interaction.geraete.info),
AttributeError: 'module' object has no attribute 'geraete'
I double-checked that the __init__.py files don't contain anything.
Maybe you've already found the (Python- or Django-related?) mistake I made and am apparently unable to see. If not, read on. In any case, thanks for reading this long post!
Isolating the problem
1st test
It works if I provide the view functions as strings:
(r'^interaction/geraete/info/(?P<geraet>\d+)$', 'devices.views.interaction.geraete.info'),
(r'^interaction/geraete/delete/(?P<geraet>\d+)?$', 'devices.views.interaction.geraete.delete'),
(r'^interaction/geraetemodelle/delete/(?P<geraetemodell>\d+)?$', 'devices.views.interaction.geraetemodelle.delete'),
(r'^interaction/geraetegruppen/delete/(?P<geraetegruppe>\d+)?$', 'devices.views.interaction.geraetegruppen.delete'),
... or add yet another line to the imports:
from views.interaction import geraete, geraetemodelle, geraetegruppen
Using from views.interaction import *, however, doesn't work either and results in the same error message.
2nd test
I created a file test.py in /devices:
from views import interaction
print dir(interaction)
Output:
simon@bsd-simon:~/projekte/pybsd/devices$ python test.py
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
Again, no sign of the modules I created in the interaction package (geraete.py, geraetemodelle.py, geraetegruppen.py).
Unlike in urls.py, trying from view.interaction import geraete, geraetegruppen, geraetemodelle in test.py results in ImportError: No module named view.interaction this time.
3rd test
I started the Django shell:
$ python manage.py shell
>>> import devices.views.interaction.geraete
>>> dir(devices.views.interaction.geraete)
['Abteilung', 'Auftrag', 'Auftragsvorlage', 'Geraet', 'Geraetegruppe', 'Geraetemodell', 'HttpResponse', 'HttpResponseBadRequest', 'HttpResponseRedirect', 'Raum', 'Standort', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'delete', 'info', 'models', 'move', 'render_to_response']
>>>
$ python manage.py shell
>>> from devices.views.interaction import geraete
>>> dir(geraete)
['Abteilung', 'Auftrag', 'Auftragsvorlage', 'Geraet', 'Geraetegruppe', 'Geraetemodell', 'HttpResponse', 'HttpResponseBadRequest', 'HttpResponseRedirect', 'Raum', 'Standort', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'delete', 'info', 'models', 'move', 'render_to_response']
>>>
$ python manage.py shell
>>> import devices.views.interaction
>>> devices.views.interaction.geraete
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'module' object has no attribute 'geraete'
>>> dir(devices.views.interaction)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
|
[
"When modules live in packages, and you import the package, Python does not automatically import all the modules in the package. Something in your program needs to import the modules you want to use. That can either be your urls module:\nimport views.interaction.gaerete\n\nor, if you want interaction.garaete to always be available when you import interaction, it can be interaction/__init__.py:\nimport gaerete\n\n",
"When you say\nimport devices.views.interaction\n\nand later\ninteraction.geraete\n\nPython looks for geraete in the __init__.py module in the interaction package.\nIf you want to see this works, you may include import geraete explicitly in the __init__.py module.\n",
"You should explicitly import the submodules if they are not imported in the __init__.py file:\nimport interaction.geraete\n\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"import",
"package",
"python"
] |
stackoverflow_0002628192_import_package_python.txt
|
Q:
python file manipulation
I have a directory /tmp/dir with two types of file names
/tmp/dir/abc-something-server.log
/tmp/dir/xyz-something-server.log
..
..
and
/tmp/dir/something-client.log
I need append a few lines (these lines are constant) to files end with "client.log"
line 1
line 2
line 3
line 4
append these four lines to files end with "client.log"
Yes I found open () "a" option will provide the desired result. but how to select the correct file that is, exclude server.log and choose client.log ?
and For files end with "server.log"
I needed to append after a keyword say "After-this".
"server.log " file has multiple entries of "After-this" I need to find the first entry of "After-this" and append above said four lines keep the remaining file as it is.
Any help will be great appreciated :) Thanks in advance.
A:
not tested
import os,glob,fileinput
root="/tmp"
path=os.path.join(root,"dir")
alines=["line 1\n","line 2\n","line 3\n","line 4\n"]
os.chdir(path)
# for clients
for clientfile in glob.glob("*.client.log"):
data=open(clientfile).readlines()
data.append(alines)
open("temp","w").write(''.join(data))
os.rename("temp",clientfile)
for svrfile in glob.glob("*.server.log"):
f=0
for line in fileinput.FileInput(svrfile,inplace=1):
ind=line.find("After-this")
if ind!=-1 and not f:
line=line[:ind+10] + ''.join(alines) + line[ind+10:]
f=1
print line
|
python file manipulation
|
I have a directory /tmp/dir with two types of file names
/tmp/dir/abc-something-server.log
/tmp/dir/xyz-something-server.log
..
..
and
/tmp/dir/something-client.log
I need append a few lines (these lines are constant) to files end with "client.log"
line 1
line 2
line 3
line 4
append these four lines to files end with "client.log"
Yes I found open () "a" option will provide the desired result. but how to select the correct file that is, exclude server.log and choose client.log ?
and For files end with "server.log"
I needed to append after a keyword say "After-this".
"server.log " file has multiple entries of "After-this" I need to find the first entry of "After-this" and append above said four lines keep the remaining file as it is.
Any help will be great appreciated :) Thanks in advance.
|
[
"not tested\nimport os,glob,fileinput\nroot=\"/tmp\"\npath=os.path.join(root,\"dir\")\nalines=[\"line 1\\n\",\"line 2\\n\",\"line 3\\n\",\"line 4\\n\"]\nos.chdir(path)\n# for clients\nfor clientfile in glob.glob(\"*.client.log\"):\n data=open(clientfile).readlines()\n data.append(alines)\n open(\"temp\",\"w\").write(''.join(data))\n os.rename(\"temp\",clientfile)\nfor svrfile in glob.glob(\"*.server.log\"):\n f=0\n for line in fileinput.FileInput(svrfile,inplace=1):\n ind=line.find(\"After-this\")\n if ind!=-1 and not f:\n line=line[:ind+10] + ''.join(alines) + line[ind+10:]\n f=1\n print line\n\n"
] |
[
3
] |
[] |
[] |
[
"file",
"python"
] |
stackoverflow_0002628370_file_python.txt
|
Q:
Best practise when using httplib2.Http() object
I'm writing a pythonic web API wrapper with a class like this
import httplib2
import urllib
class apiWrapper:
def __init__(self):
self.http = httplib2.Http()
def _http(self, url, method, dict):
'''
Im using this wrapper arround the http object
all the time inside the class
'''
params = urllib.urlencode(dict)
response, content = self.http.request(url,params,method)
as you can see I'm using the _http() method to simplify the interaction with the httplib2.Http() object. This method is called quite often inside the class and I'm wondering what's the best way to interact with this object:
create the object in the __init__ and then reuse it when the _http() method is called (as shown in the code above)
or create the httplib2.Http() object inside the method for every call of the _http() method (as shown in the code sample below)
import httplib2
import urllib
class apiWrapper:
def __init__(self):
def _http(self, url, method, dict):
'''Im using this wrapper arround the http object
all the time inside the class'''
http = httplib2.Http()
params = urllib.urlencode(dict)
response, content = http.request(url,params,method)
A:
Supplying 'connection': 'close' in your headers should according to the docs close the connection after a response is received.:
headers = {'connection': 'close'}
resp, content = h.request(url, headers=headers)
A:
You should keep the Http object if you reuse connections. It seems httplib2 is capable of reusing connections the way you use it in your first code, so this looks like a good approach.
At the same time, from a shallow inspection of the httplib2 code, it seems that httplib2 has no support for cleaning up unused connections, or to even notice when a server has decided to close a connection it no longer wants. If that is indeed the case, it looks like a bug in httplib2 to me - so I would rather use the standard library (httplib) instead.
|
Best practise when using httplib2.Http() object
|
I'm writing a pythonic web API wrapper with a class like this
import httplib2
import urllib
class apiWrapper:
def __init__(self):
self.http = httplib2.Http()
def _http(self, url, method, dict):
'''
Im using this wrapper arround the http object
all the time inside the class
'''
params = urllib.urlencode(dict)
response, content = self.http.request(url,params,method)
as you can see I'm using the _http() method to simplify the interaction with the httplib2.Http() object. This method is called quite often inside the class and I'm wondering what's the best way to interact with this object:
create the object in the __init__ and then reuse it when the _http() method is called (as shown in the code above)
or create the httplib2.Http() object inside the method for every call of the _http() method (as shown in the code sample below)
import httplib2
import urllib
class apiWrapper:
def __init__(self):
def _http(self, url, method, dict):
'''Im using this wrapper arround the http object
all the time inside the class'''
http = httplib2.Http()
params = urllib.urlencode(dict)
response, content = http.request(url,params,method)
|
[
"Supplying 'connection': 'close' in your headers should according to the docs close the connection after a response is received.:\nheaders = {'connection': 'close'}\nresp, content = h.request(url, headers=headers)\n\n",
"You should keep the Http object if you reuse connections. It seems httplib2 is capable of reusing connections the way you use it in your first code, so this looks like a good approach.\nAt the same time, from a shallow inspection of the httplib2 code, it seems that httplib2 has no support for cleaning up unused connections, or to even notice when a server has decided to close a connection it no longer wants. If that is indeed the case, it looks like a bug in httplib2 to me - so I would rather use the standard library (httplib) instead.\n"
] |
[
7,
2
] |
[] |
[] |
[
"httplib2",
"python"
] |
stackoverflow_0001248926_httplib2_python.txt
|
Q:
How can a total, complete beginner read source code?
I am a complete, total beginner in programming, although I do have knowledge of CSS and HTML.
I would like to learn Python. I downloaded lots of source code but the amount of files and the complexity really confuses me. I don't know where to begin. Is there a particular order I should look for?
Thanks.
EDIT: Sorry guys, I forgot to mention that I already have both the online tutorial and a couple of books handy. I basically I don't quite understand how to "dismantle" and understand complex source code, in order to grasp programming techniques and concepts.
EDIT2: Thanks for the extremely quick comments, guys. I really appreciate it. This website is awesome.
A:
Have you looked at these:
Python tutorial for total beginners?
What is the best quick-read Python book out there?
SO Python Book Search
A:
I would recommend you understand the basics. What are methods, classes, variables and so on. It would be important to understand the constructs you are seeing. If you don't understand those then it's just going to be a bunch of characters.
A:
To understand source code in any language, you first need to learn the language. It's as simple as that!
Usually, reading source code (as a sole activity) will hurt your head without giving much benefit in terms of learning the underlying language. You need a structured tour through carefully chosen small source code examples, such as a book or tutorial will give you.
Check Amazon out for books and Google for tutorials, try a few. The links offered by some of the other answers would also be a great starting point.
A:
There is no magic way to learn anything without reading and writing code yourself. If you get stuck there are always folks in SO who will help you.
A:
Donald Knuth suggests:
"It [is] basically the way you solve some kind of unknown puzzle -- make tables and charts and get a little more information here and make a hypothesis."
(From "Coders at Work", Chapter 15)
In my opinion, the easiest way to understand a program is to study the data structures first. Write them down, memorize them. Only then, think about how they move through program-time.
As an aside, it is sort of a shame how few books there are on code reading. "Coders at Work" is probably the best so far. Ironically, "Reading Code" is one of the worst so far.
A:
If you don't have any experience in programming, even the simplest code might be too hard to understand. Just start reading the docs/tutorial (http://docs.python.org/tutorial/index.html) and write your own small apps. You'll get hang of it soon and will be able to understand what others created.
A:
I would start with reading the Python tutorial. This wiki page looks good, too.
A:
try python "Python in a Nutshell" it gives you from a to z in python..
however, python code is "eye-fiendly" clear and simple to read unlike other languages
http://books.google.jo/books?id=vpTAq4dnmuAC&dq=Python+in+a+Nutshell,+2nd+Edition+(O%27Reilly,+2006)&printsec=frontcover&source=bl&ots=AOQ5A-IdxA&sig=zh6PwVhjlNt5MRKYUZKl65h1goU&hl=en&ei=A7kgS8SiBouh4Qbd6e34CQ&sa=X&oi=book_result&ct=result&resnum=8&ved=0CB8Q6AEwBw
A:
Maybe you have a project in mind that you want to code up? It's very hard to read what other people write, the best way to learn is to try something. Other people will have gone through the problems you will come across, and so why code is written the way it is may start to make sense. This is an excellent site to post questions, no matter how stupid you consider them.
|
How can a total, complete beginner read source code?
|
I am a complete, total beginner in programming, although I do have knowledge of CSS and HTML.
I would like to learn Python. I downloaded lots of source code but the amount of files and the complexity really confuses me. I don't know where to begin. Is there a particular order I should look for?
Thanks.
EDIT: Sorry guys, I forgot to mention that I already have both the online tutorial and a couple of books handy. I basically I don't quite understand how to "dismantle" and understand complex source code, in order to grasp programming techniques and concepts.
EDIT2: Thanks for the extremely quick comments, guys. I really appreciate it. This website is awesome.
|
[
"Have you looked at these:\nPython tutorial for total beginners?\nWhat is the best quick-read Python book out there?\nSO Python Book Search\n",
"I would recommend you understand the basics. What are methods, classes, variables and so on. It would be important to understand the constructs you are seeing. If you don't understand those then it's just going to be a bunch of characters. \n",
"To understand source code in any language, you first need to learn the language. It's as simple as that!\nUsually, reading source code (as a sole activity) will hurt your head without giving much benefit in terms of learning the underlying language. You need a structured tour through carefully chosen small source code examples, such as a book or tutorial will give you.\nCheck Amazon out for books and Google for tutorials, try a few. The links offered by some of the other answers would also be a great starting point.\n",
"There is no magic way to learn anything without reading and writing code yourself. If you get stuck there are always folks in SO who will help you.\n",
"Donald Knuth suggests:\n\"It [is] basically the way you solve some kind of unknown puzzle -- make tables and charts and get a little more information here and make a hypothesis.\"\n(From \"Coders at Work\", Chapter 15)\nIn my opinion, the easiest way to understand a program is to study the data structures first. Write them down, memorize them. Only then, think about how they move through program-time.\nAs an aside, it is sort of a shame how few books there are on code reading. \"Coders at Work\" is probably the best so far. Ironically, \"Reading Code\" is one of the worst so far.\n",
"If you don't have any experience in programming, even the simplest code might be too hard to understand. Just start reading the docs/tutorial (http://docs.python.org/tutorial/index.html) and write your own small apps. You'll get hang of it soon and will be able to understand what others created.\n",
"I would start with reading the Python tutorial. This wiki page looks good, too.\n",
"try python \"Python in a Nutshell\" it gives you from a to z in python..\nhowever, python code is \"eye-fiendly\" clear and simple to read unlike other languages\nhttp://books.google.jo/books?id=vpTAq4dnmuAC&dq=Python+in+a+Nutshell,+2nd+Edition+(O%27Reilly,+2006)&printsec=frontcover&source=bl&ots=AOQ5A-IdxA&sig=zh6PwVhjlNt5MRKYUZKl65h1goU&hl=en&ei=A7kgS8SiBouh4Qbd6e34CQ&sa=X&oi=book_result&ct=result&resnum=8&ved=0CB8Q6AEwBw\n",
"Maybe you have a project in mind that you want to code up? It's very hard to read what other people write, the best way to learn is to try something. Other people will have gone through the problems you will come across, and so why code is written the way it is may start to make sense. This is an excellent site to post questions, no matter how stupid you consider them.\n"
] |
[
9,
6,
3,
3,
3,
2,
1,
0,
0
] |
[] |
[] |
[
"code_readability",
"coding_style",
"python"
] |
stackoverflow_0001854827_code_readability_coding_style_python.txt
|
Q:
python reportlab - registerFont - django - font not available after some time
I'm wondering what is the best time to register a font for use in reportlab. I added the following line into my settings.py:
pdfmetrics.registerFont(TTFont('Calibri', FONT_DIR + '/fonts/Calibri.ttf'))
After this call the font is available for pdf generation. But it occurs that after a few days the font is not available anymore and I have to restart the django app, which leads to a re-registering of the font.
One approach I already tried was registering the font before each pdf generation call, which did not worked since it crashed each 3-5 call.
I just want to know if the settings.py is the correct place to register a font for reportlab and if yes, what could be the reason that the font is not available after a few days anymore!?
--Edit--
actually we discovered that there are some issues with reportlab and mod-wsgi. we switched to fast-cgi and never saw this problem again.
A:
I don't know what anything about how reportlabs works, but I can say about django.
Django doesn't warrant that settings will be imported once (may be, there are any other problems) and it's not a good place for such things. Usually, urls.py is used for objects registration (for example, admin.autodiscover).
|
python reportlab - registerFont - django - font not available after some time
|
I'm wondering what is the best time to register a font for use in reportlab. I added the following line into my settings.py:
pdfmetrics.registerFont(TTFont('Calibri', FONT_DIR + '/fonts/Calibri.ttf'))
After this call the font is available for pdf generation. But it occurs that after a few days the font is not available anymore and I have to restart the django app, which leads to a re-registering of the font.
One approach I already tried was registering the font before each pdf generation call, which did not worked since it crashed each 3-5 call.
I just want to know if the settings.py is the correct place to register a font for reportlab and if yes, what could be the reason that the font is not available after a few days anymore!?
--Edit--
actually we discovered that there are some issues with reportlab and mod-wsgi. we switched to fast-cgi and never saw this problem again.
|
[
"I don't know what anything about how reportlabs works, but I can say about django.\nDjango doesn't warrant that settings will be imported once (may be, there are any other problems) and it's not a good place for such things. Usually, urls.py is used for objects registration (for example, admin.autodiscover).\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python",
"reportlab"
] |
stackoverflow_0002628377_django_python_reportlab.txt
|
Q:
In Django, how to create tables from an SQL file when syncdb is run
How do I make syncdb execute SQL queries (for table creation) defined by me, rather then generating tables automatically.
I'm looking for this solution as some particular models in my app represent SQL-table-views for a legacy-database table.
So, I've created their SQL-views in my django-DB like this:
CREATE VIEW legacy_series AS SELECT * FROM legacy.series;
I have a reverse engineered model that represents the above view/legacytable. But whenever I run syncdb, I have to create all the views first by running sql scripts, otherwise syncdb simply creates tables for them (if a view is not found).
How do I make syncdb run the above mentioned SQL?
A:
There are 2 possible approaches I know of to adapt your models to a legacy database table (without using views that is):
1) Run python manage.py inspectdb within your project. This will generate models for existing database tables, you can then continue to work with those.
2) Modify your tables with some specific settings. First of all you define the table name in your model by setting the db_table option in your meta options. Secondly you define for each field the column name to match your legacy database by setting the db_column option. Note there are other db_ options listed you possibly could use to match your legacy database.
If you really want the views approach an (ugly) workaround is possible, you can define custom sql commands per application model. This file is found in "application"/sql/"model".sql . Django will call this sql's after it created all tables. You can try to specify DROP statements for the generated tables followed by your view create statement in this file. Note that this will be a bit tricky for the tables with foreign keys as django guarantees no order of execution of these files (so stuffing all statements in one .sql will be the easiest way I think, I've never tried this before).
A:
You could use unmanaged models for your reverse-engineered models, and initial SQL scripts for creating your views.
EDIT:
A bit more detailed answer. When you use unmanaged models, syncdb will not create your database tables for you, so you have to take care of it yourself. An important point is the table name, and how django maps Model classes to table names, I suggest you read the doc on that point.
Basically, your Series model will look like that :
class Series(models.Model):
# model fields...
...
class Meta:
managed = False
db_table = "legacy_series"
Then, you can put your SQL commands, in the yourapp/sql/series.sql file :
### yourapp/sql/series.sql
CREATE VIEW legacy_series AS SELECT * FROM legacy.series;
You can then syncdb as usual, and start using your legacy models.
|
In Django, how to create tables from an SQL file when syncdb is run
|
How do I make syncdb execute SQL queries (for table creation) defined by me, rather then generating tables automatically.
I'm looking for this solution as some particular models in my app represent SQL-table-views for a legacy-database table.
So, I've created their SQL-views in my django-DB like this:
CREATE VIEW legacy_series AS SELECT * FROM legacy.series;
I have a reverse engineered model that represents the above view/legacytable. But whenever I run syncdb, I have to create all the views first by running sql scripts, otherwise syncdb simply creates tables for them (if a view is not found).
How do I make syncdb run the above mentioned SQL?
|
[
"There are 2 possible approaches I know of to adapt your models to a legacy database table (without using views that is):\n1) Run python manage.py inspectdb within your project. This will generate models for existing database tables, you can then continue to work with those.\n2) Modify your tables with some specific settings. First of all you define the table name in your model by setting the db_table option in your meta options. Secondly you define for each field the column name to match your legacy database by setting the db_column option. Note there are other db_ options listed you possibly could use to match your legacy database.\nIf you really want the views approach an (ugly) workaround is possible, you can define custom sql commands per application model. This file is found in \"application\"/sql/\"model\".sql . Django will call this sql's after it created all tables. You can try to specify DROP statements for the generated tables followed by your view create statement in this file. Note that this will be a bit tricky for the tables with foreign keys as django guarantees no order of execution of these files (so stuffing all statements in one .sql will be the easiest way I think, I've never tried this before).\n",
"You could use unmanaged models for your reverse-engineered models, and initial SQL scripts for creating your views.\nEDIT:\nA bit more detailed answer. When you use unmanaged models, syncdb will not create your database tables for you, so you have to take care of it yourself. An important point is the table name, and how django maps Model classes to table names, I suggest you read the doc on that point.\nBasically, your Series model will look like that :\nclass Series(models.Model):\n # model fields...\n ...\n\n class Meta:\n managed = False\n db_table = \"legacy_series\"\n\nThen, you can put your SQL commands, in the yourapp/sql/series.sql file :\n### yourapp/sql/series.sql\nCREATE VIEW legacy_series AS SELECT * FROM legacy.series;\n\nYou can then syncdb as usual, and start using your legacy models.\n"
] |
[
5,
4
] |
[] |
[] |
[
"django",
"django_models",
"mysql",
"python",
"views"
] |
stackoverflow_0002628431_django_django_models_mysql_python_views.txt
|
Q:
Looking for a good example usage of get_or _create in Django views and raising a Form error
I am looking for a good example of how to achieve the following:
I would like to use get_or_create to check whether an object already exists in my database. If it does not, then it will be created. If it does exist, then I will not create the new object, but need to raise a form error to inform the user that they need to enter different data (for example, a different username).
The view contains:
p, created = Person.objects.get_or_create(
email = registration_form.cleaned_data['email'],
defaults = {
'creationDate': datetime.datetime.now(),
'dateOfBirth': datetime.date(1970,1,1)
})
So 'p' will contain the existing Person if it exists, or the new Person if not. I would like to act on the boolean value in 'created' in order to skip over saving the Person and re-display the registration_form and raise an appropriate form validation error.
The alternative I'm considering is doing a check in a custom Form validation method to see whether a Person exists with the data in the provided 'email' field, and just raising a validation error.
A:
This is not a good example usage of get_or_create. Form validation (which you obviously try to do) comes before saving and those shouldn't be mixed at all. You should be sure your form validated before saving, but the 'already exists' check is part of the validating.
In your form's clean() method, write something like this:
try:
Person.objects.get(email=...)
raise forms.ValidationError(...)
except Person.DoesNotExist:
pass
This is the alternative you proposed and is the most sensible solution.
Good usage of get_or_create is for example a tagging library, where you want new tags to be created on the fly or information about old tags collected, without having to write try/except all the time.
Edit: also, if you wanted to do this to avoid the separated get/create cycle later on, make sure you use modelforms. The save method of modelforms returns you the just created instance.
|
Looking for a good example usage of get_or _create in Django views and raising a Form error
|
I am looking for a good example of how to achieve the following:
I would like to use get_or_create to check whether an object already exists in my database. If it does not, then it will be created. If it does exist, then I will not create the new object, but need to raise a form error to inform the user that they need to enter different data (for example, a different username).
The view contains:
p, created = Person.objects.get_or_create(
email = registration_form.cleaned_data['email'],
defaults = {
'creationDate': datetime.datetime.now(),
'dateOfBirth': datetime.date(1970,1,1)
})
So 'p' will contain the existing Person if it exists, or the new Person if not. I would like to act on the boolean value in 'created' in order to skip over saving the Person and re-display the registration_form and raise an appropriate form validation error.
The alternative I'm considering is doing a check in a custom Form validation method to see whether a Person exists with the data in the provided 'email' field, and just raising a validation error.
|
[
"This is not a good example usage of get_or_create. Form validation (which you obviously try to do) comes before saving and those shouldn't be mixed at all. You should be sure your form validated before saving, but the 'already exists' check is part of the validating.\nIn your form's clean() method, write something like this:\ntry:\n Person.objects.get(email=...)\n raise forms.ValidationError(...)\nexcept Person.DoesNotExist:\n pass\n\nThis is the alternative you proposed and is the most sensible solution.\nGood usage of get_or_create is for example a tagging library, where you want new tags to be created on the fly or information about old tags collected, without having to write try/except all the time.\nEdit: also, if you wanted to do this to avoid the separated get/create cycle later on, make sure you use modelforms. The save method of modelforms returns you the just created instance.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_forms",
"python"
] |
stackoverflow_0002628755_django_django_forms_python.txt
|
Q:
What's the purpose of "import package"?
As I just found out import package does not make the package's modules available through package.module. The same obviously holds true for from package import subpackage as well as from package import *
What's the purpose of importing a package at all then if I can't access its submodules but only the objects defined in __init__.py?
It makes sense to me that from package import * would bloat the namespace, which, however, doesn't apply in case of the other two ways! I also understand that loading all submodules might take a long time. But I don't know what these unwanted side-effects, "that should only happen when the sub-module is explicitly imported", are which the author of the previous link mentions.
To me it looks like doing an import package[.subpackage] (or from package import subpackage) makes absolutely no sense if I don't exactly want to access objects provided in __init__.py.
Are those unwanted side effects really that serious that the language actually has to protect the programmer from causing them? Actually, I thought that Python was a little bit more about "If the programmer wants to do it, let him do it."
In my case, I really do want to import all submodules with the single statement from package import subpackage, because I need all of them!
Telling Python in the __init__.py file which submodules I'm exactly talking about (all of them!) is quite cumbersome from my point of view.
Please enlighten me. :)
A:
It's up to the package if it automatically imports submodules in its __init__.py or not. For example os automatically imports os.path, so this works:
import os
print os.path.abspath('somefile')
So the creator of the package can decide what is best. If automatically loading all submodules would take a rather long time and would rarely be needed, it probably shouldn't be done. If all the submodules are always required they probably should be imported automatically.
If you think a package imports not enough you could work around it by writing your own wrapper module that does all the imports, and then use that with from wrappermodule import *.
A:
As said, the solution is to import each submodule. You can use a hack to avoid listing them:
__init__.py
import os
def import_sub():
for fn in os.listdir(os.path.dirname(__file__)):
if fn.endswith(".py") and fn != "__init__.py":
__import__(".".join([__name__, os.path.basename(fn)[:-3]]), level=0)
import_sub()
del import_sub # if desired
This will easily break under some circumstances. However, it will handle the common case and could be temporarily suitable.
|
What's the purpose of "import package"?
|
As I just found out import package does not make the package's modules available through package.module. The same obviously holds true for from package import subpackage as well as from package import *
What's the purpose of importing a package at all then if I can't access its submodules but only the objects defined in __init__.py?
It makes sense to me that from package import * would bloat the namespace, which, however, doesn't apply in case of the other two ways! I also understand that loading all submodules might take a long time. But I don't know what these unwanted side-effects, "that should only happen when the sub-module is explicitly imported", are which the author of the previous link mentions.
To me it looks like doing an import package[.subpackage] (or from package import subpackage) makes absolutely no sense if I don't exactly want to access objects provided in __init__.py.
Are those unwanted side effects really that serious that the language actually has to protect the programmer from causing them? Actually, I thought that Python was a little bit more about "If the programmer wants to do it, let him do it."
In my case, I really do want to import all submodules with the single statement from package import subpackage, because I need all of them!
Telling Python in the __init__.py file which submodules I'm exactly talking about (all of them!) is quite cumbersome from my point of view.
Please enlighten me. :)
|
[
"It's up to the package if it automatically imports submodules in its __init__.py or not. For example os automatically imports os.path, so this works:\nimport os\nprint os.path.abspath('somefile')\n\nSo the creator of the package can decide what is best. If automatically loading all submodules would take a rather long time and would rarely be needed, it probably shouldn't be done. If all the submodules are always required they probably should be imported automatically.\nIf you think a package imports not enough you could work around it by writing your own wrapper module that does all the imports, and then use that with from wrappermodule import *.\n",
"As said, the solution is to import each submodule. You can use a hack to avoid listing them:\n__init__.py\nimport os\n\ndef import_sub():\n for fn in os.listdir(os.path.dirname(__file__)):\n if fn.endswith(\".py\") and fn != \"__init__.py\":\n __import__(\".\".join([__name__, os.path.basename(fn)[:-3]]), level=0)\nimport_sub()\ndel import_sub # if desired\n\nThis will easily break under some circumstances. However, it will handle the common case and could be temporarily suitable.\n"
] |
[
4,
1
] |
[] |
[] |
[
"import",
"package",
"python"
] |
stackoverflow_0002628783_import_package_python.txt
|
Q:
TypeError: coercing to Unicode: need string or buffer, User found
i have to crawl last.fm for users (university exercise). I'm new to python and get following error:
Traceback (most recent call last):
File "crawler.py", line 23, in <module>
for f in user_.get_friends(limit='200'):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 2717, in get_friends
for node in _collect_nodes(limit, self, "user.getFriends", False):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 3409, in _collect_nodes
doc = sender._request(method_name, cacheable, params)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 969, in _request
return _Request(self.network, method_name, params).execute(cacheable)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 721, in __init__
self.sign_it()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 727, in sign_it
self.params['api_sig'] = self._get_signature()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 740, in _get_signature
string += self.params[name]
TypeError: coercing to Unicode: need string or buffer, User found
i use the pylast lib for crawling. what i want to do:
i want to get a users friends and the friends of the users friends. the error occurs, when i have a for loop in another for loop. here's the code:
network = pylast.get_lastfm_network(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash)
user = network.get_user("vidarnelson")
friends = user.get_friends(limit='200')
i = 1
for friend in friends:
user_ = network.get_user(friend)
print '#%d %s' % (i, friend)
i = i + 1
for f in user_.get_friends(limit='200'):
print f
any advice?
thanks in advance. regards!
A:
It looks like get_friends will return a list of User objects, so you don't need to call get_user on its entries. Just use:
for friend in friends:
for f in friend.get_friends(limit='200'):
...
|
TypeError: coercing to Unicode: need string or buffer, User found
|
i have to crawl last.fm for users (university exercise). I'm new to python and get following error:
Traceback (most recent call last):
File "crawler.py", line 23, in <module>
for f in user_.get_friends(limit='200'):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 2717, in get_friends
for node in _collect_nodes(limit, self, "user.getFriends", False):
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 3409, in _collect_nodes
doc = sender._request(method_name, cacheable, params)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 969, in _request
return _Request(self.network, method_name, params).execute(cacheable)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 721, in __init__
self.sign_it()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 727, in sign_it
self.params['api_sig'] = self._get_signature()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pylast.py", line 740, in _get_signature
string += self.params[name]
TypeError: coercing to Unicode: need string or buffer, User found
i use the pylast lib for crawling. what i want to do:
i want to get a users friends and the friends of the users friends. the error occurs, when i have a for loop in another for loop. here's the code:
network = pylast.get_lastfm_network(api_key = API_KEY, api_secret = API_SECRET, username = username, password_hash = password_hash)
user = network.get_user("vidarnelson")
friends = user.get_friends(limit='200')
i = 1
for friend in friends:
user_ = network.get_user(friend)
print '#%d %s' % (i, friend)
i = i + 1
for f in user_.get_friends(limit='200'):
print f
any advice?
thanks in advance. regards!
|
[
"It looks like get_friends will return a list of User objects, so you don't need to call get_user on its entries. Just use:\nfor friend in friends:\n for f in friend.get_friends(limit='200'):\n ...\n\n"
] |
[
6
] |
[] |
[] |
[
"last.fm",
"loops",
"python",
"typeerror",
"web_crawler"
] |
stackoverflow_0002629524_last.fm_loops_python_typeerror_web_crawler.txt
|
Q:
how to create a pure browser/javascript search engine for a bunch of static files?
I was wondering if there exists some kind of indexer (in python language for exemple) that would take a bunch of html files and create an index in javascript.
In the solution, these javascript files would then be used to create a pure browser search engine.
Jerome
A:
A bit old and not in python:
http://jssindex.sourceforge.net/
A:
another very simple option is
http://dentedreality.com.au/projects/jssearch/
|
how to create a pure browser/javascript search engine for a bunch of static files?
|
I was wondering if there exists some kind of indexer (in python language for exemple) that would take a bunch of html files and create an index in javascript.
In the solution, these javascript files would then be used to create a pure browser search engine.
Jerome
|
[
"A bit old and not in python:\nhttp://jssindex.sourceforge.net/\n",
"another very simple option is\nhttp://dentedreality.com.au/projects/jssearch/\n"
] |
[
1,
1
] |
[] |
[] |
[
"full_text_search",
"javascript",
"python",
"search_engine"
] |
stackoverflow_0002607283_full_text_search_javascript_python_search_engine.txt
|
Q:
python sqlite fails
My program uses sqlite3 plus python. It works fine with python 2.6.2
I moved it another machine and installed 2.6.4 and running the program gave me this error
File "", line 1, in
File "/opt/python-2.6.4/lib/python2.6/sqlite3/init.py", line 24, in
from dbapi2 import *
File "/opt/python-2.6.4/lib/python2.6/sqlite3/dbapi2.py", line 27, in
from _sqlite3 import *
ImportError: No module named _sqlite3
A:
See cannot-import-sqlite-with-python-2-6.
You are missing the .so (shared object) - probably an installation step.
|
python sqlite fails
|
My program uses sqlite3 plus python. It works fine with python 2.6.2
I moved it another machine and installed 2.6.4 and running the program gave me this error
File "", line 1, in
File "/opt/python-2.6.4/lib/python2.6/sqlite3/init.py", line 24, in
from dbapi2 import *
File "/opt/python-2.6.4/lib/python2.6/sqlite3/dbapi2.py", line 27, in
from _sqlite3 import *
ImportError: No module named _sqlite3
|
[
"See cannot-import-sqlite-with-python-2-6.\nYou are missing the .so (shared object) - probably an installation step.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"sqlite"
] |
stackoverflow_0002629789_python_sqlite.txt
|
Q:
app-engine-rest-server to raise KeyError("name %s already used" % model_name)
I'm playing with the project appengine-rest-server to create the REST webservices for all the existing models. I got a strange error, the first time I query the browser: http://localhost:8080/rest/metadata/user, it gives me the result:
<xs:schema>
−
<xs:element name="user">
−
<xs:complexType>
−
<xs:sequence>
<xs:element maxOccurs="1" minOccurs="0" name="key" type="xs:normalizedString"/>
<xs:element maxOccurs="1" minOccurs="0" name="surname" type="xs:string"/>
<xs:element maxOccurs="1" minOccurs="0" name="firstname" type="xs:string"/>
<xs:element maxOccurs="1" minOccurs="0" name="ages" type="xs:long"/>
<xs:element maxOccurs="1" minOccurs="0" name="sex" type="xs:boolean"/>
<xs:element maxOccurs="1" minOccurs="0" name="updatedDate" type="xs:dateTime"/>
<xs:element maxOccurs="1" minOccurs="0" name="createdDate" type="xs:dateTime"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
But refreshing the page, gives me this error:
Traceback (most recent call last):
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3185, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3128, in _Dispatch
base_env_dict=env_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 515, in Dispatch
base_env_dict=base_env_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2387, in Dispatch
self._module_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2297, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2195, in ExecuteOrImportScript
script_module.main()
File "/Users/foo/Documents/AppEngine/helloworld/main.py", line 48, in main
rest.Dispatcher.add_models({"user": UserModel})
File "/Users/foo/Documents/AppEngine/helloworld/rest/__init__.py", line 845, in add_models
cls.add_model(model_name, model_type)
File "/Users/foo/Documents/AppEngine/helloworld/rest/__init__.py", line 863, in add_model
raise KeyError("name %s already used" % model_name)
KeyError: 'name user already used'
Can someone give me the explanation on why it happens? Restarting the server, run on the browser again I get the xml result, but refreshing causes the error. Is it a bug in the appengine-rest-server application or it is in my code? My helloworld application is available for download here.
A:
Since you have a main() function, the App Engine caches your module and imports. Hence within the same runtime, you may call add_models() more than once. If you move the rest initialization code to module level (or into a function that gets called once during module initialization, not during every call to main()) it should work.
|
app-engine-rest-server to raise KeyError("name %s already used" % model_name)
|
I'm playing with the project appengine-rest-server to create the REST webservices for all the existing models. I got a strange error, the first time I query the browser: http://localhost:8080/rest/metadata/user, it gives me the result:
<xs:schema>
−
<xs:element name="user">
−
<xs:complexType>
−
<xs:sequence>
<xs:element maxOccurs="1" minOccurs="0" name="key" type="xs:normalizedString"/>
<xs:element maxOccurs="1" minOccurs="0" name="surname" type="xs:string"/>
<xs:element maxOccurs="1" minOccurs="0" name="firstname" type="xs:string"/>
<xs:element maxOccurs="1" minOccurs="0" name="ages" type="xs:long"/>
<xs:element maxOccurs="1" minOccurs="0" name="sex" type="xs:boolean"/>
<xs:element maxOccurs="1" minOccurs="0" name="updatedDate" type="xs:dateTime"/>
<xs:element maxOccurs="1" minOccurs="0" name="createdDate" type="xs:dateTime"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
But refreshing the page, gives me this error:
Traceback (most recent call last):
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3185, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 3128, in _Dispatch
base_env_dict=env_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 515, in Dispatch
base_env_dict=base_env_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2387, in Dispatch
self._module_dict)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2297, in ExecuteCGI
reset_modules = exec_script(handler_path, cgi_path, hook)
File "/Users/foo/Documents/AppEngine/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver.py", line 2195, in ExecuteOrImportScript
script_module.main()
File "/Users/foo/Documents/AppEngine/helloworld/main.py", line 48, in main
rest.Dispatcher.add_models({"user": UserModel})
File "/Users/foo/Documents/AppEngine/helloworld/rest/__init__.py", line 845, in add_models
cls.add_model(model_name, model_type)
File "/Users/foo/Documents/AppEngine/helloworld/rest/__init__.py", line 863, in add_model
raise KeyError("name %s already used" % model_name)
KeyError: 'name user already used'
Can someone give me the explanation on why it happens? Restarting the server, run on the browser again I get the xml result, but refreshing causes the error. Is it a bug in the appengine-rest-server application or it is in my code? My helloworld application is available for download here.
|
[
"Since you have a main() function, the App Engine caches your module and imports. Hence within the same runtime, you may call add_models() more than once. If you move the rest initialization code to module level (or into a function that gets called once during module initialization, not during every call to main()) it should work.\n"
] |
[
3
] |
[] |
[] |
[
"google_app_engine",
"python",
"rest"
] |
stackoverflow_0002629813_google_app_engine_python_rest.txt
|
Q:
Copying contents of a model
If there exists an old data of a model say ,
query=Emp.objects.filter(pk=profile.id)
Is there a easier way to copy the same values into the same model again..
Now that the id will be different so..
I have this requirement.
Thanks..
A:
object = Emp.objects.get(pk=profile.id)
object.save(force_insert=True)
It's much more explicit then removing primary key's value. See also "forcing an insert or update" in Django documentation.
A:
Unless you have a complex model with inheritance, this should work:
query.pk = None
query.save() #Will insert new record
For the other case I found a snippet here, did not test it however.
|
Copying contents of a model
|
If there exists an old data of a model say ,
query=Emp.objects.filter(pk=profile.id)
Is there a easier way to copy the same values into the same model again..
Now that the id will be different so..
I have this requirement.
Thanks..
|
[
"object = Emp.objects.get(pk=profile.id)\nobject.save(force_insert=True)\n\nIt's much more explicit then removing primary key's value. See also \"forcing an insert or update\" in Django documentation.\n",
"Unless you have a complex model with inheritance, this should work:\nquery.pk = None\nquery.save() #Will insert new record\n\nFor the other case I found a snippet here, did not test it however.\n"
] |
[
7,
3
] |
[] |
[] |
[
"django",
"django_models",
"django_queryset",
"django_views",
"python"
] |
stackoverflow_0002628893_django_django_models_django_queryset_django_views_python.txt
|
Q:
Python - multi-line array
in c++ I can wrote:
int someArray[8][8];
for (int i=0; i < 7; i++)
for (int j=0; j < 7; j++)
someArray[i][j] = 0;
And how can I initialize multi-line arrays in python?
I tried:
array = [[],[]]
for i in xrange(8):
for j in xrange(8):
array[i][j] = 0
A:
>>> [[0]*8 for x in xrange(8)]
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
>>>
A:
You asked about initializing a list of lists. Its a very useful data structure, but it has an important difference from the 2D array in C++: There are no guarantees that all lines have the same length (i.e, that len(a[0])==len(a[1]) (while in C++ you do have that guarantee).
So another solution that might be handy, is using NumPy's array datatype, like this:
import numpy as np
array = np.zeros((8,8))
A:
Here is a shorter way:
array = []
for i in xrange(8):
array.append( [0] * 8 )
A:
array = [[0]*8 for i in xrange(8)]
A:
[[0]*8 for x in range(8)]
|
Python - multi-line array
|
in c++ I can wrote:
int someArray[8][8];
for (int i=0; i < 7; i++)
for (int j=0; j < 7; j++)
someArray[i][j] = 0;
And how can I initialize multi-line arrays in python?
I tried:
array = [[],[]]
for i in xrange(8):
for j in xrange(8):
array[i][j] = 0
|
[
">>> [[0]*8 for x in xrange(8)]\n[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]\n>>>\n\n",
"You asked about initializing a list of lists. Its a very useful data structure, but it has an important difference from the 2D array in C++: There are no guarantees that all lines have the same length (i.e, that len(a[0])==len(a[1]) (while in C++ you do have that guarantee).\nSo another solution that might be handy, is using NumPy's array datatype, like this:\nimport numpy as np\narray = np.zeros((8,8))\n\n",
"Here is a shorter way:\narray = []\nfor i in xrange(8):\n array.append( [0] * 8 )\n\n",
"array = [[0]*8 for i in xrange(8)]\n\n",
"[[0]*8 for x in range(8)]\n\n"
] |
[
7,
7,
3,
3,
2
] |
[] |
[] |
[
"arrays",
"python"
] |
stackoverflow_0002630211_arrays_python.txt
|
Q:
django create list from a queryset list
I have a list of objects from a django queryset, e.g.
my_list = MyObject.objects.filter(variable=something)
MyObject has a field called year which is set to a particular year, e.g. 2005, 2007, 2009
I want to take my_list and create a dictionary of years which holds all MyObject values for that year. e.g.
my_dict['2005'] = list of objects from my_list which match year = 2005
my_dict['2006'] = list of objects from my_list which match year = 2006
my_dict['2007'] = list of objects from my_list which match year = 2007
my_dict['2008'] = list of objects from my_list which match year = 2008
Can anyone tell me the best way of doing this. I already have the first bit sorted, e.g getting my_list. I just need it splitting down into years. I have attempted to write it myself but it became very inefficient with a lot of for loops and db queries
Thanks
A:
import collections
mydict = collections.defaultdict(list)
for obj in my_list:
mydict[obj.year].append(obj)
A:
(Don't call the queryset 'my_list', it's not actually a list but a queryset. Call it something like 'my_objects'.)
my_dict = {}
for obj in my_objects:
my_dict.setdefault(obj.year, []).append(obj)
|
django create list from a queryset list
|
I have a list of objects from a django queryset, e.g.
my_list = MyObject.objects.filter(variable=something)
MyObject has a field called year which is set to a particular year, e.g. 2005, 2007, 2009
I want to take my_list and create a dictionary of years which holds all MyObject values for that year. e.g.
my_dict['2005'] = list of objects from my_list which match year = 2005
my_dict['2006'] = list of objects from my_list which match year = 2006
my_dict['2007'] = list of objects from my_list which match year = 2007
my_dict['2008'] = list of objects from my_list which match year = 2008
Can anyone tell me the best way of doing this. I already have the first bit sorted, e.g getting my_list. I just need it splitting down into years. I have attempted to write it myself but it became very inefficient with a lot of for loops and db queries
Thanks
|
[
"import collections\n\nmydict = collections.defaultdict(list)\n\nfor obj in my_list:\n mydict[obj.year].append(obj)\n\n",
"(Don't call the queryset 'my_list', it's not actually a list but a queryset. Call it something like 'my_objects'.)\nmy_dict = {}\nfor obj in my_objects:\n my_dict.setdefault(obj.year, []).append(obj)\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002630680_django_python.txt
|
Q:
python: sorting
hi im doing a loop so i could get dict of data, but since its a dict it's
sorting alphabetical and not as i push it trought the loop ...
is it possible to somehow turn off alphabetical sorting?
here is how do i do that
data = {}
for item in container:
data[item] = {}
...
for key, val in item_container.iteritems():
...
data[item][key] = val
whitch give me something like this
data = {
A : { K1 : V1, K2 : V2, K3 : V3 },
B : { K1 : V1, K2 : V2, K3 : V3 },
C : { K1 : V1, K2 : V2, K3 : V3 }
}
and i want it to be as i was going throught the loop, e.g.
data = {
B : {K2 : V2, K3 : V3, K1 : V1},
A : {K1 : V1, K2 : V2, K3 : V3},
C : {K3 : V3, K1 : V1, K2 : V2}
}
A:
If you really need to use a dictionary and not a list, take a look at the new OrderedDict (Python 3.1, soon to be available in Python 2.7, too). This will preserve the order in which its items were added.
from collections import OrderedDict
data = OrderedDict()
for item in container:
data[item] = OrderedDict()
...
for key, val in item_container.iteritems():
...
data[item][key] = val
A:
You should not be relying on the sort order of data in a dict; since it is just a collection of key/value pairs, the ordering is not guaranteed by the underlying implementation and could change in a future version.
A:
You can use a list of lists, instead of a dict of dicts. Each element would be a tuple of (key,value). Of course, this means you won't be able to retrieve elements by keys, but it will preserve order. I'm not sure if its a good idea, because I don't really know what you're trying to do, but its an option.
|
python: sorting
|
hi im doing a loop so i could get dict of data, but since its a dict it's
sorting alphabetical and not as i push it trought the loop ...
is it possible to somehow turn off alphabetical sorting?
here is how do i do that
data = {}
for item in container:
data[item] = {}
...
for key, val in item_container.iteritems():
...
data[item][key] = val
whitch give me something like this
data = {
A : { K1 : V1, K2 : V2, K3 : V3 },
B : { K1 : V1, K2 : V2, K3 : V3 },
C : { K1 : V1, K2 : V2, K3 : V3 }
}
and i want it to be as i was going throught the loop, e.g.
data = {
B : {K2 : V2, K3 : V3, K1 : V1},
A : {K1 : V1, K2 : V2, K3 : V3},
C : {K3 : V3, K1 : V1, K2 : V2}
}
|
[
"If you really need to use a dictionary and not a list, take a look at the new OrderedDict (Python 3.1, soon to be available in Python 2.7, too). This will preserve the order in which its items were added.\nfrom collections import OrderedDict\ndata = OrderedDict()\nfor item in container:\n data[item] = OrderedDict()\n ...\n for key, val in item_container.iteritems():\n ...\n data[item][key] = val\n\n",
"You should not be relying on the sort order of data in a dict; since it is just a collection of key/value pairs, the ordering is not guaranteed by the underlying implementation and could change in a future version.\n",
"You can use a list of lists, instead of a dict of dicts. Each element would be a tuple of (key,value). Of course, this means you won't be able to retrieve elements by keys, but it will preserve order. I'm not sure if its a good idea, because I don't really know what you're trying to do, but its an option.\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"dictionary",
"loops",
"python",
"sorting"
] |
stackoverflow_0002630241_dictionary_loops_python_sorting.txt
|
Q:
sqlalchemy relation through another (declarative)
Is anyone familiar with ActiveRecord's "has_many :through" relations for models? I'm not really a Rails guy, but that's basically what I'm trying to do.
As a contrived example consider Projects, Programmers, and Assignments:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import Integer, String, Text
from sqlalchemy.orm import relation
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Assignment(Base):
__tablename__ = 'assignment'
id = Column(Integer, primary_key=True)
description = Column(Text)
programmer_id = Column(Integer, ForeignKey('programmer.id'))
project_id = Column(Integer, ForeignKey('project.id'))
def __init__(self, description=description):
self.description = description
def __repr__(self):
return '<Assignment("%s")>' % self.description
class Programmer(Base):
__tablename__ = 'programmer'
id = Column(Integer, primary_key=True)
name = Column(String(64))
assignments = relation("Assignment", backref='programmer')
def __init__(self, name=name):
self.name = name
def __repr__(self):
return '<Programmer("%s")>' % self.name
class Project(Base):
__tablename__ = 'project'
id = Column(Integer, primary_key=True)
name = Column(String(64))
description = Column(Text)
assignments = relation("Assignment", backref='project')
def __init__(self, name=name, description=description):
self.name = name
self.description = description
def __repr__(self):
return '<Project("%s", "%s...")>' % (self.name, self.description[:10])
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
Projects have many Assignments.
Programmers have many Assignments. (understatement?)
But in my office at least, Programmers also have many Projects - I'd like this relationship to be inferred through the Assignments assigned to the Programmer.
I'd like the Programmer model to have a attribute "projects" which will return a list of Projects associated to the Programmer through the Assignment model.
me = session.query(Programmer).filter_by(name='clay').one()
projects = session.query(Project).\
join(Project.assignments).\
join(Assignment.programmer).\
filter(Programmer.id==me.id).all()
How can I describe this relationship clearly and simply using the sqlalchemy declarative syntax?
Thanks!
A:
There are two ways I see:
Define a relation Programmer.projects with secondary='assignment'.
I define Assignment.project as relation and Programmer.projects as association_proxy('assignments', 'project') (probably you'd also like to define a creator). See Simplifying Association Object Relationships chapter for more information.
|
sqlalchemy relation through another (declarative)
|
Is anyone familiar with ActiveRecord's "has_many :through" relations for models? I'm not really a Rails guy, but that's basically what I'm trying to do.
As a contrived example consider Projects, Programmers, and Assignments:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, ForeignKey
from sqlalchemy.types import Integer, String, Text
from sqlalchemy.orm import relation
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Assignment(Base):
__tablename__ = 'assignment'
id = Column(Integer, primary_key=True)
description = Column(Text)
programmer_id = Column(Integer, ForeignKey('programmer.id'))
project_id = Column(Integer, ForeignKey('project.id'))
def __init__(self, description=description):
self.description = description
def __repr__(self):
return '<Assignment("%s")>' % self.description
class Programmer(Base):
__tablename__ = 'programmer'
id = Column(Integer, primary_key=True)
name = Column(String(64))
assignments = relation("Assignment", backref='programmer')
def __init__(self, name=name):
self.name = name
def __repr__(self):
return '<Programmer("%s")>' % self.name
class Project(Base):
__tablename__ = 'project'
id = Column(Integer, primary_key=True)
name = Column(String(64))
description = Column(Text)
assignments = relation("Assignment", backref='project')
def __init__(self, name=name, description=description):
self.name = name
self.description = description
def __repr__(self):
return '<Project("%s", "%s...")>' % (self.name, self.description[:10])
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
Projects have many Assignments.
Programmers have many Assignments. (understatement?)
But in my office at least, Programmers also have many Projects - I'd like this relationship to be inferred through the Assignments assigned to the Programmer.
I'd like the Programmer model to have a attribute "projects" which will return a list of Projects associated to the Programmer through the Assignment model.
me = session.query(Programmer).filter_by(name='clay').one()
projects = session.query(Project).\
join(Project.assignments).\
join(Assignment.programmer).\
filter(Programmer.id==me.id).all()
How can I describe this relationship clearly and simply using the sqlalchemy declarative syntax?
Thanks!
|
[
"There are two ways I see:\n\nDefine a relation Programmer.projects with secondary='assignment'.\nI define Assignment.project as relation and Programmer.projects as association_proxy('assignments', 'project') (probably you'd also like to define a creator). See Simplifying Association Object Relationships chapter for more information.\n\n"
] |
[
3
] |
[] |
[] |
[
"declarative",
"one_to_many",
"python",
"relation",
"sqlalchemy"
] |
stackoverflow_0002630146_declarative_one_to_many_python_relation_sqlalchemy.txt
|
Q:
Python analog of Unix 'which'
In *nix systems one can use which to find out the full path to a command. For example:
$ which python
/usr/bin/python
or whereis to show all possible locations for a given command
$ whereis python
python: /bin/python.exe /bin/python2.5-config /usr/bin/python.exe /usr/bin/python2.5-config /lib/python2.4 /lib/python2.5 /usr/lib/python2.4 /usr/lib/python2.5 /usr/include/python2.4 /usr/include/python2.5 /usr/share/man/man1/python.1
Is there an easy way to find out the location of a module in the PYTHONPATH. Something like:
>>> which (sys)
'c:\\Python25\Lib\site-packages'
A:
If you do:
modulename.__file__
You will get a full path return of that exact module. For example, importing django:
>>>> import django
>>> django.__file__
'/home/bartek/.virtualenvs/safetyville/lib/python2.6/site-packages/django/__init__.pyc'
Edit: I recommend seeing the comments below for some good insight if you haven't had a chance to.
A:
This is a bit kludgy but you can type python pywhich os django PIL:
import os, os.path
import sys
def pywhich(mod):
for p in sys.path:
try:
if any(p.startswith(mod + '.py') for p in os.listdir(p)):
return os.path.join(p, mod)
except OSError:
pass
return "Not found"
if __name__ == '__main__':
for arg in sys.argv[1:]:
print arg, pywhich(arg)
|
Python analog of Unix 'which'
|
In *nix systems one can use which to find out the full path to a command. For example:
$ which python
/usr/bin/python
or whereis to show all possible locations for a given command
$ whereis python
python: /bin/python.exe /bin/python2.5-config /usr/bin/python.exe /usr/bin/python2.5-config /lib/python2.4 /lib/python2.5 /usr/lib/python2.4 /usr/lib/python2.5 /usr/include/python2.4 /usr/include/python2.5 /usr/share/man/man1/python.1
Is there an easy way to find out the location of a module in the PYTHONPATH. Something like:
>>> which (sys)
'c:\\Python25\Lib\site-packages'
|
[
"If you do:\nmodulename.__file__\nYou will get a full path return of that exact module. For example, importing django:\n>>>> import django\n>>> django.__file__\n'/home/bartek/.virtualenvs/safetyville/lib/python2.6/site-packages/django/__init__.pyc'\n\nEdit: I recommend seeing the comments below for some good insight if you haven't had a chance to.\n",
"This is a bit kludgy but you can type python pywhich os django PIL:\nimport os, os.path\nimport sys\n\ndef pywhich(mod):\n for p in sys.path:\n try:\n if any(p.startswith(mod + '.py') for p in os.listdir(p)):\n return os.path.join(p, mod)\n except OSError:\n pass\n return \"Not found\"\n\nif __name__ == '__main__':\n for arg in sys.argv[1:]:\n print arg, pywhich(arg)\n\n"
] |
[
5,
1
] |
[] |
[] |
[
"bash",
"python"
] |
stackoverflow_0002629472_bash_python.txt
|
Q:
Checkers board structure
I am implementing a checkers game board with python. Here is how I generate the board structure as an [8][8] array:
_matrix = []
for i in xrange(8):
_matrix.append( [' '] * 8 )
for row in xrange(0, 8):
for col in xrange(0, 8):
if _darkQuad(row, col) == True:
_matrix[row][col] = '#'
else:
_matrix[row][col] = '-'
def _darkQuad(row, col):
return ((row%2) == (col%2))
def _printDebugBoard():
for row in xrange(0, 8):
for col in xrange(0, 8):
print _matrix[row][col]
print ''
This should do my board like:
# - # - # - # -
- # - # - # - #
...
But the result is:
- - - - - - - -
# # # # # # # #
- - - - - - - -
# # # # # # # #
- - - - - - - -
# # # # # # # #
- - - - - - - -
# # # # # # # #
What's wrong?
UPD:
Hm, I didn't think this will be important. I made my code easier but here is the exact code I use:
class gameSquare(object):
def __init__(self):
self.validSquare = False
self.symbol = ''
def printSymbol(self):
print self.symbol,
-------
def _validateSquares(self):
for row in xrange(0, 8):
for col in xrange(0, 8):
if self._darkQuad(row, col) == True:
self._matrix[row][col].validSquare = False
self._matrix[row][col].symbol = '#'
else:
self._matrix[row][col].validSquare = True
self._matrix[row][col].symbol = '-'
--------
for i in xrange(8):
self._matrix.append( [gameSquare()] * 8 )
-------
def _printDebugBoard(self):
print ''
for row in xrange(0, 8):
for col in xrange(0, 8):
self._matrix[row][col].printSymbol()
print ''
A:
Update for newly posted code
The problem is with the line:
self._matrix.append( [gameSquare()] * 8 )
This will create 8 references on each line to the same object. When you change one of them, it will actually change the whole row. To fix it:
self._matrix.append( [gameSquare() for _ in xrange(8)] )
End update
Your code works for me. Only thing that needs fixing is:
print _matrix[row][col],
instead of:
print _matrix[row][col]
To avoid printing every character on a different line.
I also had to reorder the functions to get the code to run (put _darkQuad at the top).
A:
I am not able to reproduce this problem. Modifying the code you posted so that it will run:
# Moved this function up here so it can be called.
def _darkQuad(row, col):
return row % 2 == col % 2
def _printDebugBoard():
for row in xrange(8):
for col in xrange(8):
print _matrix[row][col],
# Added the comma here ^ so that I don't get unwanted newlines
print ''
_matrix = []
for i in xrange(8):
_matrix.append([' '] * 8)
for row in xrange(8):
for col in xrange(8):
if _darkQuad(row, col):
_matrix[row][col] = '#'
else:
_matrix[row][col] = '-'
_printDebugBoard() # called the _printDebugBoard function
gives me:
# - # - # - # -
- # - # - # - #
# - # - # - # -
- # - # - # - #
# - # - # - # -
- # - # - # - #
# - # - # - # -
- # - # - # - #
(I also made two changes that didn't affect the result but that reflect better usage. I changed if _darkQuad(row, col) == True: to if _darkQuad(row, col):, which is how you do if statements and I changed xrange(0, 8) to xrange(8), which is the typical usage.)
A:
All you need to do is:
print _matrix[row][col],
The comma tells the interpreter to skip the carriage return after the print statement.
A:
I'd go for something like this:
matrix = ['#-' * 4, '-#' * 4] * 4
It keeps the math to a minimum.
|
Checkers board structure
|
I am implementing a checkers game board with python. Here is how I generate the board structure as an [8][8] array:
_matrix = []
for i in xrange(8):
_matrix.append( [' '] * 8 )
for row in xrange(0, 8):
for col in xrange(0, 8):
if _darkQuad(row, col) == True:
_matrix[row][col] = '#'
else:
_matrix[row][col] = '-'
def _darkQuad(row, col):
return ((row%2) == (col%2))
def _printDebugBoard():
for row in xrange(0, 8):
for col in xrange(0, 8):
print _matrix[row][col]
print ''
This should do my board like:
# - # - # - # -
- # - # - # - #
...
But the result is:
- - - - - - - -
# # # # # # # #
- - - - - - - -
# # # # # # # #
- - - - - - - -
# # # # # # # #
- - - - - - - -
# # # # # # # #
What's wrong?
UPD:
Hm, I didn't think this will be important. I made my code easier but here is the exact code I use:
class gameSquare(object):
def __init__(self):
self.validSquare = False
self.symbol = ''
def printSymbol(self):
print self.symbol,
-------
def _validateSquares(self):
for row in xrange(0, 8):
for col in xrange(0, 8):
if self._darkQuad(row, col) == True:
self._matrix[row][col].validSquare = False
self._matrix[row][col].symbol = '#'
else:
self._matrix[row][col].validSquare = True
self._matrix[row][col].symbol = '-'
--------
for i in xrange(8):
self._matrix.append( [gameSquare()] * 8 )
-------
def _printDebugBoard(self):
print ''
for row in xrange(0, 8):
for col in xrange(0, 8):
self._matrix[row][col].printSymbol()
print ''
|
[
"Update for newly posted code\nThe problem is with the line:\nself._matrix.append( [gameSquare()] * 8 )\n\nThis will create 8 references on each line to the same object. When you change one of them, it will actually change the whole row. To fix it:\nself._matrix.append( [gameSquare() for _ in xrange(8)] )\n\nEnd update\n\nYour code works for me. Only thing that needs fixing is:\nprint _matrix[row][col],\n\ninstead of:\nprint _matrix[row][col]\n\nTo avoid printing every character on a different line.\nI also had to reorder the functions to get the code to run (put _darkQuad at the top).\n",
"I am not able to reproduce this problem. Modifying the code you posted so that it will run:\n# Moved this function up here so it can be called.\ndef _darkQuad(row, col): \n return row % 2 == col % 2\n\ndef _printDebugBoard():\n for row in xrange(8):\n for col in xrange(8):\n print _matrix[row][col],\n # Added the comma here ^ so that I don't get unwanted newlines\n print ''\n\n_matrix = []\nfor i in xrange(8):\n _matrix.append([' '] * 8)\n\n\nfor row in xrange(8):\n for col in xrange(8):\n if _darkQuad(row, col): \n _matrix[row][col] = '#'\n else:\n _matrix[row][col] = '-'\n\n_printDebugBoard() # called the _printDebugBoard function\n\ngives me:\n# - # - # - # - \n- # - # - # - # \n# - # - # - # - \n- # - # - # - # \n# - # - # - # - \n- # - # - # - # \n# - # - # - # - \n- # - # - # - # \n\n(I also made two changes that didn't affect the result but that reflect better usage. I changed if _darkQuad(row, col) == True: to if _darkQuad(row, col):, which is how you do if statements and I changed xrange(0, 8) to xrange(8), which is the typical usage.)\n",
"All you need to do is:\nprint _matrix[row][col],\n\nThe comma tells the interpreter to skip the carriage return after the print statement.\n",
"I'd go for something like this:\nmatrix = ['#-' * 4, '-#' * 4] * 4\n\nIt keeps the math to a minimum.\n"
] |
[
6,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002631165_python.txt
|
Q:
Converting BMP to Grey Scale in Image Module Python
I was wondering how I can convert BMPs to a grey scale using Image Module of Python?
Thanks
A:
Greyscale image mode is 'L'.
>>> import Image
>>> Image.open('input.bmp').convert('L').save('output.bmp')
|
Converting BMP to Grey Scale in Image Module Python
|
I was wondering how I can convert BMPs to a grey scale using Image Module of Python?
Thanks
|
[
"Greyscale image mode is 'L'.\n>>> import Image\n>>> Image.open('input.bmp').convert('L').save('output.bmp')\n\n"
] |
[
4
] |
[] |
[] |
[
"image",
"python"
] |
stackoverflow_0002631311_image_python.txt
|
Q:
Best Way to Run Functional Tests of a WSGI Application?
I'm writing a pair of simple WSGI applications to get a feel for the standard, and I'm to the point where I'd like to test that my applications are working as expected. Now I'm trying to figure out the best way start and stop a server hosting those applications.
My first thought was to start up the SimpleServer from wsgiref in the setUp method and shut it down in the tearDown method. Since serve_forever blocks, I did that work in a separate Thread. Unfortunately, if I use serve_forever to start the server, the secondary thread it's in never dies, and it turns out threading doesn't expose a way to kill a Thread.
Now I'm considering using something like this as my run implementation in the server's Thread:
while keep_going:
httpd.handle_request()
where keep_going is a variable that I set to True in my setUp and set to False in my tearDown.
Is there a better way? I was hoping to write these apps and tests using just the standard library—the better to understand what I'm abstracting away when I use a lib/framework—but this seems like an awful lot of trouble.
Thanks.
A:
The best way to test WSGI applications is WebTest, which eliminates the need to spawn test servers for your app. Instead, it allows you to do make HTTP requests to your WSGI app as method calls on a TestApp object:
>>> from webtest import TestApp
>>> from myapp import my_wsgi_app
>>> app = TestApp(my_wsgi_app)
>>> res = app.get('/')
>>> res.status
'200 OK'
>>> res.status_int
200
>>> params = {'email': 'foo@example.com', 'password': 'foo', }
>>> res = app.post('/login/', params)
>>> res.status_int
302
I usually have a base test class that will add a self.app attribute to my test cases that points to a TestApp instance for the WSGI app I'm testing. So my test methods end up looking something like:
def test_index_page(self):
res = self.app.get('/')
self.failUnlessEqual(res.status_int, 200)
A:
I don't think SimpleServer was ever intended to run in a thread. You might be better off starting SimpleServer in a separate process, e.g. using the subprocess module in the stdlib. Then, you can spawn/kill the process in your setUp and tearDown methods.
|
Best Way to Run Functional Tests of a WSGI Application?
|
I'm writing a pair of simple WSGI applications to get a feel for the standard, and I'm to the point where I'd like to test that my applications are working as expected. Now I'm trying to figure out the best way start and stop a server hosting those applications.
My first thought was to start up the SimpleServer from wsgiref in the setUp method and shut it down in the tearDown method. Since serve_forever blocks, I did that work in a separate Thread. Unfortunately, if I use serve_forever to start the server, the secondary thread it's in never dies, and it turns out threading doesn't expose a way to kill a Thread.
Now I'm considering using something like this as my run implementation in the server's Thread:
while keep_going:
httpd.handle_request()
where keep_going is a variable that I set to True in my setUp and set to False in my tearDown.
Is there a better way? I was hoping to write these apps and tests using just the standard library—the better to understand what I'm abstracting away when I use a lib/framework—but this seems like an awful lot of trouble.
Thanks.
|
[
"The best way to test WSGI applications is WebTest, which eliminates the need to spawn test servers for your app. Instead, it allows you to do make HTTP requests to your WSGI app as method calls on a TestApp object:\n>>> from webtest import TestApp\n>>> from myapp import my_wsgi_app\n>>> app = TestApp(my_wsgi_app)\n>>> res = app.get('/')\n>>> res.status\n'200 OK'\n>>> res.status_int\n200\n>>> params = {'email': 'foo@example.com', 'password': 'foo', }\n>>> res = app.post('/login/', params)\n>>> res.status_int\n302\n\nI usually have a base test class that will add a self.app attribute to my test cases that points to a TestApp instance for the WSGI app I'm testing. So my test methods end up looking something like:\ndef test_index_page(self):\n res = self.app.get('/')\n self.failUnlessEqual(res.status_int, 200)\n\n",
"I don't think SimpleServer was ever intended to run in a thread. You might be better off starting SimpleServer in a separate process, e.g. using the subprocess module in the stdlib. Then, you can spawn/kill the process in your setUp and tearDown methods. \n"
] |
[
4,
1
] |
[] |
[] |
[
"functional_testing",
"python",
"testing",
"wsgi"
] |
stackoverflow_0002630843_functional_testing_python_testing_wsgi.txt
|
Q:
Which software for intranet CMS - Django or Joomla?
In my company we are thinking of moving from wiki style
intranet to a more bespoke CMS solution. Natural choice
would be Joomla, but we have a specific architecture. There
is a few hundred people who will use the system. System
should be self explainable (easier than wiki).
We use a lot of tools web, applications and integrated
within 3rd party software. The superior element which is a
glue for all of them is API. In example for the intranet
tools we do use Django, but it's used without ORM, kind of
limited to templates and url - every application has an
adequate methods within our API. We do not use the Django
admin interface, because it is hardly dependent on ORM.
Because of that Joomla may be hard to integrate. Every
employee should be able to edit most of the pages,
authentication and privileges have to be managed by our API.
How hard is it to plug Joomla to use a different
authentication process? (extension only - no hacks)
If one knows Django better than Joomla, should Django be
used?
A:
Django isn't a CMS. If you want to build an application then you'd use Django (by the sound of your post you understand that though). If you just want to be able to edit/store content and have permissions for your users - a CMS would be the way to go. I really don't know anything about Joomla though. It should be easy enough to mock up a hack to do whatever authentication you need - even if that's just a POST directly to the server.
Django will take a long time to get up to the point where you're using it for the purposes you mention. The admin interface will need to be used (or you're building a CMS from scratch) - which means creating models to model the content you already own. Then you have to customise each model page, and 'plug in' whatever authentication system you want.
Lot of work.
A:
Perhaps you can check Django CMS.
A:
Plone option cancelled on today's
meeting.
In my view Plone is very powerful for building an intranet.
Some references:
Plone
Building an Intranet: Drupal vs. Plone
Intranet 2.0
A:
Joomla! has authentication plugins; you can write your own without hacking the core. When someone attempts to log into your site, it will go through all published authentication plugins (in the order you set) until one returns true. If you only want to use one method, unpublish all of the other plugins except for your custom one.
Also, Joomla! already has a plugin for LDAP if your system supports this.
The part that may be more difficult would be managing specific privileges through the API. Joomla! currently lacks group level access control; it currently has permission level access control (Editors, Publishers, Administrators, etc...).
A:
As you tagged your question with Python, you can have a look at plone (http://plone.org)
A:
If you use FLEXIcontent and FLEXiaccess you can get granular level permissions on Joomla
A:
Django CMS way of work requires using a built-in ORM model and an admin interface.
A:
Thank you for all the answers.
Plone option cancelled on today's meeting.
Using Joomla will involve quite a lot of coding to make it act as the rest of the intranet. I think that writing a CMS in Django (with "stealing" some code from existing cms solutions) will win. Newforms are very interesting and it shouldn't be that hard (I wrote already a CMS system in PHP build on my own framework - used on about 15 sites)
A:
Thanks for that.
The system has been chosen behind my back by higher management.
It's SilverStripe.
Slow Admin interface
No experienced programmer in the company knowing this product
Implemented by a graphic designer who's leaving in about two weeks, but "he can do consulting as he's going to be a freelancer"
I'm not happy at all
Thanks again.
|
Which software for intranet CMS - Django or Joomla?
|
In my company we are thinking of moving from wiki style
intranet to a more bespoke CMS solution. Natural choice
would be Joomla, but we have a specific architecture. There
is a few hundred people who will use the system. System
should be self explainable (easier than wiki).
We use a lot of tools web, applications and integrated
within 3rd party software. The superior element which is a
glue for all of them is API. In example for the intranet
tools we do use Django, but it's used without ORM, kind of
limited to templates and url - every application has an
adequate methods within our API. We do not use the Django
admin interface, because it is hardly dependent on ORM.
Because of that Joomla may be hard to integrate. Every
employee should be able to edit most of the pages,
authentication and privileges have to be managed by our API.
How hard is it to plug Joomla to use a different
authentication process? (extension only - no hacks)
If one knows Django better than Joomla, should Django be
used?
|
[
"Django isn't a CMS. If you want to build an application then you'd use Django (by the sound of your post you understand that though). If you just want to be able to edit/store content and have permissions for your users - a CMS would be the way to go. I really don't know anything about Joomla though. It should be easy enough to mock up a hack to do whatever authentication you need - even if that's just a POST directly to the server.\nDjango will take a long time to get up to the point where you're using it for the purposes you mention. The admin interface will need to be used (or you're building a CMS from scratch) - which means creating models to model the content you already own. Then you have to customise each model page, and 'plug in' whatever authentication system you want.\nLot of work.\n",
"Perhaps you can check Django CMS.\n",
"\nPlone option cancelled on today's\n meeting.\n\nIn my view Plone is very powerful for building an intranet.\nSome references:\n\nPlone\nBuilding an Intranet: Drupal vs. Plone\nIntranet 2.0\n\n",
"Joomla! has authentication plugins; you can write your own without hacking the core. When someone attempts to log into your site, it will go through all published authentication plugins (in the order you set) until one returns true. If you only want to use one method, unpublish all of the other plugins except for your custom one.\nAlso, Joomla! already has a plugin for LDAP if your system supports this.\nThe part that may be more difficult would be managing specific privileges through the API. Joomla! currently lacks group level access control; it currently has permission level access control (Editors, Publishers, Administrators, etc...).\n",
"As you tagged your question with Python, you can have a look at plone (http://plone.org)\n",
"If you use FLEXIcontent and FLEXiaccess you can get granular level permissions on Joomla \n",
"Django CMS way of work requires using a built-in ORM model and an admin interface.\n",
"Thank you for all the answers.\nPlone option cancelled on today's meeting.\nUsing Joomla will involve quite a lot of coding to make it act as the rest of the intranet. I think that writing a CMS in Django (with \"stealing\" some code from existing cms solutions) will win. Newforms are very interesting and it shouldn't be that hard (I wrote already a CMS system in PHP build on my own framework - used on about 15 sites)\n",
"Thanks for that.\nThe system has been chosen behind my back by higher management.\nIt's SilverStripe. \n\nSlow Admin interface\nNo experienced programmer in the company knowing this product\nImplemented by a graphic designer who's leaving in about two weeks, but \"he can do consulting as he's going to be a freelancer\"\n\nI'm not happy at all\nThanks again.\n"
] |
[
8,
7,
3,
2,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"content_management_system",
"django",
"joomla",
"python"
] |
stackoverflow_0000423916_content_management_system_django_joomla_python.txt
|
Q:
Is there a programmatic way to transform a sequence of image files into a PDF?
I have a sequence of JPG images. Each of the scans is already cropped to the exact size of one page. They are sequential pages of a valuable and out of print book. The publishing application requires that these pages be submitted as a single PDF file.
I could take each of these images and just past them into a word-processor (e.g. OpenOffice) - unfortunately the problem here is that it's a very big book and I've got quite a few of these books to get through. It would obviously be time-consuming. This is volunteer work!
My second idea was to use LaTeX (actually pdflatex) - I could make a very simple document that consists of nothing more than a series of in-line image includes. I'm sure that this approach could be made to work, it's just a little on the complex side for something which seems like a very simple job.
It occurred to me that there must be a simpler way - so any suggestions?
I'm on Ubuntu 9.10, my primary programming language is Python, but if the solution is super-simple I'd happily adopt any technology that works.
UPDATE, can somebody explain what's going wrong here?
sal@bobnit:/media/NIKON D200/DCIM/100HPAIO/bat$ convert '*.jpg' bat.pdf
convert: unable to open image `*.jpg': No such file or directory @ blob.c/OpenBlob/2439.
convert: missing an image filename `bat.pdf' @ convert.c/ConvertImageCommand/2775.
Is there a way in the convert command syntax to specify that bat.pdf is the output?
Thanks
A:
It occurred to me that there must be a simpler way - so any suggestions?
You're right, there is! Try this:
sudo apt-get install imagemagick
cd ~/rare-book-images
convert "*.jpg" rare-book.pdf
Note: depending on what shell you're using "*.jpg" might not work as expected. Try omitting the quotes and seeing if that gets you the results you expect.
A:
If you're interested in a Python solution, you can use the ReportLab library. For example:
from reportlab.platypus import SimpleDocTemplate, Image
from reportlab.lib.pagesizes import letter
from glob import glob
doc = SimpleDocTemplate('image-collection.pdf', pagesize=letter)
parts = [Image(filename) for filename in glob('*.jpg')]
doc.build(parts)
This will take all the jpg files in your current directory and produce a file called "image-collection.pdf".
A:
I wonder if you could just do it with a for loop with a \includegraphics command inside and some suitably nifty standard image file naming and so on inside a LaTeX file. This might have the advantage of allowing title pages etc and page numbering and so on. (I'm not sure either of the other solutions do this and I can't be bothered to check. I'm just pondering out loud here, really)
|
Is there a programmatic way to transform a sequence of image files into a PDF?
|
I have a sequence of JPG images. Each of the scans is already cropped to the exact size of one page. They are sequential pages of a valuable and out of print book. The publishing application requires that these pages be submitted as a single PDF file.
I could take each of these images and just past them into a word-processor (e.g. OpenOffice) - unfortunately the problem here is that it's a very big book and I've got quite a few of these books to get through. It would obviously be time-consuming. This is volunteer work!
My second idea was to use LaTeX (actually pdflatex) - I could make a very simple document that consists of nothing more than a series of in-line image includes. I'm sure that this approach could be made to work, it's just a little on the complex side for something which seems like a very simple job.
It occurred to me that there must be a simpler way - so any suggestions?
I'm on Ubuntu 9.10, my primary programming language is Python, but if the solution is super-simple I'd happily adopt any technology that works.
UPDATE, can somebody explain what's going wrong here?
sal@bobnit:/media/NIKON D200/DCIM/100HPAIO/bat$ convert '*.jpg' bat.pdf
convert: unable to open image `*.jpg': No such file or directory @ blob.c/OpenBlob/2439.
convert: missing an image filename `bat.pdf' @ convert.c/ConvertImageCommand/2775.
Is there a way in the convert command syntax to specify that bat.pdf is the output?
Thanks
|
[
"\nIt occurred to me that there must be a simpler way - so any suggestions? \n\nYou're right, there is! Try this:\nsudo apt-get install imagemagick\ncd ~/rare-book-images\nconvert \"*.jpg\" rare-book.pdf\n\nNote: depending on what shell you're using \"*.jpg\" might not work as expected. Try omitting the quotes and seeing if that gets you the results you expect.\n",
"If you're interested in a Python solution, you can use the ReportLab library. For example:\nfrom reportlab.platypus import SimpleDocTemplate, Image\nfrom reportlab.lib.pagesizes import letter\nfrom glob import glob\n\ndoc = SimpleDocTemplate('image-collection.pdf', pagesize=letter)\nparts = [Image(filename) for filename in glob('*.jpg')]\ndoc.build(parts)\n\nThis will take all the jpg files in your current directory and produce a file called \"image-collection.pdf\".\n",
"I wonder if you could just do it with a for loop with a \\includegraphics command inside and some suitably nifty standard image file naming and so on inside a LaTeX file. This might have the advantage of allowing title pages etc and page numbering and so on. (I'm not sure either of the other solutions do this and I can't be bothered to check. I'm just pondering out loud here, really)\n"
] |
[
12,
6,
0
] |
[] |
[] |
[
"documentation",
"latex",
"pdf_generation",
"python",
"tex"
] |
stackoverflow_0002619071_documentation_latex_pdf_generation_python_tex.txt
|
Q:
Converting IPv4 or IPv6 address to a long for comparisons
In order to check if an IPv4 or IPv6 address is within a certain range, I've got code that takes an IPv4 address, turns that into a long, then does that same conversion on the upper/lower bound of the subnet, then checks to see if the long is between those values.
I'd like to be able to do the same thing for IPv6, but saw nothing in the Python 2.6 standard libraries to allow me to do this, so I wrote this up:
import socket, struct
from array import array
def ip_address_to_long(address):
ip_as_long = None
try:
ip_as_long = socket.ntohl(struct.unpack('L',
socket.inet_pton(socket.AF_INET, address))[0])
except socket.error:
# try IPv6
try:
addr = array('L', struct.unpack('!4L',
socket.inet_pton(socket.AF_INET6, address)))
addr.reverse()
ip_as_long = sum(addr[i] << (i * 32) for i in range(len(addr)))
except socket.error as se:
raise ValueError('Invalid address')
except Exception as e:
print str(e)
return ip_as_long
My question is: Is there a simpler way to do this that I am missing? Is there a standard library call that can do this for me?
A:
IPy allows you to do all sorts of transforms on both IPv4 and IPv6 addresses.
|
Converting IPv4 or IPv6 address to a long for comparisons
|
In order to check if an IPv4 or IPv6 address is within a certain range, I've got code that takes an IPv4 address, turns that into a long, then does that same conversion on the upper/lower bound of the subnet, then checks to see if the long is between those values.
I'd like to be able to do the same thing for IPv6, but saw nothing in the Python 2.6 standard libraries to allow me to do this, so I wrote this up:
import socket, struct
from array import array
def ip_address_to_long(address):
ip_as_long = None
try:
ip_as_long = socket.ntohl(struct.unpack('L',
socket.inet_pton(socket.AF_INET, address))[0])
except socket.error:
# try IPv6
try:
addr = array('L', struct.unpack('!4L',
socket.inet_pton(socket.AF_INET6, address)))
addr.reverse()
ip_as_long = sum(addr[i] << (i * 32) for i in range(len(addr)))
except socket.error as se:
raise ValueError('Invalid address')
except Exception as e:
print str(e)
return ip_as_long
My question is: Is there a simpler way to do this that I am missing? Is there a standard library call that can do this for me?
|
[
"IPy allows you to do all sorts of transforms on both IPv4 and IPv6 addresses.\n"
] |
[
2
] |
[] |
[] |
[
"ipv6",
"python"
] |
stackoverflow_0002631588_ipv6_python.txt
|
Q:
using a "temporary files" folder in python
I recently wrote a script which queries PyPI and downloads a package; however, the package gets downloaded to a user defined folder.
I`d like to modify the script in such a way that my downloaded files go into a temporary folder, if the folder is not specified.
The temporary-files folder in *nix machines is "/tmp" ; would there be any Python method I could use to find out the temporary-files folder in a particular machine?
If not, could someone suggest an alternative to this problem?
A:
Python has a built-in module for using temporary files and folders. You probably want tempfile.mkdtemp().
A:
Perhaps the tempfile module?
|
using a "temporary files" folder in python
|
I recently wrote a script which queries PyPI and downloads a package; however, the package gets downloaded to a user defined folder.
I`d like to modify the script in such a way that my downloaded files go into a temporary folder, if the folder is not specified.
The temporary-files folder in *nix machines is "/tmp" ; would there be any Python method I could use to find out the temporary-files folder in a particular machine?
If not, could someone suggest an alternative to this problem?
|
[
"Python has a built-in module for using temporary files and folders. You probably want tempfile.mkdtemp().\n",
"Perhaps the tempfile module?\n"
] |
[
8,
0
] |
[] |
[] |
[
"operating_system",
"python",
"temporary_directory",
"temporary_files"
] |
stackoverflow_0002631923_operating_system_python_temporary_directory_temporary_files.txt
|
Q:
difference in logging mechanism: API and application(python)
I am currently writing an API and an application which uses the API. I have gotten suggestions from people stating that I should perform logging using handlers in the application and use a "logger" object for logging from the API.
In light of the advice I received above, is the following implementation correct?
class test:
def __init__(self, verbose):
self.logger = logging.getLogger("test")
self.logger.setLevel(verbose)
def do_something(self):
# do something
self.logger.log("something")
# by doing this i get the error message "No handlers could be found for logger "test"
The implementation i had in mind was as follows:
#!/usr/bin/python
"""
....
....
create a logger with a handler
....
....
"""
myobject = test()
try:
myobject.do_something()
except SomeError:
logger.log("cant do something")
I'd like to get my basics strong, I'd be grateful for any help and suggestions for code you might recommend I look up.
Thanks!
A:
It's not very clear whether your question is about the specifics of how to use logging or about logging exceptions, but if the latter, I would agree with Adam Crossland that log-and-swallow is a pattern to be avoided.
In terms of the mechanics of logging, I would make the following observations:
You don't need to have a logger as an instance member. It's more natural to declare loggers at module level using logger = logging.getLogger(__name__), and this will also work as expected in sub-packages.
Your call logger.log("message") would likely fail anyway because the log method has a level as the first argument, rather than a message.
You should declare handlers, and if your usage scenario is fairly simple you can do this in your main method or if __name__ == '__main__': clause by adding for example
logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG,
format='%(asctime)s %(levelname)s %(name)s %(message)s')
and then elsewhere in your code, just do for example
import logging
logger = logging.getLogger(__name__)
once at the top of each module where you want to use logging, and then
logger.debug('message with %s', 'arguments') # or .info, .warning, .error etc.
in your code wherever needed.
A:
The danger with the pattern that you are thinking about is that you may end up effectively hiding exceptions by putting them in a log. Many exceptions really should crash your program because they represent a problem that needs to be fixed. Generally, it is more useful to be able to step into code with a debugger to find out what caused the exception.
If there are cases that an exception represents an expected condition that does not affect the stability of the app or the correctness of its behavior, doing nothing but writing a notation to the log is OK. But be very, very careful about how you use this.
A:
I usually do the following:
import logging
import logging.config
logging.config.fileConfig('log.congig')
# for one line log records
G_LOG = logging.getLogger(__name__)
# for records with stacktraces
ST_LOG = logging.getLogger('stacktrace.' + __name__)
try:
# some code
G_LOG.info('some message %s %s', param1, param2)
except (StandardError,):
message = 'some message'
G_LOG.error(message)
# exc_info appends stacktrace to the log message
ST_LOG.error(message, exc_info=True)
Format of the config file can be seen in the python manual
|
difference in logging mechanism: API and application(python)
|
I am currently writing an API and an application which uses the API. I have gotten suggestions from people stating that I should perform logging using handlers in the application and use a "logger" object for logging from the API.
In light of the advice I received above, is the following implementation correct?
class test:
def __init__(self, verbose):
self.logger = logging.getLogger("test")
self.logger.setLevel(verbose)
def do_something(self):
# do something
self.logger.log("something")
# by doing this i get the error message "No handlers could be found for logger "test"
The implementation i had in mind was as follows:
#!/usr/bin/python
"""
....
....
create a logger with a handler
....
....
"""
myobject = test()
try:
myobject.do_something()
except SomeError:
logger.log("cant do something")
I'd like to get my basics strong, I'd be grateful for any help and suggestions for code you might recommend I look up.
Thanks!
|
[
"It's not very clear whether your question is about the specifics of how to use logging or about logging exceptions, but if the latter, I would agree with Adam Crossland that log-and-swallow is a pattern to be avoided.\nIn terms of the mechanics of logging, I would make the following observations:\n\nYou don't need to have a logger as an instance member. It's more natural to declare loggers at module level using logger = logging.getLogger(__name__), and this will also work as expected in sub-packages.\nYour call logger.log(\"message\") would likely fail anyway because the log method has a level as the first argument, rather than a message.\n\nYou should declare handlers, and if your usage scenario is fairly simple you can do this in your main method or if __name__ == '__main__': clause by adding for example\nlogging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG, \n format='%(asctime)s %(levelname)s %(name)s %(message)s')\n\nand then elsewhere in your code, just do for example\nimport logging\nlogger = logging.getLogger(__name__)\n\nonce at the top of each module where you want to use logging, and then\nlogger.debug('message with %s', 'arguments') # or .info, .warning, .error etc.\n\nin your code wherever needed.\n",
"The danger with the pattern that you are thinking about is that you may end up effectively hiding exceptions by putting them in a log. Many exceptions really should crash your program because they represent a problem that needs to be fixed. Generally, it is more useful to be able to step into code with a debugger to find out what caused the exception.\nIf there are cases that an exception represents an expected condition that does not affect the stability of the app or the correctness of its behavior, doing nothing but writing a notation to the log is OK. But be very, very careful about how you use this.\n",
"I usually do the following:\nimport logging\nimport logging.config\nlogging.config.fileConfig('log.congig')\n\n# for one line log records \nG_LOG = logging.getLogger(__name__)\n# for records with stacktraces\nST_LOG = logging.getLogger('stacktrace.' + __name__)\n\n\ntry:\n # some code\n G_LOG.info('some message %s %s', param1, param2)\nexcept (StandardError,):\n message = 'some message'\n G_LOG.error(message)\n # exc_info appends stacktrace to the log message\n ST_LOG.error(message, exc_info=True)\n\nFormat of the config file can be seen in the python manual\n"
] |
[
15,
4,
1
] |
[] |
[] |
[
"api",
"logging",
"python"
] |
stackoverflow_0002630926_api_logging_python.txt
|
Q:
Python thinks I'm a different IP
I'm trying to set a page that displays the visitor's IP. All the methods I have tried show an IP different from the IP my computer has. I've tried:
Looking up http://www.whatismyip.com/automation/n09230945.asp
Using socket.getaddrinfo(socket.gethostname(), None)[0][4][0]
How can I find the real IP of the visitor?
A:
Using the low level networking interface you are actually getting the address of the server the python interpreter is running on:
"socket.gethostname(): Return a string containing the hostname of the machine where the Python interpreter is currently executing."
Getting the client ip using low-level network interface
"socket.accept() Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection."
# Echo server program
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
More info on the low level network interface
Getting the client IP from HTTP headers (if serving html)
REMOTE_ADDR is the header that contains the clients ip address you should check that first.
You should also check to for the HTTP_X_FORWARDED header in case you're visitor is going through a proxy. Be aware that HTTP_X_FORWARDED is an array that can contain multiple comma separated values depending on the number of proxies.
Also be aware that you may be NATed (Network Address Translation). If your ip is internal (10.x.x.x or 192.168.x.x to name a few) you are definitely behind a NAT router and only your external ip will be exposed to websites.
Here is a small c# snippet that shows determining the client's ip, the logic is easy to convert the python and the server headers are the same:
string clientIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if( !string.IsNullOrEmpty(clientIp) ) {
string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
clientIp = forwardedIps[forwardedIps.Length - 1];
} else {
clientIp = context.Request.ServerVariables["REMOTE_ADDR"];
}
A:
I found a simple solution:
import getenv
print getenv("REMOTE_ADDR")
This will return the IP address of the computer connecting to the server.
|
Python thinks I'm a different IP
|
I'm trying to set a page that displays the visitor's IP. All the methods I have tried show an IP different from the IP my computer has. I've tried:
Looking up http://www.whatismyip.com/automation/n09230945.asp
Using socket.getaddrinfo(socket.gethostname(), None)[0][4][0]
How can I find the real IP of the visitor?
|
[
"Using the low level networking interface you are actually getting the address of the server the python interpreter is running on:\n\"socket.gethostname(): Return a string containing the hostname of the machine where the Python interpreter is currently executing.\"\nGetting the client ip using low-level network interface\n\"socket.accept() Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.\"\n# Echo server program\nimport socket\n\nHOST = '' # Symbolic name meaning all available interfaces\nPORT = 50007 # Arbitrary non-privileged port\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.bind((HOST, PORT))\ns.listen(1)\nconn, addr = s.accept()\nprint 'Connected by', addr\nwhile 1:\n data = conn.recv(1024)\n if not data: break\n conn.send(data)\nconn.close()\n\nMore info on the low level network interface\nGetting the client IP from HTTP headers (if serving html)\nREMOTE_ADDR is the header that contains the clients ip address you should check that first.\nYou should also check to for the HTTP_X_FORWARDED header in case you're visitor is going through a proxy. Be aware that HTTP_X_FORWARDED is an array that can contain multiple comma separated values depending on the number of proxies.\nAlso be aware that you may be NATed (Network Address Translation). If your ip is internal (10.x.x.x or 192.168.x.x to name a few) you are definitely behind a NAT router and only your external ip will be exposed to websites.\nHere is a small c# snippet that shows determining the client's ip, the logic is easy to convert the python and the server headers are the same:\nstring clientIp = context.Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"];\nif( !string.IsNullOrEmpty(clientIp) ) {\n string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );\n clientIp = forwardedIps[forwardedIps.Length - 1];\n} else {\n clientIp = context.Request.ServerVariables[\"REMOTE_ADDR\"];\n}\n\n",
"I found a simple solution:\nimport getenv\nprint getenv(\"REMOTE_ADDR\")\n\nThis will return the IP address of the computer connecting to the server.\n"
] |
[
4,
0
] |
[] |
[] |
[
"ip",
"python"
] |
stackoverflow_0002630371_ip_python.txt
|
Q:
Rewriting Live TCP/IP (Layer 4) (i.e. Socket Layer) Streams
I have a simple problem which I'm sure someone here has done before...
I want to rewrite Layer 4 TCP/IP streams (Not lower layer individual packets or frames.) Ettercap's etterfilter command lets you perform simple live replacements of Layer 4 TCP/IP streams based on fixed strings or regexes. Example ettercap scripting code:
if (ip.proto == TCP && tcp.dst == 80) {
if (search(DATA.data, "gzip")) {
replace("gzip", " ");
msg("whited out gzip\n");
}
}
if (ip.proto == TCP && tcp.dst == 80) {
if (search(DATA.data, "deflate")) {
replace("deflate", " ");
msg("whited out deflate\n");
}
}
http://ettercap.sourceforge.net/forum/viewtopic.php?t=2833
I would like to rewrite streams based on my own filter program instead of just simple string replacements. Anyone have an idea of how to do this? Is there anything other than Ettercap that can do live replacement like this, maybe as a plugin to a VPN software or something?
I would like to have a configuration similar to ettercap's silent bridged sniffing configuration between two Ethernet interfaces. This way I can silently filter traffic coming from either direction with no NATing problems. Note that my filter is an application that acts as a pipe filter, similar to the design of unix command-line filters:
>[eth0] <----------> [my filter] <----------> [eth1]<
My filter will be a userspace Python function.
What I am already aware of, but are not suitable:
Tun/Tap - Works at the lower packet layer, I need to work with the higher layer streams.
Ettercap - I can't find any way to do replacements other than the restricted capabilities in the example above.
Hooking into some VPN software? - I just can't figure out which or exactly how.
libnetfilter_queue - Works with lower layer packets, not TCP/IP streams.
Again, the rewriting should occur at the transport layer (Layer 4) as it does in this example, instead of a lower layer packet-based approach. Exact code will help immensely!
Thanks!
A:
Take a look on Scapy, or another packet crafting tool. There are not much of this type out there.
A:
Ettercap is seemingly an open source project, since it is hosted on SourceForge. Perhaps you should look at how it does it.
A:
At the time I was writing a network traffic analysis tool using libpcap for the capture and libnids for the stream assembly.
I haven't tried reinjecting traffic, but you can use TAP to forward traffic to a user program that will use libnids to assemble the packets, put out streams to a filter code, then take the stream and disassemble them (I'm pretty sure libnids has this capability as well) and reinject them into where you need it to go.
If you want python, pynids seems to do what you need, but I have no experience with it.
A:
It looks like you would be able to write an ettercap plugin that loads filters written in python. Or write your custom filter in C instead.
A:
Why not just access DATA.data directly with whatever filters you want?
I don't think you have to use search() you'll just have to build your own analyzer / state machine.
e.g.
for (int i = 0; i < DATA.len; i++) {
if ( DATA.data[i] == 'c' ) {
DATA.data[i] = q
}
}
Final Thoughts;
(1) I don't know that DATA.len exists but seems likely there's something.
(2) I know I replicated your search / replace but wanted to show how you may be able to do the equiv. 'manually'. You can get fancy w/ stuff later.
(3) If you were to adjust the length of the packet (or even the contents for that matter) you probably need to consider shifting window sizes / CRC checks, etc.
e.g. DATA.data[i] = "cc" would overwrite two characters (possibly not what you want) or would change the side of the packet.
I'd assume there are some library calls to set things right again.
A:
PyPCAP is worth checking out since this all hinges around libpcap underneath to begin with. Cut out the middle man!
A:
Since Ettercap is opensource you can change its source code to do what you want. Running your own C code to rewrite a TCP stream should be relatively easy. The hard work has already been done.
Take a look at the etterfilter man page to get started. Search in the source code for the filter engine (apparently it's a JIT interpreter).
I would also try to mail this question to the etterfilter authors, maybe they like stackoverflow :-)
Note: to use Python instead of C, see http://docs.python.org/release/2.5.2/ext/embedding.html
|
Rewriting Live TCP/IP (Layer 4) (i.e. Socket Layer) Streams
|
I have a simple problem which I'm sure someone here has done before...
I want to rewrite Layer 4 TCP/IP streams (Not lower layer individual packets or frames.) Ettercap's etterfilter command lets you perform simple live replacements of Layer 4 TCP/IP streams based on fixed strings or regexes. Example ettercap scripting code:
if (ip.proto == TCP && tcp.dst == 80) {
if (search(DATA.data, "gzip")) {
replace("gzip", " ");
msg("whited out gzip\n");
}
}
if (ip.proto == TCP && tcp.dst == 80) {
if (search(DATA.data, "deflate")) {
replace("deflate", " ");
msg("whited out deflate\n");
}
}
http://ettercap.sourceforge.net/forum/viewtopic.php?t=2833
I would like to rewrite streams based on my own filter program instead of just simple string replacements. Anyone have an idea of how to do this? Is there anything other than Ettercap that can do live replacement like this, maybe as a plugin to a VPN software or something?
I would like to have a configuration similar to ettercap's silent bridged sniffing configuration between two Ethernet interfaces. This way I can silently filter traffic coming from either direction with no NATing problems. Note that my filter is an application that acts as a pipe filter, similar to the design of unix command-line filters:
>[eth0] <----------> [my filter] <----------> [eth1]<
My filter will be a userspace Python function.
What I am already aware of, but are not suitable:
Tun/Tap - Works at the lower packet layer, I need to work with the higher layer streams.
Ettercap - I can't find any way to do replacements other than the restricted capabilities in the example above.
Hooking into some VPN software? - I just can't figure out which or exactly how.
libnetfilter_queue - Works with lower layer packets, not TCP/IP streams.
Again, the rewriting should occur at the transport layer (Layer 4) as it does in this example, instead of a lower layer packet-based approach. Exact code will help immensely!
Thanks!
|
[
"Take a look on Scapy, or another packet crafting tool. There are not much of this type out there.\n",
"Ettercap is seemingly an open source project, since it is hosted on SourceForge. Perhaps you should look at how it does it.\n",
"At the time I was writing a network traffic analysis tool using libpcap for the capture and libnids for the stream assembly. \nI haven't tried reinjecting traffic, but you can use TAP to forward traffic to a user program that will use libnids to assemble the packets, put out streams to a filter code, then take the stream and disassemble them (I'm pretty sure libnids has this capability as well) and reinject them into where you need it to go.\nIf you want python, pynids seems to do what you need, but I have no experience with it.\n",
"It looks like you would be able to write an ettercap plugin that loads filters written in python. Or write your custom filter in C instead.\n",
"Why not just access DATA.data directly with whatever filters you want?\nI don't think you have to use search() you'll just have to build your own analyzer / state machine.\ne.g.\nfor (int i = 0; i < DATA.len; i++) {\n if ( DATA.data[i] == 'c' ) {\n DATA.data[i] = q\n }\n}\nFinal Thoughts;\n(1) I don't know that DATA.len exists but seems likely there's something.\n(2) I know I replicated your search / replace but wanted to show how you may be able to do the equiv. 'manually'. You can get fancy w/ stuff later.\n(3) If you were to adjust the length of the packet (or even the contents for that matter) you probably need to consider shifting window sizes / CRC checks, etc.\n e.g. DATA.data[i] = \"cc\" would overwrite two characters (possibly not what you want) or would change the side of the packet. \n I'd assume there are some library calls to set things right again.\n",
"PyPCAP is worth checking out since this all hinges around libpcap underneath to begin with. Cut out the middle man!\n",
"Since Ettercap is opensource you can change its source code to do what you want. Running your own C code to rewrite a TCP stream should be relatively easy. The hard work has already been done.\nTake a look at the etterfilter man page to get started. Search in the source code for the filter engine (apparently it's a JIT interpreter).\nI would also try to mail this question to the etterfilter authors, maybe they like stackoverflow :-)\nNote: to use Python instead of C, see http://docs.python.org/release/2.5.2/ext/embedding.html\n"
] |
[
2,
1,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"c",
"network_programming",
"python",
"security",
"sockets"
] |
stackoverflow_0002563978_c_network_programming_python_security_sockets.txt
|
Q:
Reading an image from the clipboard with wxPython
How can I read an image from the clipboard? I'm able to read text from the clipboard using wx.Clipboard, but not images.
Is it possible to read images with wx.Clipboard? If not, is there another way?
I'm using Python 2.5 and Windows Vista 64-bit.
A:
The following works for me (tested on Mac OSX)
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, 'test frame',size=(790, 524))
self.Bind(wx.EVT_LEFT_DOWN, self.OnClick)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.clip = wx.Clipboard()
self.x = wx.BitmapDataObject()
self.bmp = None
def OnClick(self, evt):
self.clip.Open()
self.clip.GetData(self.x)
self.clip.Close()
self.bmp = self.x.GetBitmap()
self.Refresh()
def OnPaint(self, evt):
if self.bmp:
dc = wx.PaintDC(self)
dc.DrawBitmap(self.bmp, 20, 20, True)
if __name__ == '__main__':
app = wx.App()
frame = MyFrame()
frame.Show()
app.MainLoop()
To use this, I run it and when the frame comes up I copy an image using another program and then click in the wx frame, which then causes the copied image to be drawn within it.
A:
Python Imaging Library has an ImageGrab module that can do just that. This works on windows only.
|
Reading an image from the clipboard with wxPython
|
How can I read an image from the clipboard? I'm able to read text from the clipboard using wx.Clipboard, but not images.
Is it possible to read images with wx.Clipboard? If not, is there another way?
I'm using Python 2.5 and Windows Vista 64-bit.
|
[
"The following works for me (tested on Mac OSX)\nimport wx\nclass MyFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, -1, 'test frame',size=(790, 524))\n self.Bind(wx.EVT_LEFT_DOWN, self.OnClick)\n self.Bind(wx.EVT_PAINT, self.OnPaint)\n self.clip = wx.Clipboard()\n self.x = wx.BitmapDataObject()\n self.bmp = None\n\n def OnClick(self, evt):\n self.clip.Open()\n self.clip.GetData(self.x)\n self.clip.Close()\n self.bmp = self.x.GetBitmap()\n self.Refresh()\n\n def OnPaint(self, evt):\n if self.bmp:\n dc = wx.PaintDC(self)\n dc.DrawBitmap(self.bmp, 20, 20, True)\n\nif __name__ == '__main__':\n app = wx.App()\n frame = MyFrame()\n frame.Show()\n app.MainLoop()\n\nTo use this, I run it and when the frame comes up I copy an image using another program and then click in the wx frame, which then causes the copied image to be drawn within it.\n",
"Python Imaging Library has an ImageGrab module that can do just that. This works on windows only.\n"
] |
[
2,
0
] |
[] |
[] |
[
"image",
"memory",
"python",
"wxpython"
] |
stackoverflow_0002629907_image_memory_python_wxpython.txt
|
Q:
What does binding mean exactly?
I always see people mention that "Python binding" and "C Sharp binding" etc. when I am actually using their C++ libraries. What does binding mean? If the library is written in C, and does Python binding means that they use SWIG kind of tool to mock a Python interface?
Newbie in this field, and any suggestion will be welcomed.
A:
When someone talks about something like a "C# binding" of a library, they are indicating that you and API is being provided in C# for a library written in a different language. This may or may not involve an autogeneration tool like SWIG.
A:
In short, yes. A binding is just that, an interface to a library or program written in another language, though it need not be generated using SWIG.
SWIG is just a tool for automatic generation of the same...
A:
You're right, for a general library, a "binding" essentially means "easily callable from". The binding may or may not have been created with SWIG, that's just one way to do it.
A:
If the library is written in C, and
does Python binding means that they
use SWIG kind of tool to mock a Python
interface?
Yes, you are right. That will be called a Python binding of the respective library.
|
What does binding mean exactly?
|
I always see people mention that "Python binding" and "C Sharp binding" etc. when I am actually using their C++ libraries. What does binding mean? If the library is written in C, and does Python binding means that they use SWIG kind of tool to mock a Python interface?
Newbie in this field, and any suggestion will be welcomed.
|
[
"When someone talks about something like a \"C# binding\" of a library, they are indicating that you and API is being provided in C# for a library written in a different language. This may or may not involve an autogeneration tool like SWIG.\n",
"In short, yes. A binding is just that, an interface to a library or program written in another language, though it need not be generated using SWIG.\nSWIG is just a tool for automatic generation of the same...\n",
"You're right, for a general library, a \"binding\" essentially means \"easily callable from\". The binding may or may not have been created with SWIG, that's just one way to do it.\n",
"\nIf the library is written in C, and\n does Python binding means that they\n use SWIG kind of tool to mock a Python\n interface?\n\nYes, you are right. That will be called a Python binding of the respective library.\n"
] |
[
2,
0,
0,
0
] |
[] |
[] |
[
"binding",
"c++",
"python"
] |
stackoverflow_0002632466_binding_c++_python.txt
|
Q:
Can Python directory names be keywords? E.g. 'import'?
Am I allowed to have a directory named 'import' containing Python code? Or will the import command fail to parse it as a result? Is there any way around that?
A:
You can use the built-in __import__ function which accepts any string. Thus you may write:
__import__('keyword.submodule')
A:
You can have a directory with a name that is a Python keyword storing your Python code. This directory should not be used as a package, since package names should be valid Python identifiers.
A:
Or will the import command fail to parse it as a result?
It will indeed fail.
|
Can Python directory names be keywords? E.g. 'import'?
|
Am I allowed to have a directory named 'import' containing Python code? Or will the import command fail to parse it as a result? Is there any way around that?
|
[
"You can use the built-in __import__ function which accepts any string. Thus you may write:\n__import__('keyword.submodule')\n\n",
"You can have a directory with a name that is a Python keyword storing your Python code. This directory should not be used as a package, since package names should be valid Python identifiers.\n",
"\nOr will the import command fail to parse it as a result?\n\nIt will indeed fail.\n"
] |
[
9,
4,
0
] |
[] |
[] |
[
"keyword",
"module",
"python"
] |
stackoverflow_0002632179_keyword_module_python.txt
|
Q:
Is it possible to do a wx.TextCtrl with no border?
I want to do a wx.TextCtrl with no border usign wxpython :P
How can I do it?
A:
How about wx.BORDER_NONE as in:
t1 = wx.TextCtrl(self, -1, "my text", style=wx.BORDER_NONE)
|
Is it possible to do a wx.TextCtrl with no border?
|
I want to do a wx.TextCtrl with no border usign wxpython :P
How can I do it?
|
[
"How about wx.BORDER_NONE as in:\nt1 = wx.TextCtrl(self, -1, \"my text\", style=wx.BORDER_NONE)\n\n"
] |
[
16
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002632479_python_wxpython.txt
|
Q:
Regex pattern problem in python
I need to extract parts of a string using regex in Python.
I'm good with basic regex but I'm terrible at lookarounds. I've shown two sample records below. The last big is always a currency field e.g. in the first one it is 4,76. In the second one it is 2,00. The second has an account number that is the pattern of \d{6}-\d{6}. Anything after that is the currency.
24.02 24.02VALINTATALO MEGAHERTSI4,76-
24.02 24.02DOE MRIDANG 157235-1234582,00-
Could you help me out with this regex? What I've written so far is given below but it considers everything after the 'dash' in the account number to be the currency.
.*?(\d\d\.\d\d)(.*?)\s*(?<!\d{6}-\d{6})(\d*,\d\d)
Thanks in advance
A:
import re
def extract_current(s):
s = s[s.rfind(' ')+1:-1]
s = re.sub('\d{6}-\d{6}', '', s)
s = re.sub('[A-Z]+', '', s)
return s
print extract_current('24.02 24.02VALINTATALO MEGAHERTSI4,76-')
print extract_current('24.02 24.02DOE MRIDANG 157235-1234582,00-')
Output:
4,76
2,00
A:
This seems to work:
.*?(\d\d\.\d\d)(.*?)(?:\d{6}-\d{6})?(\d*,\d\d)
Explanation: (?:\d{6}-\d{6}) sees the account number but doesn't remember it. The question mark after it allows the account number to be absent. The reason we don't want to remember the account number is that it throws off the index that we access with match.group(3). I.e., it could be at index 4 if the account number were present.
A:
(?<=\b\d{6}-\d{6}|[^-\d])\d+?,\d\d
will match a "currency" that's either preceded by an account number or anything else (except for a hyphen). Is that sufficient?
A:
(?<=\d{6}-\d{6}|[A-Z ])[0-9,]+(?=-$)
This regex matches the first string of digits and commas that is preceded by either an account number or a letter or a space and has a dash after it which is the last character of the line/string.
|
Regex pattern problem in python
|
I need to extract parts of a string using regex in Python.
I'm good with basic regex but I'm terrible at lookarounds. I've shown two sample records below. The last big is always a currency field e.g. in the first one it is 4,76. In the second one it is 2,00. The second has an account number that is the pattern of \d{6}-\d{6}. Anything after that is the currency.
24.02 24.02VALINTATALO MEGAHERTSI4,76-
24.02 24.02DOE MRIDANG 157235-1234582,00-
Could you help me out with this regex? What I've written so far is given below but it considers everything after the 'dash' in the account number to be the currency.
.*?(\d\d\.\d\d)(.*?)\s*(?<!\d{6}-\d{6})(\d*,\d\d)
Thanks in advance
|
[
"import re\n\ndef extract_current(s):\n s = s[s.rfind(' ')+1:-1]\n s = re.sub('\\d{6}-\\d{6}', '', s)\n s = re.sub('[A-Z]+', '', s)\n return s\n\nprint extract_current('24.02 24.02VALINTATALO MEGAHERTSI4,76-')\nprint extract_current('24.02 24.02DOE MRIDANG 157235-1234582,00-')\n\nOutput:\n4,76\n2,00\n\n",
"This seems to work:\n.*?(\\d\\d\\.\\d\\d)(.*?)(?:\\d{6}-\\d{6})?(\\d*,\\d\\d)\n\nExplanation: (?:\\d{6}-\\d{6}) sees the account number but doesn't remember it. The question mark after it allows the account number to be absent. The reason we don't want to remember the account number is that it throws off the index that we access with match.group(3). I.e., it could be at index 4 if the account number were present.\n",
"(?<=\\b\\d{6}-\\d{6}|[^-\\d])\\d+?,\\d\\d\n\nwill match a \"currency\" that's either preceded by an account number or anything else (except for a hyphen). Is that sufficient?\n",
"(?<=\\d{6}-\\d{6}|[A-Z ])[0-9,]+(?=-$)\n\nThis regex matches the first string of digits and commas that is preceded by either an account number or a letter or a space and has a dash after it which is the last character of the line/string.\n"
] |
[
1,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002632416_python_regex.txt
|
Q:
Python integer incrementing with ++
I've always laughed to myself when I've looked back at my VB6 days and thought, "What modern language doesn't allow incrementing with double plus signs?":
number++
To my surprise, I can't find anything about this in the Python docs. Must I really subject myself to number = number + 1? Don't people use the ++ / -- notation?
A:
Python doesn't support ++, but you can do:
number += 1
A:
Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.
Fortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().
A:
You can do:
number += 1
A:
Yes. The ++ operator is not available in Python. Guido doesn't like these operators.
A:
The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++ is the next method of iterators.
A:
Take a look at Behaviour of increment and decrement operators in Python for an explanation of why this doesn't work.
Python doesn't really have ++ and --, and I personally never felt it was such a loss.
I prefer functions with clear names to operators with non-always clear semantics (hence the classic interview question about ++x vs. x++ and the difficulties of overloading it). I've also never been a huge fan of what post-incrementation does for readability.
You could always define some wrapper class (like accumulator) with clear increment semantics, and then do something like x.increment() or x.incrementAndReturnPrev()
A:
Here there is an explanation:
http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python
However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.
In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.
|
Python integer incrementing with ++
|
I've always laughed to myself when I've looked back at my VB6 days and thought, "What modern language doesn't allow incrementing with double plus signs?":
number++
To my surprise, I can't find anything about this in the Python docs. Must I really subject myself to number = number + 1? Don't people use the ++ / -- notation?
|
[
"Python doesn't support ++, but you can do:\nnumber += 1\n\n",
"Simply put, the ++ and -- operators don't exist in Python because they wouldn't be operators, they would have to be statements. All namespace modification in Python is a statement, for simplicity and consistency. That's one of the design decisions. And because integers are immutable, the only way to 'change' a variable is by reassigning it.\nFortunately we have wonderful tools for the use-cases of ++ and -- in other languages, like enumerate() and itertools.count().\n",
"You can do:\nnumber += 1\n\n",
"Yes. The ++ operator is not available in Python. Guido doesn't like these operators.\n",
"The main reason ++ comes in handy in C-like languages is for keeping track of indices. In Python, you deal with data in an abstract way and seldom increment through indices and such. The closest-in-spirit thing to ++ is the next method of iterators.\n",
"Take a look at Behaviour of increment and decrement operators in Python for an explanation of why this doesn't work. \nPython doesn't really have ++ and --, and I personally never felt it was such a loss. \nI prefer functions with clear names to operators with non-always clear semantics (hence the classic interview question about ++x vs. x++ and the difficulties of overloading it). I've also never been a huge fan of what post-incrementation does for readability. \nYou could always define some wrapper class (like accumulator) with clear increment semantics, and then do something like x.increment() or x.incrementAndReturnPrev()\n",
"Here there is an explanation:\nhttp://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python\nHowever the absence of this operator is in the python philosophy increases consistency and avoids implicitness.\nIn addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.\n"
] |
[
1677,
518,
61,
35,
25,
12,
9
] |
[] |
[] |
[
"increment",
"python",
"syntax"
] |
stackoverflow_0002632677_increment_python_syntax.txt
|
Q:
Python SQLite FTS3 alternatives?
Are there any good alternatives to SQLite + FTS3 for python?
I'm iterating over a series of text documents, and would like to categorize them according to some text queries. For example, I might want to know if a document mentions the words "rating" or "upgraded" within three words of "buy." The FTS3 syntax for this query is the following:
(rating OR upgraded) NEAR/3 buy
That's all well and good, but if I use FTS3, this operation seems rather expensive. The process goes something like this:
# create an SQLite3 db in memory
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE VIRTUAL TABLE fts USING FTS3(content TEXT)')
conn.commit()
Then, for each document, do something like this:
#insert the document text into the fts table, so I can run a query
c.execute('insert into fts(content) values (?)', content)
conn.commit()
# execute my FTS query here, look at the results, etc
# remove the document text from the fts table before working on the next document
c.execute('delete from fts')
conn.commit()
This seems rather expensive to me.
The other problem I have with SQLite FTS is that it doesn't appear to work with Python 2.5.4. The 'CREATE VIRTUAL TABLE' syntax is unrecognized. This means that I'd have to upgrade to Python 2.6, which means re-testing numerous existing scripts and programs to make sure they work under 2.6.
Is there a better way? Perhaps a different library? Something faster? Thank you.
A:
I suggest you install pysqlite2 module separately. You should make sure that you have sqlite3 installed in your system which should have the FTS3 module ;-)
Checkout http://code.google.com/p/pysqlite/downloads/list for the latest code (as of April 13, it's version 2.6.0). It's the usual setuptools build. It should also complain if you don't have sqlite3 installed -- or its libraries aren't installed in the usual location /usr/lib(64). In the latter case, update your LD_LIBRARY_PATH and perhaps tweak setup.cfg to specify the header/lib paths.
Goodluck,
Paul
|
Python SQLite FTS3 alternatives?
|
Are there any good alternatives to SQLite + FTS3 for python?
I'm iterating over a series of text documents, and would like to categorize them according to some text queries. For example, I might want to know if a document mentions the words "rating" or "upgraded" within three words of "buy." The FTS3 syntax for this query is the following:
(rating OR upgraded) NEAR/3 buy
That's all well and good, but if I use FTS3, this operation seems rather expensive. The process goes something like this:
# create an SQLite3 db in memory
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE VIRTUAL TABLE fts USING FTS3(content TEXT)')
conn.commit()
Then, for each document, do something like this:
#insert the document text into the fts table, so I can run a query
c.execute('insert into fts(content) values (?)', content)
conn.commit()
# execute my FTS query here, look at the results, etc
# remove the document text from the fts table before working on the next document
c.execute('delete from fts')
conn.commit()
This seems rather expensive to me.
The other problem I have with SQLite FTS is that it doesn't appear to work with Python 2.5.4. The 'CREATE VIRTUAL TABLE' syntax is unrecognized. This means that I'd have to upgrade to Python 2.6, which means re-testing numerous existing scripts and programs to make sure they work under 2.6.
Is there a better way? Perhaps a different library? Something faster? Thank you.
|
[
"I suggest you install pysqlite2 module separately. You should make sure that you have sqlite3 installed in your system which should have the FTS3 module ;-)\nCheckout http://code.google.com/p/pysqlite/downloads/list for the latest code (as of April 13, it's version 2.6.0). It's the usual setuptools build. It should also complain if you don't have sqlite3 installed -- or its libraries aren't installed in the usual location /usr/lib(64). In the latter case, update your LD_LIBRARY_PATH and perhaps tweak setup.cfg to specify the header/lib paths.\nGoodluck,\nPaul\n"
] |
[
2
] |
[] |
[] |
[
"full_text_search",
"python",
"search",
"text"
] |
stackoverflow_0001874957_full_text_search_python_search_text.txt
|
Q:
How to check wether a path represented by a QString with german umlauts exists?
i get a QString which represents a directory from a QLineEdit. Now i want to check wether a certain file exists in this directory. But if i try this with os.path.exists and os.path.join and get in trouble when german umlauts occur in the directory path:
#the direcory coming from the user input in the QLineEdit
#i take this QString to the local 8-Bit encoding and then make
#a string from it
target_dir = str(lineEdit.text().toLocal8Bit())
#the file name that should be checked for
file_name = 'some-name.txt'
#this fails with a UnicodeDecodeError when a umlaut occurs in target_dir
os.path.exists(os.path.join(target_dir, file_name))
How would you check if the file exists, when you might encounter german umlauts?
A:
I was getting no where with this on my Ubuntu box with an ext3 filesystem. So, I guess make sure the filesystem supports unicode filenames first, or else I believe the behavior is undefined?
>>> os.path.supports_unicode_filenames
True
If that's True, you should be able to pass unicode strings to the os.path calls directly:
>>> print u'\xf6'
ö
>>> target_dir = os.path.join(os.getcwd(), u'\xf6')
>>> print target_dir
C:\Python26\ö
>>> os.path.exists(os.path.join(target_dir, 'test.txt'))
True
You should look at QString.toUtf8 and maybe pass the returned value through os.path.normpath before handing it over to os.path.join
Good Luck!
nm, it works fine on my ubuntu box as well...
>>> os.path.supports_unicode_filenames
False
>>> target_dir = os.path.join(os.getcwd(), u'\xf6')
>>> print target_dir
/home/clayg/ö
>>> os.path.exists(os.path.join(target_dir, 'test'))
True
|
How to check wether a path represented by a QString with german umlauts exists?
|
i get a QString which represents a directory from a QLineEdit. Now i want to check wether a certain file exists in this directory. But if i try this with os.path.exists and os.path.join and get in trouble when german umlauts occur in the directory path:
#the direcory coming from the user input in the QLineEdit
#i take this QString to the local 8-Bit encoding and then make
#a string from it
target_dir = str(lineEdit.text().toLocal8Bit())
#the file name that should be checked for
file_name = 'some-name.txt'
#this fails with a UnicodeDecodeError when a umlaut occurs in target_dir
os.path.exists(os.path.join(target_dir, file_name))
How would you check if the file exists, when you might encounter german umlauts?
|
[
"I was getting no where with this on my Ubuntu box with an ext3 filesystem. So, I guess make sure the filesystem supports unicode filenames first, or else I believe the behavior is undefined?\n>>> os.path.supports_unicode_filenames\nTrue\n\nIf that's True, you should be able to pass unicode strings to the os.path calls directly:\n>>> print u'\\xf6'\nö\n>>> target_dir = os.path.join(os.getcwd(), u'\\xf6')\n>>> print target_dir\nC:\\Python26\\ö\n>>> os.path.exists(os.path.join(target_dir, 'test.txt'))\nTrue\n\nYou should look at QString.toUtf8 and maybe pass the returned value through os.path.normpath before handing it over to os.path.join\nGood Luck!\nnm, it works fine on my ubuntu box as well...\n>>> os.path.supports_unicode_filenames\nFalse\n>>> target_dir = os.path.join(os.getcwd(), u'\\xf6')\n>>> print target_dir\n/home/clayg/ö\n>>> os.path.exists(os.path.join(target_dir, 'test'))\nTrue\n\n"
] |
[
1
] |
[] |
[] |
[
"diacritics",
"pyqt4",
"python",
"qstring"
] |
stackoverflow_0002631405_diacritics_pyqt4_python_qstring.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.