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:
MongoDB: Limiting results from a $gt query (from pymongo)
I'm gathering some statistics from a web service, and storing it in a collection. The data looks similar to this (but with more fields):
{"downloads": 30, "dt": "2010-02-17T16:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T17:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T18:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T19:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T20:56:34.163000"}
{…}
{"downloads": 30, "dt": "2010-02-18T17:56:34.163000"}
{"downloads": 30, "dt": "2010-02-18T18:56:34.163000"}
{"downloads": 30, "dt": "2010-02-18T19:56:34.163000"}
{"downloads": 30, "dt": "2010-02-18T20:56:34.163000"}
If someone requests the daily numbers for the last thirty days, that would mean the max amount of (in this example) 'downloads' pr. day. Which is the last record of the day.
By using collection.find({"dt": {"$gt": datetime_obj_30_days_ago}}), I of course get all the rows, which is not very suitable. So I'm looking for a way to only return the last of the day for the given period.
I was told that group() might be the way to go, but I can't quite understand how to get it working in this instance.
Any tips, pointers would be very appreciated!
A:
You can do this using group. In your example you'd need to supply a javascript function to compute the key (as well the reduce function), because you want only the date component of the datetime field. This should work:
db.coll.group(
key='function(doc) { return {"dt": doc.dt.toDateString()} }',
condition={'dt': {'$gt': datetime_obj_30_days_ago}},
initial={'downloads': 0},
reduce='function(curr, prev) { prev.downloads = Math.max(curr.downloads, prev.downloads) }'
)
Keep in mind that still does a linear scan of the past month, just on the server instead of the client. It's possible that simply selecting the max value of each day individually is faster.
|
MongoDB: Limiting results from a $gt query (from pymongo)
|
I'm gathering some statistics from a web service, and storing it in a collection. The data looks similar to this (but with more fields):
{"downloads": 30, "dt": "2010-02-17T16:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T17:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T18:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T19:56:34.163000"}
{"downloads": 30, "dt": "2010-02-17T20:56:34.163000"}
{…}
{"downloads": 30, "dt": "2010-02-18T17:56:34.163000"}
{"downloads": 30, "dt": "2010-02-18T18:56:34.163000"}
{"downloads": 30, "dt": "2010-02-18T19:56:34.163000"}
{"downloads": 30, "dt": "2010-02-18T20:56:34.163000"}
If someone requests the daily numbers for the last thirty days, that would mean the max amount of (in this example) 'downloads' pr. day. Which is the last record of the day.
By using collection.find({"dt": {"$gt": datetime_obj_30_days_ago}}), I of course get all the rows, which is not very suitable. So I'm looking for a way to only return the last of the day for the given period.
I was told that group() might be the way to go, but I can't quite understand how to get it working in this instance.
Any tips, pointers would be very appreciated!
|
[
"You can do this using group. In your example you'd need to supply a javascript function to compute the key (as well the reduce function), because you want only the date component of the datetime field. This should work:\ndb.coll.group(\n key='function(doc) { return {\"dt\": doc.dt.toDateString()} }',\n condition={'dt': {'$gt': datetime_obj_30_days_ago}},\n initial={'downloads': 0},\n reduce='function(curr, prev) { prev.downloads = Math.max(curr.downloads, prev.downloads) }'\n)\n\nKeep in mind that still does a linear scan of the past month, just on the server instead of the client. It's possible that simply selecting the max value of each day individually is faster.\n"
] |
[
1
] |
[] |
[] |
[
"mongodb",
"pymongo",
"python"
] |
stackoverflow_0002291307_mongodb_pymongo_python.txt
|
Q:
Python Lambda behaviour
I'm trying to get my head around lambda expressions, closures and scoping in Python. Why does the program not crash on the first line here?
>>> foo = lambda x: x + a
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> a = 5
>>> foo(2)
7
>>>
A:
Because that's just not how Python functions work; it's not special to lambdas:
>>> def foo(x):
... return x + a
>>> foo
<function foo at 0xb7dde454>
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
NameError: global name 'a' is not defined
Variables are looked up when used, not when a function is defined. They are even looked up each time the function is called, which you will definitely find unexpected if you're coming from a C background (for example), but this isn't a problem in Python.
A:
Your lambda expression doesn't get evaluated until you call it.
It does get parsed, which is why a syntax error would cause a traceback.
>>> foo = lambda x : x + a
>>> bar = lambda y : print y
SyntaxError: invalid syntax
A:
Variables in Python may be used before they are set. This will generate a runtime error, not a syntax error. Here's an example using local variables:
>>> def f():
... return a
... a = 3
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
This is in contrast to languages which consider dereferencing an unassigned or undefined variable a syntax error. Python doesn't "capture" the current state of lexical scope, it just uses references to mutable lexical scopes. Here's a demonstration:
>>> def f(): return a
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in f
NameError: global name 'a' is not defined
>>> a = 3
>>> f()
3
A:
The bodies of lambdas (and functions defined with def) in Python are not evaluated until they are called. Names are always looked up at runtime.
A:
on the first line you create expression, which is different from evaluating it. When you try to evaluate it, this is then it cannot find symbol a .
|
Python Lambda behaviour
|
I'm trying to get my head around lambda expressions, closures and scoping in Python. Why does the program not crash on the first line here?
>>> foo = lambda x: x + a
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
NameError: global name 'a' is not defined
>>> a = 5
>>> foo(2)
7
>>>
|
[
"Because that's just not how Python functions work; it's not special to lambdas:\n>>> def foo(x):\n... return x + a\n>>> foo\n<function foo at 0xb7dde454>\n>>> foo(2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in foo\nNameError: global name 'a' is not defined\n\nVariables are looked up when used, not when a function is defined. They are even looked up each time the function is called, which you will definitely find unexpected if you're coming from a C background (for example), but this isn't a problem in Python.\n",
"Your lambda expression doesn't get evaluated until you call it.\nIt does get parsed, which is why a syntax error would cause a traceback.\n>>> foo = lambda x : x + a\n>>> bar = lambda y : print y\nSyntaxError: invalid syntax\n\n",
"Variables in Python may be used before they are set. This will generate a runtime error, not a syntax error. Here's an example using local variables:\n>>> def f():\n... return a\n... a = 3\n... \n>>> f()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 2, in f\nUnboundLocalError: local variable 'a' referenced before assignment\n\nThis is in contrast to languages which consider dereferencing an unassigned or undefined variable a syntax error. Python doesn't \"capture\" the current state of lexical scope, it just uses references to mutable lexical scopes. Here's a demonstration:\n>>> def f(): return a\n... \n>>> f()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 1, in f\nNameError: global name 'a' is not defined\n>>> a = 3\n>>> f()\n3\n\n",
"The bodies of lambdas (and functions defined with def) in Python are not evaluated until they are called. Names are always looked up at runtime.\n",
"on the first line you create expression, which is different from evaluating it. When you try to evaluate it, this is then it cannot find symbol a .\n"
] |
[
6,
2,
2,
0,
0
] |
[] |
[] |
[
"lambda",
"python"
] |
stackoverflow_0002294134_lambda_python.txt
|
Q:
Django: Using django.contrib.auth for SAAS ( Users, permissions, etc. )
I'm making a SAAS and I've been asking a slew of questions on here related to the Auth system built in. I'm having trouble understanding the "why" and "how". Primarily I don't understand how it fits in with my SAAS.
I (do) know the following:
You can do this: http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
There are many reasons to use the built in auth system (like security) instead of rolling your own
I (don't) know the following:
class MyUserProfile(models.Model):
"""
Administrator for an Account. Can edit tickets and other stuff.
"""
user = AutoOneToOneField(User, primary_key=True)
account = models.ForeignKey(Account)
dogs_name = models.CharField(max_length=255)
In the previous example, account is just what you'd expect; an entity that's paying to use my software. user is my main concern. Somebody goes to a page and creates a UserProfile with a username and password, etc. When they do this, where does the related User get created? Do I need to create it in my view manually based on the request.POST['username'], etc, and then do
myuserprof = MyUserProfile.create(user=foo_user_just_created, account=foo_account, dogs_name='Spot')
I don't know why but for some reason I feel like I'm missing something. This idea of asking somebody to sign up for an account, and then create a MyUserProfile with a form that asks for the password, username, email, et al, and then in my view creating 2 different objects (MyUserProfile and User) with different parts of the form data. I mean I shouldn't have a User form right? Like I said, I feel like I'm either skipping a step or I'm in the wrong paradigm. I'm not new to Django, but for some reason I have trouble with things that I didn't build (I think it might be a mental problem for real at this point).
Maybe there is a good example of this sort of thing being done on some open source project.
Update: Oops, forgot to mention that in the code above I tried to use AutoOneToOneField from django-annoying, but I have no idea where all the User's attributes get set or how to decide which User object to attach to it. This stuff is driving me crazy.
Also, do I need to use the sites app to do this stuff, and finally does a "super user" have all permissions to everything (I don't want people from Account "Acme" to access account "Microshaft" objects)? Or do they just have all permissions to all views?
A:
Somebody goes to a page and creates a UserProfile with a username and password, etc.
UserProfile doesn't have an username or password field. So it should be somebody goes to a page and create an User. Then, it creates an UserProfile associated to that newly created User.
The question is, how and when do you want this UserProfile instance to be created?
Automatically, whenever a new User is created : use signals, as described in the docs
Automatically, whenever the profile is accessed from an user instance : use AutoOneToOneField, and access the profile using user.userprofile instead of user.get_profile()
Manually. But don't forget an user might have no UserProfile associated yet, so user.get_profile() might raise a DoesNotExist exception.
When they do this, where does the related User get created?
It doesn't. You have to create it explicitely.
This idea of asking somebody to sign up for an account, and then create a MyUserProfile with a form that asks for the password, username, email, et al, and then in my view creating 2 different objects (MyUserProfile and User) with different parts of the form data. I mean I shouldn't have a User form right?
Why not? You want here to create an User and his associated profile in one go, right? You could eventually use directly the POST data, or use a Form to access to the fields, or even better, use 2 ModelForm (one for User, one for UserProfile) that you will process in the same view (maybe this question can help?)
Maybe there is a good example of this sort of thing being done on some open source project.
I suggest you check out django-registration and django-profiles.
Note
You have another way of adding information to an User object, by extending the model itsel. It will allow you to put your extra fields directly in the user model and might be easier for you to understand and use.
I won't dive into details here, have a look at that tutorial for more informations.
Other questions
I tried to use AutoOneToOneField from django-annoying, but I have no idea where all the User's attributes get set or how to decide which User object to attach to it. This stuff is driving me crazy
See above on how to use it. If you feel uncomfortable with it, the best is to follow the documentation, which recommend using a ForeignKey with unique=True in user profiles.
Also, do I need to use the sites app to do this stuff
From the site framework docs : Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way.
and finally does a "super user" have all permissions to everything (I don't want people from Account "Acme" to access account "Microshaft" objects)?
Again, from the docs, Designates that this user has all permissions without explicitly assigning them. That means that everywhere Django is using the built-in permission system (e.g. default administration pages), a super-user will be authorized.
In views you're writing yourself, or if you tweak some ModelAdmin, it's up to you to decide how you are going to check permissions.
|
Django: Using django.contrib.auth for SAAS ( Users, permissions, etc. )
|
I'm making a SAAS and I've been asking a slew of questions on here related to the Auth system built in. I'm having trouble understanding the "why" and "how". Primarily I don't understand how it fits in with my SAAS.
I (do) know the following:
You can do this: http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users
There are many reasons to use the built in auth system (like security) instead of rolling your own
I (don't) know the following:
class MyUserProfile(models.Model):
"""
Administrator for an Account. Can edit tickets and other stuff.
"""
user = AutoOneToOneField(User, primary_key=True)
account = models.ForeignKey(Account)
dogs_name = models.CharField(max_length=255)
In the previous example, account is just what you'd expect; an entity that's paying to use my software. user is my main concern. Somebody goes to a page and creates a UserProfile with a username and password, etc. When they do this, where does the related User get created? Do I need to create it in my view manually based on the request.POST['username'], etc, and then do
myuserprof = MyUserProfile.create(user=foo_user_just_created, account=foo_account, dogs_name='Spot')
I don't know why but for some reason I feel like I'm missing something. This idea of asking somebody to sign up for an account, and then create a MyUserProfile with a form that asks for the password, username, email, et al, and then in my view creating 2 different objects (MyUserProfile and User) with different parts of the form data. I mean I shouldn't have a User form right? Like I said, I feel like I'm either skipping a step or I'm in the wrong paradigm. I'm not new to Django, but for some reason I have trouble with things that I didn't build (I think it might be a mental problem for real at this point).
Maybe there is a good example of this sort of thing being done on some open source project.
Update: Oops, forgot to mention that in the code above I tried to use AutoOneToOneField from django-annoying, but I have no idea where all the User's attributes get set or how to decide which User object to attach to it. This stuff is driving me crazy.
Also, do I need to use the sites app to do this stuff, and finally does a "super user" have all permissions to everything (I don't want people from Account "Acme" to access account "Microshaft" objects)? Or do they just have all permissions to all views?
|
[
"\nSomebody goes to a page and creates a UserProfile with a username and password, etc.\n\nUserProfile doesn't have an username or password field. So it should be somebody goes to a page and create an User. Then, it creates an UserProfile associated to that newly created User.\nThe question is, how and when do you want this UserProfile instance to be created?\n\nAutomatically, whenever a new User is created : use signals, as described in the docs\nAutomatically, whenever the profile is accessed from an user instance : use AutoOneToOneField, and access the profile using user.userprofile instead of user.get_profile()\nManually. But don't forget an user might have no UserProfile associated yet, so user.get_profile() might raise a DoesNotExist exception.\n\n\nWhen they do this, where does the related User get created?\n\nIt doesn't. You have to create it explicitely.\n\nThis idea of asking somebody to sign up for an account, and then create a MyUserProfile with a form that asks for the password, username, email, et al, and then in my view creating 2 different objects (MyUserProfile and User) with different parts of the form data. I mean I shouldn't have a User form right?\n\nWhy not? You want here to create an User and his associated profile in one go, right? You could eventually use directly the POST data, or use a Form to access to the fields, or even better, use 2 ModelForm (one for User, one for UserProfile) that you will process in the same view (maybe this question can help?)\n\nMaybe there is a good example of this sort of thing being done on some open source project.\n\nI suggest you check out django-registration and django-profiles.\nNote\nYou have another way of adding information to an User object, by extending the model itsel. It will allow you to put your extra fields directly in the user model and might be easier for you to understand and use.\nI won't dive into details here, have a look at that tutorial for more informations.\nOther questions\n\nI tried to use AutoOneToOneField from django-annoying, but I have no idea where all the User's attributes get set or how to decide which User object to attach to it. This stuff is driving me crazy\n\nSee above on how to use it. If you feel uncomfortable with it, the best is to follow the documentation, which recommend using a ForeignKey with unique=True in user profiles.\n\nAlso, do I need to use the sites app to do this stuff\n\nFrom the site framework docs : Use it if your single Django installation powers more than one site and you need to differentiate between those sites in some way.\n\nand finally does a \"super user\" have all permissions to everything (I don't want people from Account \"Acme\" to access account \"Microshaft\" objects)?\n\nAgain, from the docs, Designates that this user has all permissions without explicitly assigning them. That means that everywhere Django is using the built-in permission system (e.g. default administration pages), a super-user will be authorized.\nIn views you're writing yourself, or if you tweak some ModelAdmin, it's up to you to decide how you are going to check permissions.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002293924_django_python.txt
|
Q:
How do I create a list or set object in a class in Python?
For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects.
Thus for the "lecturers" dictionary (currently):
lecturer[id] = Lecturer(lec_name, lec_id, max_students)
I'm currently reading in a white-space delimited text file that has been generated from a database. I have no direct access to the database so I haven't much say on how the file is formatted. Here's a fictionalised snippet that shows how the text file is structured. Please pardon the cheesiness.
0001 001 "Miyamoto, S." "Even Newer Super Mario Bros"
0002 001 "Miyamoto, S." "Legend of Zelda: Skies of Hyrule"
0003 002 "Molyneux, P." "Project Milo"
0004 002 "Molyneux, P." "Fable III"
0005 003 "Blow, J." "Ponytail"
The structure of each line is basically proj_id, lec_id, lec_name, proj_name.
Now, I'm currently reading the relevant data into the relevant objects. Thus, proj_id is stored in class Project whereas lec_name is a class Lecturer object, et al. The Lecturer and Project classes are not currently related.
However, as I read in each line from the text file, for that line, I wish to read in the project offered by the lecturer into the Lecturer class; I'm already reading the proj_id into the Project class. I'd like to create an object in Lecturer called offered_proj which should be a set or list of the projects offered by that lecturer. Thus whenever, for a line, I read in a new project under the same lec_id, offered_proj will be updated with that project. If I wanted to get display a list of projects offered by a lecturer I'd ideally just want to use print lecturers[lec_id].offered_proj.
My Python isn't great and I'd appreciate it if someone could show me a way to do that. I'm not sure if it's better as a set or a list, as well.
Update
After the advice from Alex Martelli and Oddthinking I went back and made some changes and tried to print the results.
Here's the code snippet:
for line in csv_file:
proj_id = int(line[0])
lec_id = int(line[1])
lec_name = line[2]
proj_name = line[3]
projects[proj_id] = Project(proj_id, proj_name)
lecturers[lec_id] = Lecturer(lec_id, lec_name)
if lec_id in lecturers.keys():
lecturers[lec_id].offered_proj.add(proj_id)
print lec_id, lecturers[lec_id].offered_proj
The print lecturers[lec_id].offered_proj line prints the following output:
001 set([0001])
001 set([0002])
002 set([0003])
002 set([0004])
003 set([0005])
It basically feels like the set is being over-written or somesuch. So if I try to print for a specific lecturer print lec_id, lecturers[001].offered_proj all I get is the last the proj_id that has been read in.
A:
set is better since you don't care about order and have no duplicate.
You can parse the file easily with the csv module (with a delimiter of ' ').
Once you have the lec_name you must check if that lecturer's already know; for that purpose, keep a dictionary from lec_name to lecturer objects (that's just another reference to the same lecturer object which you also refer to from the lecturer dictionary). On finding a lec_name that's not in that dictionary you know it's a lecturer not previously seen, so make a new lecturer object (and stick it in both dicts) in that case only, with an empty set of offered courses. Finally, just .add the course to the current lecturer's offered_proj. It's really a pretty smooth flow.
Have you tried implementing this flow? If so, what problems have you had? Can you show us the relevant code -- should be a dozen lines or so, at most?
Edit: since the OP has posted code now, I can spot the bug -- it's here:
lecturers[lec_id] = Lecturer(lec_id, lec_name)
if lec_id in lecturers.keys():
lecturers[lec_id].offered_proj.add(proj_id)
this is unconditionally creating a new lecturer object (trampling over the old one in the lecturers dict, if any) so of course the previous set gets tossed away. This is the code you need: first check, and create only if needed! (also, minor bug, don't check in....keys(), that's horribly inefficient - just check for presence in the dict). As follows:
if lec_id in lecturers:
thelec = lecturers[lec_id]
else:
thelec = lecturers[lec_id] = Lecturer(lec_id, lec_name)
thelec.offered_proj.add(proj_id)
You could express this in several different ways, but I hope this is clear enough. Just for completeness, the way I would normally phrase it (to avoid two lookups into the dictionary) is as follows:
thelec = lecturers.get(lec_id)
if thelec is None:
thelec = lecturers[lec_id] = Lecturer(lec_id, lec_name)
thelec.offered_proj.add(proj_id)
A:
Sets are useful when you want to guarantee you only have one instance of each item. They are also faster than a list at calculating whether an item is present in the collection.
Lists are faster at adding items, and also have an ordering.
This sounds like you would like a set. You sound like you are very close already.
in Lecturer.init, add a line:
self.offered_proj = set()
That will make an empty set.
When you read in the project, you can simply add to that set:
lecturer.offered_proj.add(project)
And you can print, just as you suggest (although you may like to pretty it up.)
A:
Thanks for the help Alex and Oddthinking! I think I've figured out what was going on:
I modified the code snippet that I added to the question. Basically, every time it read the line I think it was recreating the lecturer object. Thus I put in another if statement that checks if lec_id already exists in the dictionary. If it does, then it skips the object creation and simply moves onto adding projects to the offered_proj set.
The change I made is:
if not lec_id in lecturers.keys():
projects[proj_id] = Project(proj_id, proj_name)
lecturers[lec_id] = Lecturer(lec_id, lec_name)
lecturers[lec_id].offered_proj.add(proj_id)
I only recently discovered the concept behind if not thanks to my friend Samir.
Now I get the following output:
001 set([0001])
001 set([0001, 0002])
002 set([0003])
002 set([0003, 0004])
003 set([0005])
If I print for a chosen lec_id I get the fully updated set. Glee.
|
How do I create a list or set object in a class in Python?
|
For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects.
Thus for the "lecturers" dictionary (currently):
lecturer[id] = Lecturer(lec_name, lec_id, max_students)
I'm currently reading in a white-space delimited text file that has been generated from a database. I have no direct access to the database so I haven't much say on how the file is formatted. Here's a fictionalised snippet that shows how the text file is structured. Please pardon the cheesiness.
0001 001 "Miyamoto, S." "Even Newer Super Mario Bros"
0002 001 "Miyamoto, S." "Legend of Zelda: Skies of Hyrule"
0003 002 "Molyneux, P." "Project Milo"
0004 002 "Molyneux, P." "Fable III"
0005 003 "Blow, J." "Ponytail"
The structure of each line is basically proj_id, lec_id, lec_name, proj_name.
Now, I'm currently reading the relevant data into the relevant objects. Thus, proj_id is stored in class Project whereas lec_name is a class Lecturer object, et al. The Lecturer and Project classes are not currently related.
However, as I read in each line from the text file, for that line, I wish to read in the project offered by the lecturer into the Lecturer class; I'm already reading the proj_id into the Project class. I'd like to create an object in Lecturer called offered_proj which should be a set or list of the projects offered by that lecturer. Thus whenever, for a line, I read in a new project under the same lec_id, offered_proj will be updated with that project. If I wanted to get display a list of projects offered by a lecturer I'd ideally just want to use print lecturers[lec_id].offered_proj.
My Python isn't great and I'd appreciate it if someone could show me a way to do that. I'm not sure if it's better as a set or a list, as well.
Update
After the advice from Alex Martelli and Oddthinking I went back and made some changes and tried to print the results.
Here's the code snippet:
for line in csv_file:
proj_id = int(line[0])
lec_id = int(line[1])
lec_name = line[2]
proj_name = line[3]
projects[proj_id] = Project(proj_id, proj_name)
lecturers[lec_id] = Lecturer(lec_id, lec_name)
if lec_id in lecturers.keys():
lecturers[lec_id].offered_proj.add(proj_id)
print lec_id, lecturers[lec_id].offered_proj
The print lecturers[lec_id].offered_proj line prints the following output:
001 set([0001])
001 set([0002])
002 set([0003])
002 set([0004])
003 set([0005])
It basically feels like the set is being over-written or somesuch. So if I try to print for a specific lecturer print lec_id, lecturers[001].offered_proj all I get is the last the proj_id that has been read in.
|
[
"set is better since you don't care about order and have no duplicate.\nYou can parse the file easily with the csv module (with a delimiter of ' ').\nOnce you have the lec_name you must check if that lecturer's already know; for that purpose, keep a dictionary from lec_name to lecturer objects (that's just another reference to the same lecturer object which you also refer to from the lecturer dictionary). On finding a lec_name that's not in that dictionary you know it's a lecturer not previously seen, so make a new lecturer object (and stick it in both dicts) in that case only, with an empty set of offered courses. Finally, just .add the course to the current lecturer's offered_proj. It's really a pretty smooth flow.\nHave you tried implementing this flow? If so, what problems have you had? Can you show us the relevant code -- should be a dozen lines or so, at most?\nEdit: since the OP has posted code now, I can spot the bug -- it's here:\nlecturers[lec_id] = Lecturer(lec_id, lec_name)\nif lec_id in lecturers.keys():\n lecturers[lec_id].offered_proj.add(proj_id)\n\nthis is unconditionally creating a new lecturer object (trampling over the old one in the lecturers dict, if any) so of course the previous set gets tossed away. This is the code you need: first check, and create only if needed! (also, minor bug, don't check in....keys(), that's horribly inefficient - just check for presence in the dict). As follows:\nif lec_id in lecturers:\n thelec = lecturers[lec_id]\nelse:\n thelec = lecturers[lec_id] = Lecturer(lec_id, lec_name)\nthelec.offered_proj.add(proj_id)\n\nYou could express this in several different ways, but I hope this is clear enough. Just for completeness, the way I would normally phrase it (to avoid two lookups into the dictionary) is as follows:\nthelec = lecturers.get(lec_id)\nif thelec is None:\n thelec = lecturers[lec_id] = Lecturer(lec_id, lec_name)\nthelec.offered_proj.add(proj_id)\n\n",
"Sets are useful when you want to guarantee you only have one instance of each item. They are also faster than a list at calculating whether an item is present in the collection.\nLists are faster at adding items, and also have an ordering.\nThis sounds like you would like a set. You sound like you are very close already.\nin Lecturer.init, add a line:\nself.offered_proj = set()\n\nThat will make an empty set.\nWhen you read in the project, you can simply add to that set:\nlecturer.offered_proj.add(project)\n\nAnd you can print, just as you suggest (although you may like to pretty it up.)\n",
"Thanks for the help Alex and Oddthinking! I think I've figured out what was going on: \nI modified the code snippet that I added to the question. Basically, every time it read the line I think it was recreating the lecturer object. Thus I put in another if statement that checks if lec_id already exists in the dictionary. If it does, then it skips the object creation and simply moves onto adding projects to the offered_proj set. \nThe change I made is: \nif not lec_id in lecturers.keys():\n projects[proj_id] = Project(proj_id, proj_name)\nlecturers[lec_id] = Lecturer(lec_id, lec_name)\nlecturers[lec_id].offered_proj.add(proj_id)\n\nI only recently discovered the concept behind if not thanks to my friend Samir.\nNow I get the following output: \n001 set([0001])\n001 set([0001, 0002])\n002 set([0003])\n002 set([0003, 0004])\n003 set([0005])\n\nIf I print for a chosen lec_id I get the fully updated set. Glee.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"class",
"dictionary",
"python"
] |
stackoverflow_0002293968_class_dictionary_python.txt
|
Q:
Beginner extending C with Python (specifically Numpy)
I am working on a real time audio processing dynamically linked library where I have a 2 dimensional C array of floating point data which represents the audio buffer. One dimension is time (samples) and the other is channel. I would like to pass this to a python script as a numpy array for the DSP processing and then I would like to pass this back to C so the data can carry on down the processing chain in C. The member function in C++ which does the processing looks like this:
void myEffect::process (float** inputs, float** outputs, int buffersize)
{
//Some processing stuff
}
The arrays inputs and outputs are of equal size. The integer buffersize is the number of columns in the inputs and outputs arrays. On the python side I would like the processing to be carried out by a function which looks like the following:
class myPyEffect
...
...
def process(self,inBuff):
#inBuff and outBuff should be numpy arrays
outBuff = inBuff * self.whatever # some DSP stuff
return outBuff
...
...
Now, my question is, how can I go about getting the data in and out of C in the most efficient way possible (avoiding unnecessary memory copying etc.)? So far, for simple parameter changes I have been using C-API calls like the following:
pValue = PyObject_CallMethod(pInstance, "setParameter", "(f)", value);
Do I use something similar for my numpy arrays or is there a better way? Thanks for reading.
A:
You may be able to avoid dealing with the NumPy C API entirely. Python can call C code using the ctypes module, and you can access pointers into the numpy data using the array's ctypes attribute.
Here's a minimal example showing the process for a 1d sum-of-squares function.
ctsquare.c
#include <stdlib.h>
float mysumsquares(float * array, size_t size) {
float total = 0.0f;
size_t idx;
for (idx = 0; idx < size; ++idx) {
total += array[idx]*array[idx];
}
return total;
}
compilation to ctsquare.so
These command lines are for OS X, your OS may vary.
$ gcc -O3 -fPIC -c ctsquare.c -o ctsquare.o
$ ld -dylib -o ctsquare.so -lc ctsquare.o
ctsquare.py
import numpy
import ctypes
# pointer to float type, for convenience
c_float_p = ctypes.POINTER(ctypes.c_float)
# load the library
ctsquarelib = ctypes.cdll.LoadLibrary("ctsquare.so")
# define the return type and arguments of the function
ctsquarelib.mysumsquares.restype = ctypes.c_float
ctsquarelib.mysumsquares.argtypes = [c_float_p, ctypes.c_size_t]
# python front-end function, takes care of the ctypes interface
def myssq(arr):
# make sure that the array is contiguous and the right data type
arr = numpy.ascontiguousarray(arr, dtype='float32')
# grab a pointer to the array's data
dataptr = arr.ctypes.data_as(c_float_p)
# this assumes that the array is 1-dimensional. 2d is more complex.
datasize = arr.ctypes.shape[0]
# call the C function
ret = ctsquarelib.mysumsquares(dataptr, datasize)
return ret
if __name__ == '__main__':
a = numpy.array([1,2,3,4])
print 'sum of squares of [1,2,3,4] =', myssq(a)
|
Beginner extending C with Python (specifically Numpy)
|
I am working on a real time audio processing dynamically linked library where I have a 2 dimensional C array of floating point data which represents the audio buffer. One dimension is time (samples) and the other is channel. I would like to pass this to a python script as a numpy array for the DSP processing and then I would like to pass this back to C so the data can carry on down the processing chain in C. The member function in C++ which does the processing looks like this:
void myEffect::process (float** inputs, float** outputs, int buffersize)
{
//Some processing stuff
}
The arrays inputs and outputs are of equal size. The integer buffersize is the number of columns in the inputs and outputs arrays. On the python side I would like the processing to be carried out by a function which looks like the following:
class myPyEffect
...
...
def process(self,inBuff):
#inBuff and outBuff should be numpy arrays
outBuff = inBuff * self.whatever # some DSP stuff
return outBuff
...
...
Now, my question is, how can I go about getting the data in and out of C in the most efficient way possible (avoiding unnecessary memory copying etc.)? So far, for simple parameter changes I have been using C-API calls like the following:
pValue = PyObject_CallMethod(pInstance, "setParameter", "(f)", value);
Do I use something similar for my numpy arrays or is there a better way? Thanks for reading.
|
[
"You may be able to avoid dealing with the NumPy C API entirely. Python can call C code using the ctypes module, and you can access pointers into the numpy data using the array's ctypes attribute. \nHere's a minimal example showing the process for a 1d sum-of-squares function.\nctsquare.c\n#include <stdlib.h>\n\nfloat mysumsquares(float * array, size_t size) {\n float total = 0.0f;\n size_t idx;\n for (idx = 0; idx < size; ++idx) {\n total += array[idx]*array[idx];\n }\n return total;\n}\n\ncompilation to ctsquare.so\nThese command lines are for OS X, your OS may vary.\n$ gcc -O3 -fPIC -c ctsquare.c -o ctsquare.o\n$ ld -dylib -o ctsquare.so -lc ctsquare.o\n\nctsquare.py\nimport numpy\nimport ctypes\n\n# pointer to float type, for convenience\nc_float_p = ctypes.POINTER(ctypes.c_float)\n\n# load the library\nctsquarelib = ctypes.cdll.LoadLibrary(\"ctsquare.so\")\n\n# define the return type and arguments of the function\nctsquarelib.mysumsquares.restype = ctypes.c_float\nctsquarelib.mysumsquares.argtypes = [c_float_p, ctypes.c_size_t]\n\n# python front-end function, takes care of the ctypes interface\ndef myssq(arr):\n # make sure that the array is contiguous and the right data type\n arr = numpy.ascontiguousarray(arr, dtype='float32')\n\n # grab a pointer to the array's data\n dataptr = arr.ctypes.data_as(c_float_p)\n\n # this assumes that the array is 1-dimensional. 2d is more complex.\n datasize = arr.ctypes.shape[0]\n\n # call the C function\n ret = ctsquarelib.mysumsquares(dataptr, datasize)\n\n return ret\n\nif __name__ == '__main__':\n a = numpy.array([1,2,3,4])\n print 'sum of squares of [1,2,3,4] =', myssq(a)\n\n"
] |
[
7
] |
[] |
[] |
[
"api",
"c",
"c++",
"numpy",
"python"
] |
stackoverflow_0002290007_api_c_c++_numpy_python.txt
|
Q:
Deferred evaluation in python
I have heard of deferred evaluation in python (for example here), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many errors until runtime?
Or am I missing something entirely?
A:
Deferred evaluation is when an expression isn't evaluated until it's needed. In most languages, you use something like lambda to make this work. Here's a contrived example that shows part of the concept:
def list_files():
for fn in os.listdir('.'):
yield fn, lambda: open(fn, 'r').read()
for fn, body in list_files():
if fn.endswith('.txt'):
print body()
Here, list_files returns a bunch of filenames and a "thunk" (lambda with no arguments) which returns the file's contents. The "thunk" is a deferred evaluation. Using thunks allows you to separate your concerns:
The for loop doesn't need to know how to read files, so list_files could be replaced with list_ftp_files or list_zip_archive.
The list_files function doesn't need to know which files will be read. With thunks, it doesn't have to read every single file.
In proper deferred evaluation, once you evaluated the "thunk" it would replace itself with an evaluated copy, so evaluating it twice would be no more work than evaluating it once. There are other ways to accomplish the same thing, such as with classes and objects which cache values.
Deferred evaluation is a (relatively) common idiom in Scheme. In Haskell, evaluations are deferred by default and you don't need any syntax to do it (there's special syntax for turning it off).
A:
Dietrich's answer is a good one, but I just want to add that the simplest form of deferred evaluation is the if statement:
if True:
x = 5
else:
x = y # huh? what is y?
This code parses and runs correctly, although the else clause makes no sense - y is undefined. The else clause is only being parsed - so it should be valid Python syntactically. This can be actually used for some simple code:
if stuff:
print stuff.contents
else:
print "no stuff"
In a strongly typed language this wouldn't work, because to type stuff.contents requires stuff to be of a certain type that has a contents attribute. In Python, because of the deferred evaluation of the statements in if, this isn't necessarily true. stuff can be None which obviously has no attributes, and the interpreter will just take the else clause without executing the first. Hence this is valid Python and even an idiom, that makes code simpler.
Reference discussion
|
Deferred evaluation in python
|
I have heard of deferred evaluation in python (for example here), is it just referring to how lambdas are evaluated by the interpreter only when they are used? Or is this the proper term for describing how, due to python's dynamic design, it will not catch many errors until runtime?
Or am I missing something entirely?
|
[
"Deferred evaluation is when an expression isn't evaluated until it's needed. In most languages, you use something like lambda to make this work. Here's a contrived example that shows part of the concept:\ndef list_files():\n for fn in os.listdir('.'):\n yield fn, lambda: open(fn, 'r').read()\n\n\nfor fn, body in list_files():\n if fn.endswith('.txt'):\n print body()\n\nHere, list_files returns a bunch of filenames and a \"thunk\" (lambda with no arguments) which returns the file's contents. The \"thunk\" is a deferred evaluation. Using thunks allows you to separate your concerns:\n\nThe for loop doesn't need to know how to read files, so list_files could be replaced with list_ftp_files or list_zip_archive.\nThe list_files function doesn't need to know which files will be read. With thunks, it doesn't have to read every single file.\n\nIn proper deferred evaluation, once you evaluated the \"thunk\" it would replace itself with an evaluated copy, so evaluating it twice would be no more work than evaluating it once. There are other ways to accomplish the same thing, such as with classes and objects which cache values.\nDeferred evaluation is a (relatively) common idiom in Scheme. In Haskell, evaluations are deferred by default and you don't need any syntax to do it (there's special syntax for turning it off).\n",
"Dietrich's answer is a good one, but I just want to add that the simplest form of deferred evaluation is the if statement:\nif True:\n x = 5\nelse:\n x = y # huh? what is y?\n\nThis code parses and runs correctly, although the else clause makes no sense - y is undefined. The else clause is only being parsed - so it should be valid Python syntactically. This can be actually used for some simple code:\nif stuff:\n print stuff.contents\nelse:\n print \"no stuff\"\n\nIn a strongly typed language this wouldn't work, because to type stuff.contents requires stuff to be of a certain type that has a contents attribute. In Python, because of the deferred evaluation of the statements in if, this isn't necessarily true. stuff can be None which obviously has no attributes, and the interpreter will just take the else clause without executing the first. Hence this is valid Python and even an idiom, that makes code simpler.\nReference discussion\n"
] |
[
17,
8
] |
[] |
[] |
[
"evaluation",
"interpreter",
"lambda",
"python"
] |
stackoverflow_0002294236_evaluation_interpreter_lambda_python.txt
|
Q:
'ASCII' to Unicode error in python when attempting to read a latin-1 encoded string
I'm having a problem when trying to apply a regular expression to some strings encoded in latin-1 (ISO-8859-1).
What I'm trying to do is send some data via HTTP POST from a page encoded in ISO-8859-1 to my python application and do some parsing on the data using regular expressions in my python script.
The web page uses jQuery to send the data to the server and I'm grabbing the text from the page using the .text() method. Once the data is sent back to the server looks like this: re.compile(r"^[\s,]*(\d*\s*\d*\/*\d)[\s,]*") - Unfortunately the \s in my regular expression is not matching my data, and I traced the problem down to the fact that the html page uses which gets encoded to 0xA0 (non-breaking space) and sent to the server. For some reason, it seems, my script is not interpreting that character as whitespace and is not matching. According to the python [documentation][1] it looks like this should work, so I must have an encoding issue here.
I then wanted to try converting the string into unicode and pass it to the regular expression, so I tried to view what would happen when I converted the string: print(unicode(data, 'iso-8859-1')).
Unfortunately I got this error:
UnicodeEncodeError at /script/
'ascii' codec can't encode character u'\xa0' in position 122: ordinal not in range(128)
I'm confused though - I'm obviously not trying to use ASCII decoding - is python trying to decode using ASCII even though I'm obviously passing another codec?
A:
Try this instead:
print(repr(unicode(data, 'iso-8859-1')))
by printing a unicode object you're implicitly trying to convert it to the default encoding, which is ASCII. Using repr will escape it into an ASCII-safe form, plus it'll be easier for you to figure out what's going on for debugging.
A:
Are you using Python 3.X or 2.X? It makes a difference. Actually looks like 2.X but you confused me by using print(blahblah) :-)
Answer to your last question: Yes, ASCII by default when you do print(). On 3.X: Use print(ascii(foo)) for debugging, not print(foo). On 2.X use repr(), not ascii().
Your original problem with the no-break space should go away if (a) the data is unicode and (b) you use the re.UNICODE flag with the re.compile()
|
'ASCII' to Unicode error in python when attempting to read a latin-1 encoded string
|
I'm having a problem when trying to apply a regular expression to some strings encoded in latin-1 (ISO-8859-1).
What I'm trying to do is send some data via HTTP POST from a page encoded in ISO-8859-1 to my python application and do some parsing on the data using regular expressions in my python script.
The web page uses jQuery to send the data to the server and I'm grabbing the text from the page using the .text() method. Once the data is sent back to the server looks like this: re.compile(r"^[\s,]*(\d*\s*\d*\/*\d)[\s,]*") - Unfortunately the \s in my regular expression is not matching my data, and I traced the problem down to the fact that the html page uses which gets encoded to 0xA0 (non-breaking space) and sent to the server. For some reason, it seems, my script is not interpreting that character as whitespace and is not matching. According to the python [documentation][1] it looks like this should work, so I must have an encoding issue here.
I then wanted to try converting the string into unicode and pass it to the regular expression, so I tried to view what would happen when I converted the string: print(unicode(data, 'iso-8859-1')).
Unfortunately I got this error:
UnicodeEncodeError at /script/
'ascii' codec can't encode character u'\xa0' in position 122: ordinal not in range(128)
I'm confused though - I'm obviously not trying to use ASCII decoding - is python trying to decode using ASCII even though I'm obviously passing another codec?
|
[
"Try this instead:\nprint(repr(unicode(data, 'iso-8859-1')))\n\nby printing a unicode object you're implicitly trying to convert it to the default encoding, which is ASCII. Using repr will escape it into an ASCII-safe form, plus it'll be easier for you to figure out what's going on for debugging.\n",
"Are you using Python 3.X or 2.X? It makes a difference. Actually looks like 2.X but you confused me by using print(blahblah) :-)\nAnswer to your last question: Yes, ASCII by default when you do print(). On 3.X: Use print(ascii(foo)) for debugging, not print(foo). On 2.X use repr(), not ascii().\nYour original problem with the no-break space should go away if (a) the data is unicode and (b) you use the re.UNICODE flag with the re.compile()\n"
] |
[
2,
1
] |
[] |
[] |
[
"encoding",
"python"
] |
stackoverflow_0002294509_encoding_python.txt
|
Q:
how to write integer number in particular no of bytes in python ( file writing)
assume i have to store few integer numbers like 1024 or 512 or 10240 or 900000 in a file, but the condition is that i can consume only 4 bytes (not less nor max).but while writing a python file using write method it stored as "1024" or "512" or "10240" ie they written as ascii value but i want to store directly their binary value.
Any help will really appreciable.
A:
use the struct module
>>> import struct
>>> struct.pack("i",1024)
'\x00\x04\x00\x00'
>>> struct.pack("i",10240)
'\x00(\x00\x00'
>>> struct.pack("i",900000)
'\xa0\xbb\r\x00'
In Python3, it you can use the to_bytes method of int. The paren around 1024 are only necessary as 1024. parses as a float and would cause a syntax error.
>>> (1024).to_bytes(4, "big")
b'\x00\x00\x04\x00'
>>> (1024).to_bytes(4, "little")
b'\x00\x04\x00\x00'
A:
The struct module will do
>>> import struct
>>> f = open('binary.bin','wb')
>>> f.write(struct.pack("l",1024))
>>> f.close()
vinko@parrot:~$ xxd -b binary.bin
0000000: 00000000 00000100 00000000 00000000 ....
|
how to write integer number in particular no of bytes in python ( file writing)
|
assume i have to store few integer numbers like 1024 or 512 or 10240 or 900000 in a file, but the condition is that i can consume only 4 bytes (not less nor max).but while writing a python file using write method it stored as "1024" or "512" or "10240" ie they written as ascii value but i want to store directly their binary value.
Any help will really appreciable.
|
[
"use the struct module\n>>> import struct\n>>> struct.pack(\"i\",1024)\n'\\x00\\x04\\x00\\x00'\n>>> struct.pack(\"i\",10240)\n'\\x00(\\x00\\x00'\n>>> struct.pack(\"i\",900000)\n'\\xa0\\xbb\\r\\x00'\n\nIn Python3, it you can use the to_bytes method of int. The paren around 1024 are only necessary as 1024. parses as a float and would cause a syntax error.\n>>> (1024).to_bytes(4, \"big\")\nb'\\x00\\x00\\x04\\x00'\n>>> (1024).to_bytes(4, \"little\")\nb'\\x00\\x04\\x00\\x00'\n\n",
"The struct module will do\n>>> import struct\n>>> f = open('binary.bin','wb')\n>>> f.write(struct.pack(\"l\",1024))\n>>> f.close()\n\nvinko@parrot:~$ xxd -b binary.bin\n0000000: 00000000 00000100 00000000 00000000 ....\n\n"
] |
[
13,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002294608_python.txt
|
Q:
How can I replace double and single quotations in a string efficiently?
I'm parsing a xml file and inserting it into database.
However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient.
s = s.replace('"', ' ')
s = s.replace("'", ' ')
Is there any way I can insert text without replacing these quotations?
OR
Is there any efficient way to substitute them efficiently ?
Thanks !
A:
Why can't you insert strings containing quote marks into your database? Is there some weird data type that permits any character except a quote mark? Or are you building an insert statement with literal strings, rather than binding your strings to query parameters as you should be doing?
If you're doing
cursor.execute('insert into mytable (somefield) values ("%s")' % (mystring))
then that's unsafe and wrong. Instead, you should be doing
cursor.execute('insert into mytable (somefield) values (%(myparam)s)',
dict(myparam=mystring))
A:
you should use str.translate instead of doing two replace() calls
>>> import string
>>> quotes_to_spaces=string.maketrans('"\''," ")
>>> s=s.translate(quotes_to_spaces)
A:
You could try something like _mysql.escape_string():
>>> import _mysql
>>> a = '''I said, "Don't do that"'''
>>> a
'I said, "Don\'t do that"'
>>> _mysql.escape_string(a)
'I said, \\"Don\\\'t do that\\"'
However, the manual recommends using connection.escape_string(), but I think you need a database connection first.
|
How can I replace double and single quotations in a string efficiently?
|
I'm parsing a xml file and inserting it into database.
However since some text containes double or single quotation I'm having problem with insertion. Currently I'm using the code shown below. But it seems it's inefficient.
s = s.replace('"', ' ')
s = s.replace("'", ' ')
Is there any way I can insert text without replacing these quotations?
OR
Is there any efficient way to substitute them efficiently ?
Thanks !
|
[
"Why can't you insert strings containing quote marks into your database? Is there some weird data type that permits any character except a quote mark? Or are you building an insert statement with literal strings, rather than binding your strings to query parameters as you should be doing?\nIf you're doing\ncursor.execute('insert into mytable (somefield) values (\"%s\")' % (mystring))\n\nthen that's unsafe and wrong. Instead, you should be doing\ncursor.execute('insert into mytable (somefield) values (%(myparam)s)',\n dict(myparam=mystring))\n\n",
"you should use str.translate instead of doing two replace() calls \n>>> import string\n>>> quotes_to_spaces=string.maketrans('\"\\'',\" \")\n>>> s=s.translate(quotes_to_spaces)\n\n",
"You could try something like _mysql.escape_string():\n>>> import _mysql\n>>> a = '''I said, \"Don't do that\"'''\n>>> a\n'I said, \"Don\\'t do that\"'\n>>> _mysql.escape_string(a)\n'I said, \\\\\"Don\\\\\\'t do that\\\\\"'\n\nHowever, the manual recommends using connection.escape_string(), but I think you need a database connection first.\n"
] |
[
12,
2,
1
] |
[] |
[] |
[
"database",
"python",
"string"
] |
stackoverflow_0002293854_database_python_string.txt
|
Q:
How do I define an array of custom types in WSDL?
I'm very new to WSDL, but what I'm trying to do is very simple. I have gotten a web service working with python's ZSI library, but am stuck defining a service which returns an array of a custom type.
In my WSDL I have the following:
<xsd:element name="ArtPiece">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="title" type="xsd:string" />
<xsd:element name="year" type="xsd:string" />
<xsd:element name="imageId" type="xsd:int" minOccurs="0" />
<xsd:element name="image" type="xsd:base64Binary" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
If I try to add another element like ArtPieceArray that's defined by having an unlimited number of ArtPiece types, that seems to be invalid.
If, when I'm defining my message, I try to use ArtPiece[], that also seems to be invalid.
I'm using ZSI for the web service, and C# for the client. The client web service code is generated by wsdl.exe
Any suggestions?
A:
<xs:schema elementFormDefault="qualified"
targetNamespace="http://schemas.datacontract.org/2004/07/Foo"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://schemas.datacontract.org/2004/07/Foo">
<xs:complexType name="ArtPiece">
<xs:sequence>
<xs:element minOccurs="0" name="image" nillable="true" type="xs:base64Binary"/>
<xs:element minOccurs="0" name="imageId" type="xs:int"/>
<xs:element minOccurs="0" name="title" nillable="true" type="xs:string"/>
<xs:element minOccurs="0" name="year" nillable="true" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="ArtPiece" nillable="true" type="tns:ArtPiece"/>
<xs:complexType name="ArrayOfArtPiece">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="unbounded" name="ArtPiece" nillable="true" type="tns:ArtPiece"/>
</xs:sequence>
</xs:complexType>
<xs:element name="ArrayOfArtPiece" nillable="true" type="tns:ArrayOfArtPiece"/>
</xs:schema>
|
How do I define an array of custom types in WSDL?
|
I'm very new to WSDL, but what I'm trying to do is very simple. I have gotten a web service working with python's ZSI library, but am stuck defining a service which returns an array of a custom type.
In my WSDL I have the following:
<xsd:element name="ArtPiece">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="title" type="xsd:string" />
<xsd:element name="year" type="xsd:string" />
<xsd:element name="imageId" type="xsd:int" minOccurs="0" />
<xsd:element name="image" type="xsd:base64Binary" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
If I try to add another element like ArtPieceArray that's defined by having an unlimited number of ArtPiece types, that seems to be invalid.
If, when I'm defining my message, I try to use ArtPiece[], that also seems to be invalid.
I'm using ZSI for the web service, and C# for the client. The client web service code is generated by wsdl.exe
Any suggestions?
|
[
"<xs:schema elementFormDefault=\"qualified\" \n targetNamespace=\"http://schemas.datacontract.org/2004/07/Foo\" \n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" \n xmlns:tns=\"http://schemas.datacontract.org/2004/07/Foo\">\n <xs:complexType name=\"ArtPiece\">\n <xs:sequence>\n <xs:element minOccurs=\"0\" name=\"image\" nillable=\"true\" type=\"xs:base64Binary\"/>\n <xs:element minOccurs=\"0\" name=\"imageId\" type=\"xs:int\"/>\n <xs:element minOccurs=\"0\" name=\"title\" nillable=\"true\" type=\"xs:string\"/>\n <xs:element minOccurs=\"0\" name=\"year\" nillable=\"true\" type=\"xs:string\"/>\n </xs:sequence>\n </xs:complexType>\n\n <xs:element name=\"ArtPiece\" nillable=\"true\" type=\"tns:ArtPiece\"/>\n\n <xs:complexType name=\"ArrayOfArtPiece\">\n <xs:sequence>\n <xs:element minOccurs=\"0\" maxOccurs=\"unbounded\" name=\"ArtPiece\" nillable=\"true\" type=\"tns:ArtPiece\"/>\n </xs:sequence>\n </xs:complexType>\n\n <xs:element name=\"ArrayOfArtPiece\" nillable=\"true\" type=\"tns:ArrayOfArtPiece\"/>\n</xs:schema>\n\n"
] |
[
26
] |
[] |
[] |
[
"c#",
"python",
"soap",
"web_services",
"wsdl"
] |
stackoverflow_0002293873_c#_python_soap_web_services_wsdl.txt
|
Q:
Sudo equivalent for Django user profiles
Is it possible to implement an equivalent of sudo for Django profiles ? I'm using the basic authentication system django.contrib.auth.
Usecase: Sometimes, users report bugs which are only reproductible in their profile, so, each time, I change their password, log in, fix the bug and replaces the password with the original one.
I tried to implement this feature by using login() but it requires a call to authenticate() in the first place which is not an option because we don't have the password in clear text, just the hashed one.
Is there any clever way to do that? Except messing up with the user's password?
Thanks!
A:
Djangosnippets.org is your friend: http://www.djangosnippets.org/snippets/1590/
A:
I knocked up a user panel in the debug toolbar. It works well for flipping logged in users around . The fork is here.
http://github.com/mjbrownie/django-debug-toolbar
it also displays some basic user group permission info. I didn't get around to expanding it.
you could borrow the logic so it doesn't have to run in debug mode.
Edit: This post and plugin is old and no longer maintained. It looks like someone has independently created this however.
https://github.com/playfire/django-debug-toolbar-user-panel
|
Sudo equivalent for Django user profiles
|
Is it possible to implement an equivalent of sudo for Django profiles ? I'm using the basic authentication system django.contrib.auth.
Usecase: Sometimes, users report bugs which are only reproductible in their profile, so, each time, I change their password, log in, fix the bug and replaces the password with the original one.
I tried to implement this feature by using login() but it requires a call to authenticate() in the first place which is not an option because we don't have the password in clear text, just the hashed one.
Is there any clever way to do that? Except messing up with the user's password?
Thanks!
|
[
"Djangosnippets.org is your friend: http://www.djangosnippets.org/snippets/1590/\n",
"I knocked up a user panel in the debug toolbar. It works well for flipping logged in users around . The fork is here. \nhttp://github.com/mjbrownie/django-debug-toolbar\nit also displays some basic user group permission info. I didn't get around to expanding it.\nyou could borrow the logic so it doesn't have to run in debug mode.\nEdit: This post and plugin is old and no longer maintained. It looks like someone has independently created this however. \nhttps://github.com/playfire/django-debug-toolbar-user-panel\n"
] |
[
3,
2
] |
[] |
[] |
[
"authentication",
"django",
"python"
] |
stackoverflow_0002289917_authentication_django_python.txt
|
Q:
Issue with python class hierarchy
I have a class hierarchy:
class ParentClass:
def do_something(self):
pass # child classes have their own implementation of this
class ChildClass1(ParentClass):
def do_something(self):
<implementation here>
class ChildClass2(ParentClass):
def do_something(self, argument_x):
<implementation here>
class ChildClass3(ParentClass):
def do_something(self, argument_y):
<implementation here>
There are two problems here:
method do_something() has different interfaces in subclasses: it accepts an argument in child classes 2 and 3, but has no argument in child class 1
the arguments of do_something() have different names to emphasize that they have different meanings in child classes 2 and 3. This will become clearer below, from the usage example
This is how the classes are used:
There is a factory class that returns instances:
class ChildFactory:
def get_child(self, argument):
if argument == '1':
return ChildClass1()
elif argument == '2':
return ChildClass2()
elif argument == '3':
return ChildClass3()
later in code:
...
# pseudocode, not python
child_type = ? # can have values '1', '2' or '3' at this moment
var1 = 1
var2 = 'xxx'
# var1 and var2 have different types, just to emphasize the difference in their
# meaning when being passed as arguments to do_something()
# this was mentioned above (the second problem)
child = ChildFactory.get_child(child_type)
if child is an instance of ChildClass1, child.do_something() is called
if child is an instance of ChildClass2, child.do_something(var1) is called
if child is an instance of ChildClass3, child.do_something(var2) is called
# end of pseudocode
Questions:
Are the two problems mentioned above a sign of a bad design? If so, what's the correct way to design the hierarchy?
How to write the pseudocode snippet uniformly in python? The main concern is to avoid using a huge if/else statement for each particular case, because it will double the if/else statement from ChildFactory.get_child()
A:
Methods with the same name and different arguments are a code smell.
"method do_something() has different interfaces in subclasses: it accepts an argument in child classes 2 and 3, but has no argument in child class 1"
You don't say why. There are two good reasons why
child class 1 has a default value.
child class 2 ignores the value.
Almost any other reason indicates that the do_something is truly different and should have a different name.
If child class 1 has a default value, then simply code a default value explicitly in the arguments to the method function.
class ChildClass1( ParentClass ):
def do_something( argument_x= None )
....
If child class 1 ignores the value, then simply ignore the value. Don't stand on your head to ignore a vlaue.
class ChildClass1( ParentClass ):
def do_something( argument_x )
return True
There's no magic about a polymorphic method function that doesn't happen to use all argument values.
"the arguments of do_something() have different names to emphasize that they have different meanings in child classes 2 and 3."
This is just bad design. You can't have the same method function with different argument names because they do different things.
Having the same method function name is just wrong. If they are different implementations of similar things, then the arguments will have essentially the same meanings.
If they actually do different things, then you don't have polymorphism, and you should not be giving these methods the same names.
When the methods in two classes do fundamentally different things -- requiring different arguments with distinct names to make that obvious -- those methods must not have the same names. The name ceases to have meaning when it doesn't describe what the method actually does.
Note
Your code, BTW, will work in Python because of duck typing. As long as the method names match, the argument types do not have to even come close to matching. However, this is really poor design because the essential differences among the methods are so huge.
A:
Abstract questions like this are very difficult to answer. It would be much easier to answer if we knew what problem you were trying to solve. I can tell you that usually it is a bad sign to see something like:
if isinstance(obj, cls1):
...
elif isinstance(obj, cls2):
...
Usually, it means you should be defining a new method instead of using if/elif. In Python, you can define methods outside the class definition if you like, if this helps. It is also usually a bad sign if two interchangeable classes have methods with the same name but take a different number of arguments, it means that the classes are not truly interchangeable. Either the different methods should take the same arguments or they should have different names. It is also unnecessary to define methods that are never called, such as do_something in ParentClass -- this is something you see in programmers that come to Python from C++/Java/C#.
A:
If things are to be used interchangeably, they should have the the same interface. For a method, this means the same number of arguments with the same meanings and the same names in the same order. If they do not behave exactly the same, simply give them different names and make it look like they are interchangable.
|
Issue with python class hierarchy
|
I have a class hierarchy:
class ParentClass:
def do_something(self):
pass # child classes have their own implementation of this
class ChildClass1(ParentClass):
def do_something(self):
<implementation here>
class ChildClass2(ParentClass):
def do_something(self, argument_x):
<implementation here>
class ChildClass3(ParentClass):
def do_something(self, argument_y):
<implementation here>
There are two problems here:
method do_something() has different interfaces in subclasses: it accepts an argument in child classes 2 and 3, but has no argument in child class 1
the arguments of do_something() have different names to emphasize that they have different meanings in child classes 2 and 3. This will become clearer below, from the usage example
This is how the classes are used:
There is a factory class that returns instances:
class ChildFactory:
def get_child(self, argument):
if argument == '1':
return ChildClass1()
elif argument == '2':
return ChildClass2()
elif argument == '3':
return ChildClass3()
later in code:
...
# pseudocode, not python
child_type = ? # can have values '1', '2' or '3' at this moment
var1 = 1
var2 = 'xxx'
# var1 and var2 have different types, just to emphasize the difference in their
# meaning when being passed as arguments to do_something()
# this was mentioned above (the second problem)
child = ChildFactory.get_child(child_type)
if child is an instance of ChildClass1, child.do_something() is called
if child is an instance of ChildClass2, child.do_something(var1) is called
if child is an instance of ChildClass3, child.do_something(var2) is called
# end of pseudocode
Questions:
Are the two problems mentioned above a sign of a bad design? If so, what's the correct way to design the hierarchy?
How to write the pseudocode snippet uniformly in python? The main concern is to avoid using a huge if/else statement for each particular case, because it will double the if/else statement from ChildFactory.get_child()
|
[
"Methods with the same name and different arguments are a code smell.\n\"method do_something() has different interfaces in subclasses: it accepts an argument in child classes 2 and 3, but has no argument in child class 1\"\nYou don't say why. There are two good reasons why \n\nchild class 1 has a default value. \nchild class 2 ignores the value.\n\nAlmost any other reason indicates that the do_something is truly different and should have a different name.\nIf child class 1 has a default value, then simply code a default value explicitly in the arguments to the method function.\nclass ChildClass1( ParentClass ):\n def do_something( argument_x= None )\n ....\n\nIf child class 1 ignores the value, then simply ignore the value. Don't stand on your head to ignore a vlaue.\nclass ChildClass1( ParentClass ):\n def do_something( argument_x )\n return True\n\nThere's no magic about a polymorphic method function that doesn't happen to use all argument values.\n\"the arguments of do_something() have different names to emphasize that they have different meanings in child classes 2 and 3.\"\nThis is just bad design. You can't have the same method function with different argument names because they do different things.\nHaving the same method function name is just wrong. If they are different implementations of similar things, then the arguments will have essentially the same meanings.\nIf they actually do different things, then you don't have polymorphism, and you should not be giving these methods the same names.\nWhen the methods in two classes do fundamentally different things -- requiring different arguments with distinct names to make that obvious -- those methods must not have the same names. The name ceases to have meaning when it doesn't describe what the method actually does.\nNote\nYour code, BTW, will work in Python because of duck typing. As long as the method names match, the argument types do not have to even come close to matching. However, this is really poor design because the essential differences among the methods are so huge.\n",
"Abstract questions like this are very difficult to answer. It would be much easier to answer if we knew what problem you were trying to solve. I can tell you that usually it is a bad sign to see something like:\nif isinstance(obj, cls1):\n ...\nelif isinstance(obj, cls2):\n ...\n\nUsually, it means you should be defining a new method instead of using if/elif. In Python, you can define methods outside the class definition if you like, if this helps. It is also usually a bad sign if two interchangeable classes have methods with the same name but take a different number of arguments, it means that the classes are not truly interchangeable. Either the different methods should take the same arguments or they should have different names. It is also unnecessary to define methods that are never called, such as do_something in ParentClass -- this is something you see in programmers that come to Python from C++/Java/C#.\n",
"If things are to be used interchangeably, they should have the the same interface. For a method, this means the same number of arguments with the same meanings and the same names in the same order. If they do not behave exactly the same, simply give them different names and make it look like they are interchangable.\n"
] |
[
13,
2,
1
] |
[
"You could do this, to make the signatures the same:\nclass ParentClass:\n pass\n\nclass ChildClass1(ParentClass):\n\n def do_something(self, **kwargs):\n <implementation here>\n\nclass ChildClass2(ParentClass):\n\n def do_something(self, **kwargs):\n argument_x = kwargs[argument_x]\n <implementation here>\n\nclass ChildClass3(ParentClass):\n\n def do_something(self, **kwargs):\n argument_y = kwargs[argument_y]\n <implementation here>\n\nThe factory could just be a dict:\nchildfactory = {1:ChildClass1, 2:ChildClass2, 3:ChildClass3}\n\nthen later:\n...\n# pseudocode, not python\nchild_type = ? # can have values '1', '2' or '3' at this moment\nvar1 = 1\nvar2 = 'xxx'\n# var1 and var2 have different types, just to emphasize the difference in their\n# meaning when being passed as arguments to do_something()\n# this was mentioned above (the second problem)\nchild = childfactory[child_type]()\nchild.do_something(argument_x=val1, argument_y=var2)\n# end of pseudocode\n\n"
] |
[
-4
] |
[
"oop",
"python"
] |
stackoverflow_0002294200_oop_python.txt
|
Q:
assign multiple instances of a class to variables
Python. I need to assign multiple class instances to number of variables. First i tried this:
a = b = c = []
but they all refer to the same object, which is not what I need. This works better:
(a, b, c) = [[] for i in range(3)]
but it seems a bit too verbose. Is there a shorter way to do this?
UPDATE: OK, so this is not really Pythonic to cram everything into one line, question resolved.
But if this worked it'd be really cool:
a,b,c = []*3
And this line creates three references to the same object:
a,b,c = [[]] * 3
Oh well...
A:
a, b, c = [], [], []
A:
simply:
a = []
b = []
c = []
(python is not perl, there is no need for one-liners)
A:
a = []
b = a[:]
import copy
c = copy.copy(b)
You could use these if you want them all initialized to something other than []
|
assign multiple instances of a class to variables
|
Python. I need to assign multiple class instances to number of variables. First i tried this:
a = b = c = []
but they all refer to the same object, which is not what I need. This works better:
(a, b, c) = [[] for i in range(3)]
but it seems a bit too verbose. Is there a shorter way to do this?
UPDATE: OK, so this is not really Pythonic to cram everything into one line, question resolved.
But if this worked it'd be really cool:
a,b,c = []*3
And this line creates three references to the same object:
a,b,c = [[]] * 3
Oh well...
|
[
"a, b, c = [], [], []\n\n",
"simply:\na = []\nb = []\nc = []\n\n(python is not perl, there is no need for one-liners)\n",
"a = []\nb = a[:]\nimport copy\nc = copy.copy(b)\n\nYou could use these if you want them all initialized to something other than []\n"
] |
[
9,
8,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002294823_python.txt
|
Q:
python csv - export data and format color, text format, etc
I'm exporting data from python with the csv library which works pretty good. After a web-search I can not find any information about how to format the exported data with python.
For example. I export a csv row within python like this.
for hour_record in object_list:
row = list()
for field in fields:
try:
row.append(getattr(hour_record, field))
except:
pass
writer.writerow(row)
Now I'm wondering how I can pass some formating information to the row.append call. For example if I want to format the text red and make sure that it is formated as a number etc..
anybody an idea how this works?
A:
CSV is used only for plain text. If you want formatting information to be contained then you must either embed HTML fragments, or you must add the attributes as separate fields. Either option will require a consumer that understands said formatting mechanism.
A:
Instead of csv, you should use numpy.genfromtxt and numpy.savetxt:
>>> data = numpy.genfromtxt('mydata.txt', dtype=None)
>>> <-> work with the data recarray object
>>> numpy.savetxt('results.txt', data)
If you look at help(numpy.savetxt) you can see that there is a 'fmt' option that allows you to specify the output format.
To output colors, you have to use HTML as said in another answer, or you can use the module terminalcolor which is only to output to STDOUT.
|
python csv - export data and format color, text format, etc
|
I'm exporting data from python with the csv library which works pretty good. After a web-search I can not find any information about how to format the exported data with python.
For example. I export a csv row within python like this.
for hour_record in object_list:
row = list()
for field in fields:
try:
row.append(getattr(hour_record, field))
except:
pass
writer.writerow(row)
Now I'm wondering how I can pass some formating information to the row.append call. For example if I want to format the text red and make sure that it is formated as a number etc..
anybody an idea how this works?
|
[
"CSV is used only for plain text. If you want formatting information to be contained then you must either embed HTML fragments, or you must add the attributes as separate fields. Either option will require a consumer that understands said formatting mechanism.\n",
"Instead of csv, you should use numpy.genfromtxt and numpy.savetxt:\n>>> data = numpy.genfromtxt('mydata.txt', dtype=None)\n>>> <-> work with the data recarray object\n>>> numpy.savetxt('results.txt', data)\n\nIf you look at help(numpy.savetxt) you can see that there is a 'fmt' option that allows you to specify the output format.\nTo output colors, you have to use HTML as said in another answer, or you can use the module terminalcolor which is only to output to STDOUT.\n"
] |
[
3,
0
] |
[] |
[] |
[
"csv",
"python"
] |
stackoverflow_0002295727_csv_python.txt
|
Q:
join lists based on common head or tail
What is the fastest way to solve the following
I will to join several lists based on common head or tail
input = ([5,6,7], [1,2,3], [3,4,5], [8, 9])
output = [1, 2, 3, 4, 5, 6, 7]
A:
>>> def chain(inp):
d = {}
for i in inp:
d[i[0]] = i[:], i[-1]
l, n = d.pop(min(d))
while True:
lt, n = d.pop(n, [None, None])
if n is None:
if len(d) == len(inp) - 1:
l, n = d.pop(min(d))
continue
break
l += lt[1:]
return l
>>> chain(input)
[1, 2, 3, 4, 5, 6, 7]
>>> chain(([5,6,7], [1,2,10], [3,4,5], [8, 9]))
[3, 4, 5, 6, 7]
|
join lists based on common head or tail
|
What is the fastest way to solve the following
I will to join several lists based on common head or tail
input = ([5,6,7], [1,2,3], [3,4,5], [8, 9])
output = [1, 2, 3, 4, 5, 6, 7]
|
[
">>> def chain(inp):\n d = {}\n for i in inp:\n d[i[0]] = i[:], i[-1]\n l, n = d.pop(min(d))\n while True:\n lt, n = d.pop(n, [None, None])\n if n is None:\n if len(d) == len(inp) - 1:\n l, n = d.pop(min(d))\n continue\n break\n l += lt[1:]\n return l\n\n>>> chain(input)\n[1, 2, 3, 4, 5, 6, 7]\n>>> chain(([5,6,7], [1,2,10], [3,4,5], [8, 9]))\n[3, 4, 5, 6, 7]\n\n"
] |
[
1
] |
[] |
[] |
[
"head",
"join",
"list",
"python",
"tail"
] |
stackoverflow_0002296406_head_join_list_python_tail.txt
|
Q:
How to open a Pyqt 3.3 ui file with QtDesigner 4?
I've a PyQt 4 installed (I can't find PyQt 3 for Windows) and I would like to open a QtDesigner ui file which has been created with QtDesigner 3.3.
When I open this file I've the following message:
Please use uic3 -convert to convert to Qt4
Unfortunately, I don't see the uic3 tool in the bin folder of my install.
Does anybody know how can I can convert this file to QtDesigner 4?
Additional quastion: Where to download PyQy3 binaries for Windows?
Thanks in advance
A:
Qt3 and Qt4 aren't fully compatible so you may need to make some manual tweaks after uic3 converts.
That said, the uic3 tool was installed on my system when I installed the Qt SDK, in C:\Qt\2010.01\qt\bin
Qt SDK: http://qt.nokia.com/downloads
A:
Try finding pyuic3 or rather pyuic4. Since you are using PyQt all your qt tools have py in front (like pyrcc4 or pyuicc4).
I am not sure, that there are pyqt3 binaries for windows. Are you sure that Phil Thompson did PyQt3 also for windows at the time? If so, they would be on riverbank site, I guess, but I can't find them there. Tried compiling the source yourself?
|
How to open a Pyqt 3.3 ui file with QtDesigner 4?
|
I've a PyQt 4 installed (I can't find PyQt 3 for Windows) and I would like to open a QtDesigner ui file which has been created with QtDesigner 3.3.
When I open this file I've the following message:
Please use uic3 -convert to convert to Qt4
Unfortunately, I don't see the uic3 tool in the bin folder of my install.
Does anybody know how can I can convert this file to QtDesigner 4?
Additional quastion: Where to download PyQy3 binaries for Windows?
Thanks in advance
|
[
"Qt3 and Qt4 aren't fully compatible so you may need to make some manual tweaks after uic3 converts.\nThat said, the uic3 tool was installed on my system when I installed the Qt SDK, in C:\\Qt\\2010.01\\qt\\bin\nQt SDK: http://qt.nokia.com/downloads\n",
"Try finding pyuic3 or rather pyuic4. Since you are using PyQt all your qt tools have py in front (like pyrcc4 or pyuicc4).\nI am not sure, that there are pyqt3 binaries for windows. Are you sure that Phil Thompson did PyQt3 also for windows at the time? If so, they would be on riverbank site, I guess, but I can't find them there. Tried compiling the source yourself?\n"
] |
[
2,
1
] |
[] |
[] |
[
"pyqt",
"python",
"qt",
"qt_designer"
] |
stackoverflow_0002294956_pyqt_python_qt_qt_designer.txt
|
Q:
Generating recurring dates using python?
How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).
A:
import dateutil.rrule as dr
import dateutil.parser as dp
import dateutil.relativedelta as drel
start=dp.parse("19/02/2010") # Third Friday in Feb 2010
This generates the third Friday of every month
rr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)
This prints every third Friday:
print map(str,rr)
# ['2010-02-19 00:00:00', '2010-03-19 00:00:00', '2010-04-16 00:00:00', '2010-05-21 00:00:00', '2010-06-18 00:00:00', '2010-07-16 00:00:00', '2010-08-20 00:00:00', '2010-09-17 00:00:00', '2010-10-15 00:00:00', '2010-11-19 00:00:00']
rr is an iterable, so you can use slicing notation to pick out every other item. This prints the third Friday of every other month:
print map(str,rr[::2])
# ['2010-02-19 00:00:00', '2010-04-16 00:00:00', '2010-06-18 00:00:00', '2010-08-20 00:00:00', '2010-10-15 00:00:00']
Above, I used str to prettify the output a little bit. For more flexible string formatting of dates, use strftime: See http://au2.php.net/strftime or the man page for strftime for all the options.
print [d.strftime('%d/%m/%Y') for d in rr[::2]]
# ['19/02/2010', '16/04/2010', '18/06/2010', '20/08/2010', '15/10/2010']
A:
You can give dateutil a try - especially its relativedelta and rrule fetures.
A:
you may try to write this yourself. you will first need an iterator which generates dates separated by a given interval:
import datetime
def dateiter(start, resolution):
date = start
while True:
yield date
date += resolution
now, you can generate dates and filter them:
# generate a list of every tuesday of february
# this iterates over every day from now, and filtered according to the rules
# warning: infinite generator below, there is nothing to end the iteration
tuesdays_of_february = (date for date in dateiter(datetime.datetime.now(), datetime.timedelta(days=1)) if date.weekday() == 4 and date.month == 2)
you can call the iterator yourself until you have enough dates:
>>> next(tuesdays_of_february)
datetime.datetime(2010, 2, 19, 14, 25, 46, 171000)
now, you need to limit the results:
>>> from itertools import *
>>>
>>> # get the five next valid dates:
>>> list(islice(tuesdays_of_february),5)
[datetime.datetime(2010, 2,26, 14, 25, 46, 171000), datetime.datetime(2011, 2, 4
, 14, 25, 46, 171000), datetime.datetime(2011, 2, 11, 14, 25, 46, 171000), datet
ime.datetime(2011, 2, 18, 1 4, 25, 46, 171000), datetime.datetime(2011, 2, 25
, 14, 25, 46, 171000)]
>>>
>>> # or until a condition is met:
>>> list(takewhile( lambda date: date.year < 2014, tuesdays_of_february ))
[datetime.datetime(2012, 2, 3, 14, 25, 46, 171000), datetime.datetime(2012, 2, 1
0, 14, 25, 46, 171000), datetime.datetime(2012, 2, 17, 14, 25, 46, 171000), date
time.datetime(2012, 2, 24, 14, 25, 46, 171000), datetime.datetime(2013, 2, 1, 14
, 25, 46, 171000), datetime.datetime(2013, 2, 8, 14, 25, 46, 171000), datetime.d
atetime(2013, 2, 15, 14, 25, 46, 171000), datetime.datetime(2013, 2, 22, 14, 25,
46, 171000)]
don't forget to have a look at the documentation for the datetime module.
|
Generating recurring dates using python?
|
How can I generate recurring dates using Python? For example I want to generate recurring date for "Third Friday of every second month". I want to generate recurring dates for daily, weekly, monthly, yearly (i.e., same as the recurrence function in Outlook Express).
|
[
"import dateutil.rrule as dr\nimport dateutil.parser as dp\nimport dateutil.relativedelta as drel\n\nstart=dp.parse(\"19/02/2010\") # Third Friday in Feb 2010\n\nThis generates the third Friday of every month\nrr = dr.rrule(dr.MONTHLY,byweekday=drel.FR(3),dtstart=start, count=10)\n\nThis prints every third Friday:\nprint map(str,rr)\n# ['2010-02-19 00:00:00', '2010-03-19 00:00:00', '2010-04-16 00:00:00', '2010-05-21 00:00:00', '2010-06-18 00:00:00', '2010-07-16 00:00:00', '2010-08-20 00:00:00', '2010-09-17 00:00:00', '2010-10-15 00:00:00', '2010-11-19 00:00:00']\n\nrr is an iterable, so you can use slicing notation to pick out every other item. This prints the third Friday of every other month:\nprint map(str,rr[::2])\n# ['2010-02-19 00:00:00', '2010-04-16 00:00:00', '2010-06-18 00:00:00', '2010-08-20 00:00:00', '2010-10-15 00:00:00']\n\nAbove, I used str to prettify the output a little bit. For more flexible string formatting of dates, use strftime: See http://au2.php.net/strftime or the man page for strftime for all the options.\nprint [d.strftime('%d/%m/%Y') for d in rr[::2]]\n# ['19/02/2010', '16/04/2010', '18/06/2010', '20/08/2010', '15/10/2010']\n\n",
"You can give dateutil a try - especially its relativedelta and rrule fetures.\n",
"you may try to write this yourself. you will first need an iterator which generates dates separated by a given interval: \nimport datetime\n\ndef dateiter(start, resolution):\n date = start\n while True:\n yield date\n date += resolution\n\nnow, you can generate dates and filter them:\n# generate a list of every tuesday of february\n# this iterates over every day from now, and filtered according to the rules\n# warning: infinite generator below, there is nothing to end the iteration\ntuesdays_of_february = (date for date in dateiter(datetime.datetime.now(), datetime.timedelta(days=1)) if date.weekday() == 4 and date.month == 2)\n\nyou can call the iterator yourself until you have enough dates:\n>>> next(tuesdays_of_february)\ndatetime.datetime(2010, 2, 19, 14, 25, 46, 171000)\n\nnow, you need to limit the results:\n>>> from itertools import *\n>>> \n>>> # get the five next valid dates:\n>>> list(islice(tuesdays_of_february),5)\n[datetime.datetime(2010, 2,26, 14, 25, 46, 171000), datetime.datetime(2011, 2, 4\n, 14, 25, 46, 171000), datetime.datetime(2011, 2, 11, 14, 25, 46, 171000), datet\nime.datetime(2011, 2, 18, 1 4, 25, 46, 171000), datetime.datetime(2011, 2, 25\n, 14, 25, 46, 171000)]\n>>> \n>>> # or until a condition is met:\n>>> list(takewhile( lambda date: date.year < 2014, tuesdays_of_february ))\n[datetime.datetime(2012, 2, 3, 14, 25, 46, 171000), datetime.datetime(2012, 2, 1\n0, 14, 25, 46, 171000), datetime.datetime(2012, 2, 17, 14, 25, 46, 171000), date\ntime.datetime(2012, 2, 24, 14, 25, 46, 171000), datetime.datetime(2013, 2, 1, 14\n, 25, 46, 171000), datetime.datetime(2013, 2, 8, 14, 25, 46, 171000), datetime.d\natetime(2013, 2, 15, 14, 25, 46, 171000), datetime.datetime(2013, 2, 22, 14, 25,\n 46, 171000)]\n\ndon't forget to have a look at the documentation for the datetime module.\n"
] |
[
30,
0,
0
] |
[] |
[] |
[
"date",
"python"
] |
stackoverflow_0002295765_date_python.txt
|
Q:
Change tab-label on gtk.noteBook
I have a gtk.Notebook with some tabs on it. How can i change label on current tab when button clicked?
I make:
self.set_tab_label(self.scrolled_window,label)
But label change on last tab, but not in current :(
Thank you.
A:
I found the solution:
self.set_tab_label_text(self.get_nth_page(self.get_current_page()),"LABEL_TEXT")
|
Change tab-label on gtk.noteBook
|
I have a gtk.Notebook with some tabs on it. How can i change label on current tab when button clicked?
I make:
self.set_tab_label(self.scrolled_window,label)
But label change on last tab, but not in current :(
Thank you.
|
[
"I found the solution:\nself.set_tab_label_text(self.get_nth_page(self.get_current_page()),\"LABEL_TEXT\")\n\n"
] |
[
0
] |
[] |
[] |
[
"gtk",
"pygtk",
"python"
] |
stackoverflow_0002296722_gtk_pygtk_python.txt
|
Q:
Python Regex Help (httplib2 cookies)
Having the same problem as the poster of this question:
httplib2, how to set more than one cookie?
The cookie looks like this..
PHPSESSID=8527b5532b6018aec4159d81f69765bd; path=/; expires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578; expires=Mon, 22-Feb-2010 13:37:51 GMT, password=123456; expires=Mon, 22-Feb-2010 13:37:51 GMT, sid=8527b5532b6018aec4159d81f69765bd
Note how it uses commas as well as semi-colons to separate cookies, but commas are also used in the cookie itself.
This is too complicated for me to write a regex to separate them properly, it would be very much appreciated if anyone wants to give it a shot!
A:
Have you tried cookielib / http.cookiejar?
If you interpret the cookie as this
PHPSESSID=8527b5532b6018aec4159d81f69765bd;
path=/;
expires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578;
expires=Mon, 22-Feb-2010 13:37:51 GMT, password=123456;
expires=Mon, 22-Feb-2010 13:37:51 GMT, sid=8527b5532b6018aec4159d81f69765bd
Then only the semicolon is the true separator, and the comma separator is only due to an expiration date prepending it.
If you are not interested in the expiration date, then you can use 1 regex to filter out the expiration date e.g.
s/expires=[^,]+,[^,]+, //g
then separate the whole string by ;, and parse them as key=value pairs.
A:
Note how it uses commas as well as semi-colons to separate cookies, but commas are also used in the cookie itself.
As quoted, the ambiguous commas make the string unparseable with regex or any other tool. Where is that string coming from?
As a Set-Cookie: header value it would simply be completely invalid, and wouldn't work in any browser. Browsers would set PHPSESSID as a session cookie (since the expires date format is invalid with the extra comma), and ignore the rest. Multiple cookies have to be set with multiple Set-Cookie headers, not combined into one.
Edit: OK, what seems to be happening is httplib2 is handling the HTTP response data using the stdlib email package to parse the headers. In e-mail, the RFC822 family of standards require that multiple headers with the same name (like, eg. To: addresses) are equivalent to a single header with the values joined by commas.
However, HTTP responses are explicitly not an RFC822-family standard; it is totally inappropriate to handle them this way. It would appear that by using email to parse HTTP responses, httplib2 has made itself unable to handle any multiply-used header correctly, and the Set-Cookie header is very often used like that. For this reason I consider httplib2 fundamentally broken and would advise not using it.
|
Python Regex Help (httplib2 cookies)
|
Having the same problem as the poster of this question:
httplib2, how to set more than one cookie?
The cookie looks like this..
PHPSESSID=8527b5532b6018aec4159d81f69765bd; path=/; expires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578; expires=Mon, 22-Feb-2010 13:37:51 GMT, password=123456; expires=Mon, 22-Feb-2010 13:37:51 GMT, sid=8527b5532b6018aec4159d81f69765bd
Note how it uses commas as well as semi-colons to separate cookies, but commas are also used in the cookie itself.
This is too complicated for me to write a regex to separate them properly, it would be very much appreciated if anyone wants to give it a shot!
|
[
"Have you tried cookielib / http.cookiejar?\n\nIf you interpret the cookie as this\nPHPSESSID=8527b5532b6018aec4159d81f69765bd;\npath=/;\nexpires=Fri, 19-Feb-2010 13:52:51 GMT, id=1578;\nexpires=Mon, 22-Feb-2010 13:37:51 GMT, password=123456; \nexpires=Mon, 22-Feb-2010 13:37:51 GMT, sid=8527b5532b6018aec4159d81f69765bd\n\nThen only the semicolon is the true separator, and the comma separator is only due to an expiration date prepending it. \nIf you are not interested in the expiration date, then you can use 1 regex to filter out the expiration date e.g.\ns/expires=[^,]+,[^,]+, //g\n\nthen separate the whole string by ;, and parse them as key=value pairs.\n",
"\nNote how it uses commas as well as semi-colons to separate cookies, but commas are also used in the cookie itself.\n\nAs quoted, the ambiguous commas make the string unparseable with regex or any other tool. Where is that string coming from?\nAs a Set-Cookie: header value it would simply be completely invalid, and wouldn't work in any browser. Browsers would set PHPSESSID as a session cookie (since the expires date format is invalid with the extra comma), and ignore the rest. Multiple cookies have to be set with multiple Set-Cookie headers, not combined into one.\nEdit: OK, what seems to be happening is httplib2 is handling the HTTP response data using the stdlib email package to parse the headers. In e-mail, the RFC822 family of standards require that multiple headers with the same name (like, eg. To: addresses) are equivalent to a single header with the values joined by commas.\nHowever, HTTP responses are explicitly not an RFC822-family standard; it is totally inappropriate to handle them this way. It would appear that by using email to parse HTTP responses, httplib2 has made itself unable to handle any multiply-used header correctly, and the Set-Cookie header is very often used like that. For this reason I consider httplib2 fundamentally broken and would advise not using it.\n"
] |
[
1,
1
] |
[] |
[] |
[
"cookies",
"httplib2",
"python",
"regex"
] |
stackoverflow_0002296654_cookies_httplib2_python_regex.txt
|
Q:
How to see possible combinations of a given number in python
in Python I wanting see all the possible combination's of a number, but limiting to 0's and 1's...
So for example the result of some loop would be:
0000
0001
0011
0111
1111
1000
and so on.
What python algorithm would best suite this?
A:
Example is in the itertools docs:
>>> import itertools
>>> for i in itertools.product(range(2), repeat=4):
print(i)
A:
def f(n):
if n==1:
return ['0', '1']
tmp = f(n-1)
return ['0'+v for v in tmp] + ['1'+v for v in tmp]
>>> f(4)
['0000',
'0001',
'0010',
'0011',
'0100',
'0101',
'0110',
'0111',
'1000',
'1001',
'1010',
'1011',
'1100',
'1101',
'1110',
'1111']
A:
You're looking for k-combinations. Check this out.
The function you want to look at is xcombinations:
def xcombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xcombinations(items[:i]+items[i+1:],n-1):
yield [items[i]]+cc
A:
See the product generator.
This module implements a number of iterator building blocks inspired
by constructs from APL, Haskell, and SML. Each has been recast in a
form suitable for Python.
The module standardizes a core set of fast, memory efficient tools
that are useful by themselves or in combination. Together, they form
an “iterator algebra” making it possible to construct specialized
tools succinctly and efficiently in pure Python
.
A:
def print_all_combinations(max_value):
width = len('{0:0b}'.format(max_value))
format_string = '{0:0%db}' % width
for i in xrange(max_value):
print format_string.format(i)
|
How to see possible combinations of a given number in python
|
in Python I wanting see all the possible combination's of a number, but limiting to 0's and 1's...
So for example the result of some loop would be:
0000
0001
0011
0111
1111
1000
and so on.
What python algorithm would best suite this?
|
[
"Example is in the itertools docs:\n>>> import itertools\n>>> for i in itertools.product(range(2), repeat=4):\n print(i)\n\n",
"def f(n):\n if n==1:\n return ['0', '1']\n tmp = f(n-1)\n return ['0'+v for v in tmp] + ['1'+v for v in tmp]\n\n>>> f(4)\n['0000',\n'0001',\n'0010',\n'0011',\n'0100',\n'0101',\n'0110',\n'0111',\n'1000',\n'1001',\n'1010',\n'1011',\n'1100',\n'1101',\n'1110',\n'1111']\n\n",
"You're looking for k-combinations. Check this out.\nThe function you want to look at is xcombinations:\ndef xcombinations(items, n):\n if n==0: yield []\n else:\n for i in xrange(len(items)):\n for cc in xcombinations(items[:i]+items[i+1:],n-1):\n yield [items[i]]+cc\n\n",
"See the product generator.\n\nThis module implements a number of iterator building blocks inspired\n by constructs from APL, Haskell, and SML. Each has been recast in a\n form suitable for Python.\nThe module standardizes a core set of fast, memory efficient tools\n that are useful by themselves or in combination. Together, they form\n an “iterator algebra” making it possible to construct specialized\n tools succinctly and efficiently in pure Python\n\n.\n",
"def print_all_combinations(max_value):\n width = len('{0:0b}'.format(max_value))\n format_string = '{0:0%db}' % width\n for i in xrange(max_value):\n print format_string.format(i)\n"
] |
[
7,
1,
1,
0,
0
] |
[] |
[] |
[
"algorithm",
"binary",
"python"
] |
stackoverflow_0002296505_algorithm_binary_python.txt
|
Q:
Replace a whole line in a file
I have a .txt file containing data like this:
0,Rent1,Expense,16/02/2010,1,4000,4000
0,Car Loan1,Expense,16/02/2010,2,4500,9000
0,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,4000,8000
Now i want to replace the line 4 with the new items like:
0,Loan,Expense,19/02/2010,2,5000,10000
I use the following code:
newline='0,Loan,Expense,19/02/2010,2,5000,10000'
lnum=1
for line in fileinput.FileInput("sample.txt",inplace=1):
if lnum=='4':
result = newline
lnum=lnum+1
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
But it shows the in file like:
0,Rent1,Expense,16/02/2010,1,4000,4000
0,Car Loan1,Expense,16/02/2010,2,4500,9000
0,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Loan,Expense,19/02/2010,2,5000,100000,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,4000,8000
How can I solve this?
A:
Put a new line
newline='0,Loan,Expense,19/02/2010,2,5000,10000'
lnum=1
for line in fileinput.FileInput("sample.txt",inplace=1):
if lnum==4:
result = newline+"\n"
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
Or you can just declare newline variable as
newline="0,Loan,Expense,19/02/2010,2,5000,10000\n"
A:
Use enumerate: less code less error posibilities
newline = '0,Loan,Expense,19/02/2010,2,5000,10000\n'
for lnum, line in enumerate(fileinput.FileInput("sample.txt",inplace=1)):
if lnum == 4:
line = newline
sys.stdout.write(line)
A:
sys.stdout.write() does not add a newline. Either append a \n, use print after, or use print's file syntax:
print >>sys.stdout, result
... Or since sys.stdout is the default:
print result
A:
Replace:
result = newline #you lose the newline here
with:
result = newline + '\n' #or '\r\n' depending on your newline format.
|
Replace a whole line in a file
|
I have a .txt file containing data like this:
0,Rent1,Expense,16/02/2010,1,4000,4000
0,Car Loan1,Expense,16/02/2010,2,4500,9000
0,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Rent2,Expense,16/02/2010,1,4000,4000
0,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,4000,8000
Now i want to replace the line 4 with the new items like:
0,Loan,Expense,19/02/2010,2,5000,10000
I use the following code:
newline='0,Loan,Expense,19/02/2010,2,5000,10000'
lnum=1
for line in fileinput.FileInput("sample.txt",inplace=1):
if lnum=='4':
result = newline
lnum=lnum+1
else:
result=line
lnum=lnum+1
sys.stdout.write(result)
But it shows the in file like:
0,Rent1,Expense,16/02/2010,1,4000,4000
0,Car Loan1,Expense,16/02/2010,2,4500,9000
0,Flat Loan1,Expense,16/02/2010,2,4000,8000
0,Loan,Expense,19/02/2010,2,5000,100000,Car Loan2,Expense,16/02/2010,2,4500,9000
0,Flat Loan2,Expense,16/02/2010,2,4000,8000
How can I solve this?
|
[
"Put a new line \nnewline='0,Loan,Expense,19/02/2010,2,5000,10000'\nlnum=1\nfor line in fileinput.FileInput(\"sample.txt\",inplace=1):\n if lnum==4:\n result = newline+\"\\n\"\n else:\n result=line\n lnum=lnum+1 \n sys.stdout.write(result)\n\nOr you can just declare newline variable as \nnewline=\"0,Loan,Expense,19/02/2010,2,5000,10000\\n\"\n\n",
"Use enumerate: less code less error posibilities\nnewline = '0,Loan,Expense,19/02/2010,2,5000,10000\\n'\nfor lnum, line in enumerate(fileinput.FileInput(\"sample.txt\",inplace=1)):\n if lnum == 4:\n line = newline\nsys.stdout.write(line)\n\n",
"sys.stdout.write() does not add a newline. Either append a \\n, use print after, or use print's file syntax:\nprint >>sys.stdout, result\n\n... Or since sys.stdout is the default:\nprint result\n\n",
"Replace:\nresult = newline #you lose the newline here\n\nwith:\nresult = newline + '\\n' #or '\\r\\n' depending on your newline format.\n\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"file",
"python",
"replace"
] |
stackoverflow_0002294848_file_python_replace.txt
|
Q:
how to encode/decode escape sequence characters in python
how to encode/decode escape sequence character '\x13' in python into a character that is valid in a RSS or XML.
use case is, I am getting data from arbitrary sources and making a RSS feed for that data. The data source sometimes have escape sequence character which is breaking my RSS feed.
So how can I sanitize the input data with escape sequence character.
A:
\x13 (ASCII 19, ‘DC3’) can't be escaped; it is invalid in XML 1.0, period. You can include one, encoded as  or  in XML 1.1, but then you have to include the <?xml version="1.1"?> declaration and many tools won't like it.
I've no idea why that character would be included in your data, but the way forward is probably to completely remove control codes. For example:
re.sub('[\x00-\x08\x0B-\x1F]', '', s)
For some kinds of escape sequence (eg. ANSI colour codes) you might get stray (non-control) characters still in there, in which case you'd probably want a custom parser for that particular format.
|
how to encode/decode escape sequence characters in python
|
how to encode/decode escape sequence character '\x13' in python into a character that is valid in a RSS or XML.
use case is, I am getting data from arbitrary sources and making a RSS feed for that data. The data source sometimes have escape sequence character which is breaking my RSS feed.
So how can I sanitize the input data with escape sequence character.
|
[
"\\x13 (ASCII 19, ‘DC3’) can't be escaped; it is invalid in XML 1.0, period. You can include one, encoded as  or  in XML 1.1, but then you have to include the <?xml version=\"1.1\"?> declaration and many tools won't like it.\nI've no idea why that character would be included in your data, but the way forward is probably to completely remove control codes. For example:\nre.sub('[\\x00-\\x08\\x0B-\\x1F]', '', s)\n\nFor some kinds of escape sequence (eg. ANSI colour codes) you might get stray (non-control) characters still in there, in which case you'd probably want a custom parser for that particular format.\n"
] |
[
2
] |
[] |
[] |
[
"character_encoding",
"encoding",
"python"
] |
stackoverflow_0002296525_character_encoding_encoding_python.txt
|
Q:
tkinter: Specifying arguments for a function that's called when you press a button
button1 = tkinter.Button(frame, text="Say hi", command=print)
button2 = tkinter.Button(frame, text="foo", command=print)
button3 = tkinter.Button(frame, text="bar", command=print)
You've probably spotted the hole in my program: print can't specify arguments. This renders the whole thing useless and faulty. Obviously, having something like
command=print("foo")
will call that function when the object is actually instantiated and make command the return value (if any) of that function call. (Not what I want)
So, how can I specify arguments in the above mentioned scenario, and avoid having to define seperate command functions for each of the buttons?
A:
If you have at least python 2.6 (which I'm guessing you are since you use print in a function position) you can use functools.partial. It takes a function and any arguments to supply and returns a callable that will call the underlying function and add on any arguments passed to the final call. For example:
>>> from functools import partial
>>> def add(x,y): return x+y
>>> add2 = partial(add,2)
>>> add3 = partial(add,3)
>>> add2(3)
5
>>> add3(5)
8
Your example could be done as
from functools import partial
button1 = tkinter.Button(frame, text="Say hi", command=partial(print,"hi"))
button2 = tkinter.Button(frame, text="foo", command=partial(print,"foo"))
button3 = tkinter.Button(frame, text="bar", command=partial(print,"bar"))
If you don't have 2.6, you can implement partial as:
def partial(fun, *args, **kwargs):
def merge(d1,d2):
r = dict(d1)
r.update(d2)
return r
return lambda *a,**kw: fun(*(args+a),**(merge(kwargs,kw)))
A:
A simple solution is to use lambda, which lets you create anonymous functions.
button1 = tkinter.Button(frame, text="Say hi", command=lambda: print("Say hi")
button2 = tkinter.Button(frame, text="foo", command=lambda: print("foo"))
button3 = tkinter.Button(frame, text="bar", command=lambda: print("bar"))
Another choice is to use functools.partial, which is explained a bit in this answer: https://stackoverflow.com/a/2297423/7432
|
tkinter: Specifying arguments for a function that's called when you press a button
|
button1 = tkinter.Button(frame, text="Say hi", command=print)
button2 = tkinter.Button(frame, text="foo", command=print)
button3 = tkinter.Button(frame, text="bar", command=print)
You've probably spotted the hole in my program: print can't specify arguments. This renders the whole thing useless and faulty. Obviously, having something like
command=print("foo")
will call that function when the object is actually instantiated and make command the return value (if any) of that function call. (Not what I want)
So, how can I specify arguments in the above mentioned scenario, and avoid having to define seperate command functions for each of the buttons?
|
[
"If you have at least python 2.6 (which I'm guessing you are since you use print in a function position) you can use functools.partial. It takes a function and any arguments to supply and returns a callable that will call the underlying function and add on any arguments passed to the final call. For example:\n>>> from functools import partial\n>>> def add(x,y): return x+y\n>>> add2 = partial(add,2)\n>>> add3 = partial(add,3)\n>>> add2(3)\n5\n>>> add3(5)\n8\n\nYour example could be done as\nfrom functools import partial\nbutton1 = tkinter.Button(frame, text=\"Say hi\", command=partial(print,\"hi\"))\nbutton2 = tkinter.Button(frame, text=\"foo\", command=partial(print,\"foo\"))\nbutton3 = tkinter.Button(frame, text=\"bar\", command=partial(print,\"bar\"))\n\nIf you don't have 2.6, you can implement partial as:\ndef partial(fun, *args, **kwargs):\n def merge(d1,d2):\n r = dict(d1)\n r.update(d2)\n return r\n return lambda *a,**kw: fun(*(args+a),**(merge(kwargs,kw)))\n\n",
"A simple solution is to use lambda, which lets you create anonymous functions.\nbutton1 = tkinter.Button(frame, text=\"Say hi\", command=lambda: print(\"Say hi\")\nbutton2 = tkinter.Button(frame, text=\"foo\", command=lambda: print(\"foo\"))\nbutton3 = tkinter.Button(frame, text=\"bar\", command=lambda: print(\"bar\"))\n\nAnother choice is to use functools.partial, which is explained a bit in this answer: https://stackoverflow.com/a/2297423/7432\n"
] |
[
7,
2
] |
[] |
[] |
[
"arguments",
"python",
"tkinter"
] |
stackoverflow_0002297336_arguments_python_tkinter.txt
|
Q:
How to switch to a python subprocess created by IPython (on OS X)?
When I use IPython along with the -wthread option, it spawns a python subprocess, which appears as a Mac OS X application.
My problem is that when I send commands to that application (for example plotting with matplotlib), the window is updated behind all my other windows. I would like to be able to call a python command to switch this python window to the front (I do that manually with ⌘-tab, but I have to find the python application first, and there might be several ones).
Is there a python script to detect which application IPython has spawned, and how to then automatically switch to it in OS X?
(I'm stating the problem in OS X, but the issue should be similar on other systems).
Edit: let me break this down in two problems:
how to know which Mac OS X application python is running in? (probably possible with some IPython witchery)
how to tell Mac OS X to put the focus on that application? (maybe using applescript)
A:
Could be either:
Making a new python script that tracks grandchild processes of another script might be tricky. The IPython documentation has an example to monitor spawned processes by pid; JobControl. JobControl only kills the processes but I imagine adding a command to change window focus would be fairly easy.
From what I've read, the Tk gui does not properly set window focus on macs. If your 'matplotlib' or otherwise uses the Tk gui, this may be the problem. -source-
I am not very familiar with OS X, so either run with those, clarify your situation or let me know if I'm too far off.
A:
Here is my full solution, with an IPython magic function.
Install appscript (see this question about switching apps programmatically in OS X), and put the following code in a script called activate.py in your ~/.ipython folder.
import appscript
import sys
appscript.app(pid=int(sys.argv[1])).activate()
Now, edit your ~/.ipython/ipy_user_conf.py configuration file and define the magic function:
def wxactivate(self, arg):
import wx
pid = wx.GetProcessId()
ip = self.api
import os
here = os.path.dirname(__file__)
import subprocess
subprocess.Popen([os.path.join(here, 'activate.py'), str(pid)])
Now you just have to register this magic IPython function by putting the following somewhere in that same configuration file:
ip.expose_magic('wxactivate', wxactivate)
Now, after you run IPython -wthread, you can call %wxactivate and you will switch to the corresponding Python application!
(note that the reason why one has to run the call to appscript's activate() in another process in not clear to me; it may have to do with some threading problem... any explanation would be appreciatated)
|
How to switch to a python subprocess created by IPython (on OS X)?
|
When I use IPython along with the -wthread option, it spawns a python subprocess, which appears as a Mac OS X application.
My problem is that when I send commands to that application (for example plotting with matplotlib), the window is updated behind all my other windows. I would like to be able to call a python command to switch this python window to the front (I do that manually with ⌘-tab, but I have to find the python application first, and there might be several ones).
Is there a python script to detect which application IPython has spawned, and how to then automatically switch to it in OS X?
(I'm stating the problem in OS X, but the issue should be similar on other systems).
Edit: let me break this down in two problems:
how to know which Mac OS X application python is running in? (probably possible with some IPython witchery)
how to tell Mac OS X to put the focus on that application? (maybe using applescript)
|
[
"Could be either:\n\nMaking a new python script that tracks grandchild processes of another script might be tricky. The IPython documentation has an example to monitor spawned processes by pid; JobControl. JobControl only kills the processes but I imagine adding a command to change window focus would be fairly easy.\n\nFrom what I've read, the Tk gui does not properly set window focus on macs. If your 'matplotlib' or otherwise uses the Tk gui, this may be the problem. -source-\n\n\nI am not very familiar with OS X, so either run with those, clarify your situation or let me know if I'm too far off.\n",
"Here is my full solution, with an IPython magic function.\nInstall appscript (see this question about switching apps programmatically in OS X), and put the following code in a script called activate.py in your ~/.ipython folder.\nimport appscript\nimport sys\nappscript.app(pid=int(sys.argv[1])).activate()\n\nNow, edit your ~/.ipython/ipy_user_conf.py configuration file and define the magic function:\ndef wxactivate(self, arg):\n import wx\n pid = wx.GetProcessId()\n ip = self.api\n import os\n here = os.path.dirname(__file__)\n import subprocess\n subprocess.Popen([os.path.join(here, 'activate.py'), str(pid)])\n\nNow you just have to register this magic IPython function by putting the following somewhere in that same configuration file:\nip.expose_magic('wxactivate', wxactivate)\n\nNow, after you run IPython -wthread, you can call %wxactivate and you will switch to the corresponding Python application!\n(note that the reason why one has to run the call to appscript's activate() in another process in not clear to me; it may have to do with some threading problem... any explanation would be appreciatated)\n"
] |
[
1,
1
] |
[] |
[] |
[
"ipython",
"macos",
"python",
"wxpython"
] |
stackoverflow_0002260614_ipython_macos_python_wxpython.txt
|
Q:
Assignment into Python 3.x Buffers with itemsize > 1
I am trying to expose a buffer of image pixel information (32 bit RGBA) through the Python 3.x buffer interface. After quite a bit of playing around, I was able to get this working like so:
int Image_get_buffer(PyObject* self, Py_buffer* view, int flags)
{
int img_len;
void* img_bytes;
// Do my image fetch magic
get_image_pixel_data(self, &img_bytes, &img_len);
// Let python fill my buffer
PyBuffer_FillInfo(view, self, img_bytes, img_len, 0, flags);
}
And in python I can play with it like so:
mv = memoryview(image)
print(mv[0]) # prints b'\x00'
mv[0] = b'\xFF' # set the first pixels red component to full
mx[0:4] = b'\xFF\xFF\xFF\xFF' # set the first pixel to white
And that works splendidly. However, it would be great if I could work with the full pixel value (int, 4 byte) instead of individual bytes, so I modified the buffer fetch like so:
int Image_get_buffer(PyObject* self, Py_buffer* view, int flags)
{
int img_len;
void* img_bytes;
// Do my image fetch magic
get_image_pixel_data(self, &img_bytes, &img_len);
// Fill my buffer manually (derived from the PyBuffer_FillInfo source)
Py_INCREF(self);
view->readonly = 0;
view->obj = self;
view->buf = img_bytes;
view->itemsize = 4;
view->ndim = 1;
view->len = img_len;
view->suboffsets = NULL;
view->format = NULL;
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
view->format = "I";
view->shape = NULL;
if ((flags & PyBUF_ND) == PyBUF_ND)
{
Py_ssize_t shape[] = { (int)(img_len/4) };
view->shape = shape;
}
view->strides = NULL;
if((flags & PyBUF_STRIDED) == PyBUF_STRIDED)
{
Py_ssize_t strides[] = { 4 };
view->strides = strides;
}
return 0;
}
This actually returns the data and I can read it correctly, but any attempt to assign a value into it now fails!
mv = memoryview(image)
print(mv[0]) # prints b'\x00\x00\x00\x00'
mv[0] = 0xFFFFFFFF # ERROR (1)
mv[0] = b'\xFF\xFF\xFF\xFF' # ERROR! (2)
mv[0] = mv[0] # ERROR?!? (3)
In case 1 the error informs me that 'int' does not support the buffer interface, which is a shame and a bit confusing (I did specify that the buffer format was "I" after all), but I can deal with that. In case 2 and 3 things get really weird, though: Both cases gime me an TypeError reading mismatching item sizes for "my.Image" and "bytes" (Where my.Image is, obviously, my image type)
This is very confusing to me, since the data I'm passing in is obviously the same size as what I get out of that element. It seems as though buffers simply stop allowing assignment if the itemsize is greater than 1. Of course, the documentation for this interface is really sparse and perusing through the python code doesn't really give any usage examples so I'm fairly stuck. Am I missing some snippit of documentation that states "buffers become essentially useless when itemsize > 1", am I doing something wrong that I can't see, or is this a bug in Python? (Testing against 3.1.1)
Thanks for any insight you can give on this (admittedly advanced) issue!
A:
I found this in the python code (in memoryobject.c in Objects) in the function memory_ass_sub:
/* XXX should we allow assignment of different item sizes
as long as the byte length is the same?
(e.g. assign 2 shorts to a 4-byte slice) */
if (srcview.itemsize != view->itemsize) {
PyErr_Format(PyExc_TypeError,
"mismatching item sizes for \"%.200s\" and \"%.200s\"",
view->obj->ob_type->tp_name, srcview.obj->ob_type->tp_name);
goto _error;
}
that's the source of the latter two errors. It looks like the itemsize for even mv[0] is still not equal to itself.
Update
Here's what I think is going on. When you try to assign something in mv, it calls memory_ass_sub in Objects/memoryobject.c, but that function takes only a PyObject as input. This object is then changed into a buffer inside using the PyObject_GetBuffer function even though in the case of mv[0] it is already a buffer (and the buffer you want!). My guess is that this function takes the object and makes it into a simple buffer of itemsize=1 regardless of whether it is already a buffer or not. That is why you get the mismatching item sizes even for
mv[0] = mv[0]
The problem with the first assignment,
mv[0] = 0xFFFFFFFF
stems (I think) from checking if the int is able to be used as a buffer, which currently it isn't set-up for from what I understand.
In other words, the buffer system isn't currently able to handle item sizes bigger from 1. It doesn't look like it is so far off, but it would take a bit more work on your end. If you do get it working, you should probably submit the changes back to the main Python distribution.
Another Update
The error code from your first try at assigning mv[0] stems from the int failing the PyObject_CheckBuffer when PyObject_CheckBuffer is called on it. Apparently the system only handles copies from bufferable objects. This seems like it should be changed too.
Conclusion
Currently the Python buffer system can't handle items with itemsize > 1 as you guessed. Also, it can't handle assignments to a buffer from non-bufferable objects such as ints.
|
Assignment into Python 3.x Buffers with itemsize > 1
|
I am trying to expose a buffer of image pixel information (32 bit RGBA) through the Python 3.x buffer interface. After quite a bit of playing around, I was able to get this working like so:
int Image_get_buffer(PyObject* self, Py_buffer* view, int flags)
{
int img_len;
void* img_bytes;
// Do my image fetch magic
get_image_pixel_data(self, &img_bytes, &img_len);
// Let python fill my buffer
PyBuffer_FillInfo(view, self, img_bytes, img_len, 0, flags);
}
And in python I can play with it like so:
mv = memoryview(image)
print(mv[0]) # prints b'\x00'
mv[0] = b'\xFF' # set the first pixels red component to full
mx[0:4] = b'\xFF\xFF\xFF\xFF' # set the first pixel to white
And that works splendidly. However, it would be great if I could work with the full pixel value (int, 4 byte) instead of individual bytes, so I modified the buffer fetch like so:
int Image_get_buffer(PyObject* self, Py_buffer* view, int flags)
{
int img_len;
void* img_bytes;
// Do my image fetch magic
get_image_pixel_data(self, &img_bytes, &img_len);
// Fill my buffer manually (derived from the PyBuffer_FillInfo source)
Py_INCREF(self);
view->readonly = 0;
view->obj = self;
view->buf = img_bytes;
view->itemsize = 4;
view->ndim = 1;
view->len = img_len;
view->suboffsets = NULL;
view->format = NULL;
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
view->format = "I";
view->shape = NULL;
if ((flags & PyBUF_ND) == PyBUF_ND)
{
Py_ssize_t shape[] = { (int)(img_len/4) };
view->shape = shape;
}
view->strides = NULL;
if((flags & PyBUF_STRIDED) == PyBUF_STRIDED)
{
Py_ssize_t strides[] = { 4 };
view->strides = strides;
}
return 0;
}
This actually returns the data and I can read it correctly, but any attempt to assign a value into it now fails!
mv = memoryview(image)
print(mv[0]) # prints b'\x00\x00\x00\x00'
mv[0] = 0xFFFFFFFF # ERROR (1)
mv[0] = b'\xFF\xFF\xFF\xFF' # ERROR! (2)
mv[0] = mv[0] # ERROR?!? (3)
In case 1 the error informs me that 'int' does not support the buffer interface, which is a shame and a bit confusing (I did specify that the buffer format was "I" after all), but I can deal with that. In case 2 and 3 things get really weird, though: Both cases gime me an TypeError reading mismatching item sizes for "my.Image" and "bytes" (Where my.Image is, obviously, my image type)
This is very confusing to me, since the data I'm passing in is obviously the same size as what I get out of that element. It seems as though buffers simply stop allowing assignment if the itemsize is greater than 1. Of course, the documentation for this interface is really sparse and perusing through the python code doesn't really give any usage examples so I'm fairly stuck. Am I missing some snippit of documentation that states "buffers become essentially useless when itemsize > 1", am I doing something wrong that I can't see, or is this a bug in Python? (Testing against 3.1.1)
Thanks for any insight you can give on this (admittedly advanced) issue!
|
[
"I found this in the python code (in memoryobject.c in Objects) in the function memory_ass_sub:\n/* XXX should we allow assignment of different item sizes\n as long as the byte length is the same?\n (e.g. assign 2 shorts to a 4-byte slice) */\nif (srcview.itemsize != view->itemsize) {\n PyErr_Format(PyExc_TypeError,\n \"mismatching item sizes for \\\"%.200s\\\" and \\\"%.200s\\\"\", \n view->obj->ob_type->tp_name, srcview.obj->ob_type->tp_name);\n goto _error;\n}\n\nthat's the source of the latter two errors. It looks like the itemsize for even mv[0] is still not equal to itself.\nUpdate\nHere's what I think is going on. When you try to assign something in mv, it calls memory_ass_sub in Objects/memoryobject.c, but that function takes only a PyObject as input. This object is then changed into a buffer inside using the PyObject_GetBuffer function even though in the case of mv[0] it is already a buffer (and the buffer you want!). My guess is that this function takes the object and makes it into a simple buffer of itemsize=1 regardless of whether it is already a buffer or not. That is why you get the mismatching item sizes even for\nmv[0] = mv[0]\n\nThe problem with the first assignment, \nmv[0] = 0xFFFFFFFF\nstems (I think) from checking if the int is able to be used as a buffer, which currently it isn't set-up for from what I understand.\nIn other words, the buffer system isn't currently able to handle item sizes bigger from 1. It doesn't look like it is so far off, but it would take a bit more work on your end. If you do get it working, you should probably submit the changes back to the main Python distribution.\nAnother Update\nThe error code from your first try at assigning mv[0] stems from the int failing the PyObject_CheckBuffer when PyObject_CheckBuffer is called on it. Apparently the system only handles copies from bufferable objects. This seems like it should be changed too.\nConclusion\nCurrently the Python buffer system can't handle items with itemsize > 1 as you guessed. Also, it can't handle assignments to a buffer from non-bufferable objects such as ints.\n"
] |
[
1
] |
[] |
[] |
[
"pep3118",
"pybuffer",
"python",
"python_3.x",
"python_c_api"
] |
stackoverflow_0002297026_pep3118_pybuffer_python_python_3.x_python_c_api.txt
|
Q:
Searching a website
import urllib
import re
import os
search = (raw_input('[!]Search: '))
site = "http://www.exploit-db.com/list.php?description="+search+"&author=&platform=&type=&port=&osvdb=&cve="
print site
source = urllib.urlopen(site).read()
founds = re.findall("href='/exploits/\d+",source)
print "\n[+]Search",len(founds),"Results\n"
if len(founds) >=1:
for found in founds:
found = found.replace("href='","")
print "http://www.exploit-db.com"+found
else:
print "\nCouldnt find anything with your search\n"
When I search the exploit-db.com site I only come up with 25 results, how can I make it go to the other page or go pass 25 results.
A:
Easy to check by just visiting the site and looking at the URLs as you manually page: just put right after the ? in the URL page=1& to look at the second page of results, or page=2& to look at the third page, and so forth.
How is this a Python question? It's a (very elementary!) "screen scraping" question.
A:
Apparently the exploit-db.com site doesn't allow extending the page size. You therefore need to "manually" page through the result list by repeating the urllib.urlopen() to get subsequent pages. The URL is the same as the one initially used, plus the &page=n parameter. Attention this n value appears to be 0-based (i.e. &page=1 will give the second page)
|
Searching a website
|
import urllib
import re
import os
search = (raw_input('[!]Search: '))
site = "http://www.exploit-db.com/list.php?description="+search+"&author=&platform=&type=&port=&osvdb=&cve="
print site
source = urllib.urlopen(site).read()
founds = re.findall("href='/exploits/\d+",source)
print "\n[+]Search",len(founds),"Results\n"
if len(founds) >=1:
for found in founds:
found = found.replace("href='","")
print "http://www.exploit-db.com"+found
else:
print "\nCouldnt find anything with your search\n"
When I search the exploit-db.com site I only come up with 25 results, how can I make it go to the other page or go pass 25 results.
|
[
"Easy to check by just visiting the site and looking at the URLs as you manually page: just put right after the ? in the URL page=1& to look at the second page of results, or page=2& to look at the third page, and so forth.\nHow is this a Python question? It's a (very elementary!) \"screen scraping\" question.\n",
"Apparently the exploit-db.com site doesn't allow extending the page size. You therefore need to \"manually\" page through the result list by repeating the urllib.urlopen() to get subsequent pages. The URL is the same as the one initially used, plus the &page=n parameter. Attention this n value appears to be 0-based (i.e. &page=1 will give the second page)\n"
] |
[
0,
0
] |
[] |
[] |
[
"python",
"urllib"
] |
stackoverflow_0002297787_python_urllib.txt
|
Q:
Production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django?
Seems that Python lacks e-commerce solutions compared to PHP and C#. Any production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django?
EDIT:
http://github.com/johnboxall/django-paypal
http://www.djangosnippets.org/snippets/969/
E-commerce: http://www.satchmoproject.com/
http://code.activestate.com/recipes/456361/
http://code.google.com/p/django-cart/
http://www.chickenwingsw.com/paypal-on-python
A:
You might look into Satchmo's source code. Satchmo is an open source e-commerce app for Django, and I'm pretty sure that it has support for a variety of payment gateways.
Their payment modules appear to work with at least PayPal and Authorize.Net from the list you gave, among others.
|
Production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django?
|
Seems that Python lacks e-commerce solutions compared to PHP and C#. Any production-ready PayPal, 2CO and Authorize.Net libraries for Python/Django?
EDIT:
http://github.com/johnboxall/django-paypal
http://www.djangosnippets.org/snippets/969/
E-commerce: http://www.satchmoproject.com/
http://code.activestate.com/recipes/456361/
http://code.google.com/p/django-cart/
http://www.chickenwingsw.com/paypal-on-python
|
[
"You might look into Satchmo's source code. Satchmo is an open source e-commerce app for Django, and I'm pretty sure that it has support for a variety of payment gateways.\nTheir payment modules appear to work with at least PayPal and Authorize.Net from the list you gave, among others.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"e_commerce",
"frameworks",
"python"
] |
stackoverflow_0002296542_django_e_commerce_frameworks_python.txt
|
Q:
python basic while loop
I have another newbie Python question. I have the following piece of code that I have a feeling is not written as pythonic as it should be:
rowindex = 0
while params.getfirst('myfield'+rowindex):
myid = params.getfirst('myfield'+rowindex)
# do stuff with myid
rowindex+=1
The input to this script is an HTML page that can have any number of input fields named "myfield#" where # starts at 0 and increases sequentially. In Perl, I would do something more like this:
rowindex = 0
while myid = params.getfirst('myfield'+rowindex):
#do stuff with myid
rowindex+=1
But that is not valid syntax in Python. I know what I have will work, but is there a better way? Thank you.
A:
The "unbounded" nature of a simple counter has some appeal. However, it's also an opportunity for someone to attempt a Denial of Service attack by spoofing a form with billions of fields. Simply counting through the fields could stall your web server as you attempt to process those billions of fields.
Since Python converts to long automatically, the usual 2 billion integer overflow doesn't apply. Someone could really punish your site with 10's of billions of fields.
for i in range(1024): # some sensible upper limit, beyond which the input is suspicious
myid= params.getfirst("myfield%d" % i)
if not myid: break
# do stuff with myid
A:
I think I'd make a little generator to fully encapsulate the looping logic:
import itertools
def genit(params):
for rowindex in itertools.count():
theid = params.getfirst('myfield%s' % rowindex)
if not theid: break
yield theid
so that application ("business") logic can be more cleanly seen in the main flow:
for myid in genit(params):
dosomething_with(myid)
especially if dosomething_with is inline. Generators are really "the cat's pajamas" to cleanly separate rich / complex looping logic from application / business logic.
If for some special reason I was keen to keep them merged in this particular case, I still would avoid the low-abstraction rowindex = 0 / while / rowindex += 1 code in favor of for rowindex in itertools.count(): which I think is clearer and sharper as well as more concise. This overall framing also makes it easier to switch between limiting the loop, as in the accepted answer, if and when you decide to do that, and having an unbounded loop, as in the original question -- just change itertools.count() to/from xrange(N).
A:
you can do this. I consider this more "flexible" as I can give any conditions i want, as many as i want, inside the while loop. But then again, some will say its personal taste.
rowindex = 0
while 1:
myid = params.getfirst('myfield'+rowindex)
if not myid: #or check for length of 0 , etc, then break
break
rowindex+=1
|
python basic while loop
|
I have another newbie Python question. I have the following piece of code that I have a feeling is not written as pythonic as it should be:
rowindex = 0
while params.getfirst('myfield'+rowindex):
myid = params.getfirst('myfield'+rowindex)
# do stuff with myid
rowindex+=1
The input to this script is an HTML page that can have any number of input fields named "myfield#" where # starts at 0 and increases sequentially. In Perl, I would do something more like this:
rowindex = 0
while myid = params.getfirst('myfield'+rowindex):
#do stuff with myid
rowindex+=1
But that is not valid syntax in Python. I know what I have will work, but is there a better way? Thank you.
|
[
"The \"unbounded\" nature of a simple counter has some appeal. However, it's also an opportunity for someone to attempt a Denial of Service attack by spoofing a form with billions of fields. Simply counting through the fields could stall your web server as you attempt to process those billions of fields. \nSince Python converts to long automatically, the usual 2 billion integer overflow doesn't apply. Someone could really punish your site with 10's of billions of fields.\nfor i in range(1024): # some sensible upper limit, beyond which the input is suspicious\n myid= params.getfirst(\"myfield%d\" % i)\n if not myid: break\n # do stuff with myid\n\n",
"I think I'd make a little generator to fully encapsulate the looping logic:\nimport itertools\n\ndef genit(params):\n for rowindex in itertools.count():\n theid = params.getfirst('myfield%s' % rowindex)\n if not theid: break\n yield theid\n\nso that application (\"business\") logic can be more cleanly seen in the main flow:\nfor myid in genit(params):\n dosomething_with(myid)\n\nespecially if dosomething_with is inline. Generators are really \"the cat's pajamas\" to cleanly separate rich / complex looping logic from application / business logic.\nIf for some special reason I was keen to keep them merged in this particular case, I still would avoid the low-abstraction rowindex = 0 / while / rowindex += 1 code in favor of for rowindex in itertools.count(): which I think is clearer and sharper as well as more concise. This overall framing also makes it easier to switch between limiting the loop, as in the accepted answer, if and when you decide to do that, and having an unbounded loop, as in the original question -- just change itertools.count() to/from xrange(N).\n",
"you can do this. I consider this more \"flexible\" as I can give any conditions i want, as many as i want, inside the while loop. But then again, some will say its personal taste. \nrowindex = 0\nwhile 1:\n myid = params.getfirst('myfield'+rowindex)\n if not myid: #or check for length of 0 , etc, then break\n break\n rowindex+=1\n\n"
] |
[
5,
2,
1
] |
[
"Try Doing this\nWhile 1:\n\n codehere\n\n"
] |
[
-1
] |
[
"python",
"while_loop"
] |
stackoverflow_0002296803_python_while_loop.txt
|
Q:
Looking for example GUI applications written in Python for the iPhone
I have a little script I wrote in python and it actually works on the iPhone via the terminal. I am looking for code snippets or documentation for the GUI writing for the iPhone -
Actually what I need is to implement an input and some output.
nothing fancy - for now.
I have found this page: http://www.saurik.com/id/5
but as i understand from the article i will need to write it in objective-c which i am not familiar with - do i have to? or can i write in python or just C?
and it is very descriptive, looking for more docs...
Thanks Alot :)
A:
You cannot write an iPhone app in Python that will run on non-jailbroken phones. Apple's SDK license prohibits interpreted code on the iPhone, which definitely excludes Python. Although you can write OS X apps in Python using PyObjC, you still need to understand the Objective-C language both for documentation and for groking the many Cocoa patterns that are closely tied to Objective-C's way of doing things.
Learn Objective-C. For a programer that knows C or C++, it takes only a couple of days to become proficient in Objective-C. If you've never used a language that has pointers before, it may take a little longer. On the flip side, embracing Objective-C's dynamic nature is much easier for developers coming from dynamic languages as opposed to statically typed languages like C/C++/Java/C#.
A:
There is a GUI sample in that link. The whole app is written in Python with ObjC runtime (but no ObjC code involved).
Still, the ObjC "feel" cannot be avoided because UIKit is designed for and uses ObjC. Note that the GUI programmed in Python is extremely slow on the iPhoneOS. Python can be used as testing, but never release an (interpreted) iPhoneOS Python GUI app to public.
|
Looking for example GUI applications written in Python for the iPhone
|
I have a little script I wrote in python and it actually works on the iPhone via the terminal. I am looking for code snippets or documentation for the GUI writing for the iPhone -
Actually what I need is to implement an input and some output.
nothing fancy - for now.
I have found this page: http://www.saurik.com/id/5
but as i understand from the article i will need to write it in objective-c which i am not familiar with - do i have to? or can i write in python or just C?
and it is very descriptive, looking for more docs...
Thanks Alot :)
|
[
"You cannot write an iPhone app in Python that will run on non-jailbroken phones. Apple's SDK license prohibits interpreted code on the iPhone, which definitely excludes Python. Although you can write OS X apps in Python using PyObjC, you still need to understand the Objective-C language both for documentation and for groking the many Cocoa patterns that are closely tied to Objective-C's way of doing things.\nLearn Objective-C. For a programer that knows C or C++, it takes only a couple of days to become proficient in Objective-C. If you've never used a language that has pointers before, it may take a little longer. On the flip side, embracing Objective-C's dynamic nature is much easier for developers coming from dynamic languages as opposed to statically typed languages like C/C++/Java/C#.\n",
"There is a GUI sample in that link. The whole app is written in Python with ObjC runtime (but no ObjC code involved). \nStill, the ObjC \"feel\" cannot be avoided because UIKit is designed for and uses ObjC. Note that the GUI programmed in Python is extremely slow on the iPhoneOS. Python can be used as testing, but never release an (interpreted) iPhoneOS Python GUI app to public.\n"
] |
[
1,
0
] |
[] |
[] |
[
"iphone",
"objective_c",
"python",
"user_interface"
] |
stackoverflow_0002296068_iphone_objective_c_python_user_interface.txt
|
Q:
How to set pythonpath (python2.6) for tkinter on Ubuntu 9.04 (to use nltk)?
I'd like to use the nltk toolkit on my machine which runs Ubuntu 9.04. I installed python 2.6.4 and several additional packages (numpy, scipy, matplotlib and of course nltk). I can import nltk, but calling a few methods gives various error masseges, all contain "please install Tkinter library".
Googling around I discovered from http://wiki.python.org/moin/TkInter that I should set my pythonpath environment variable. However I couldn't find out how to do this after searching for hours.
A:
Sounds like you forgot to install the appropriate TkInter when you installed Python 2.6.4. Install it from the same source.
A:
Tkinter is usually included with the python standard libraries but Ubuntu left it out of the regular python package. You just need to install the python-tk package.
sudo apt-get install python-tk
|
How to set pythonpath (python2.6) for tkinter on Ubuntu 9.04 (to use nltk)?
|
I'd like to use the nltk toolkit on my machine which runs Ubuntu 9.04. I installed python 2.6.4 and several additional packages (numpy, scipy, matplotlib and of course nltk). I can import nltk, but calling a few methods gives various error masseges, all contain "please install Tkinter library".
Googling around I discovered from http://wiki.python.org/moin/TkInter that I should set my pythonpath environment variable. However I couldn't find out how to do this after searching for hours.
|
[
"Sounds like you forgot to install the appropriate TkInter when you installed Python 2.6.4. Install it from the same source.\n",
"Tkinter is usually included with the python standard libraries but Ubuntu left it out of the regular python package. You just need to install the python-tk package.\nsudo apt-get install python-tk\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"nltk",
"python",
"pythonpath",
"tkinter"
] |
stackoverflow_0002290375_nltk_python_pythonpath_tkinter.txt
|
Q:
Updating a de-normalized attribute automatically with an AttributeExtension
I am having some troubles with the AttributeExtension of SQLAlchemy.
Actually I am storing a de-normalized sum attribute in the Partent table, because I need it quite often for sorting purposes. However, I would like the attribute to get updated whenever the value of one of it's children is changed.
Unfortunately, the set() method of the AttributeExtension is never called and so, changes aren't recognized. Using a property-setter which updates also the parent might work, but I would like to know how to use the AttributeExtension of SQLAlchemy (version: 0.6beta2) correctly.
Here is a small (runnable) code snippet which demonstrates the problem:
from sqlalchemy import create_engine, Column, Integer, ForeignKey
from sqlalchemy.orm import relation, scoped_session, sessionmaker, \
AttributeExtension
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine, autoflush=True))
Base = declarative_base()
Base.query = session.query_property()
class ChildrenAttributeExtension(AttributeExtension):
active_history = True
def append(self, state, child, initiator):
parent = state.obj()
parent.sum_of_children += child.value
return child
def remove(self, state, child, initiator):
parent = state.obj()
parent.sum_of_children -= child.value
def set(self, state, child, oldchild, initiator):
print 'set called' # gets never printed
parent = state.obj()
parent.sum_of_children += -oldchild.value + child.value
return child
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)
value = Column(Integer, nullable=False, default=0)
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
sum_of_children = Column(Integer, nullable=False, default=0)
children = relation('Child', backref='parent',
extension=ChildrenAttributeExtension())
Base.metadata.create_all(engine)
# Add a parent
p = Parent()
session.add(p)
session.commit()
p = Parent.query.first()
assert p.sum_of_children == 0
# Add a child
c = Child(parent=p, value=5)
session.add(c)
session.commit()
p = Parent.query.first()
assert p.sum_of_children == 5
# Change a child
c = Child.query.first()
c.value = 3
session.commit() # extension.set() doesn't get called
p = Parent.query.first()
assert p.sum_of_children == 3 # Assertion fails
Thanks for your help!
Christoph
A:
As far as I can see, you are looking for events on child, but change child.value. Something like this should do the trick:
class ValueAttributeExtension(AttributeExtension):
...
class Child(Base):
...
value = ColumnProperty(Column(Integer, nullable=False, default=0),
extension=ValueAttributeExtension())
EDIT-1: full working example below:
from sqlalchemy import create_engine, Column, Integer, ForeignKey
from sqlalchemy.orm import relation, scoped_session, sessionmaker, AttributeExtension, ColumnProperty
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=False)
session = scoped_session(sessionmaker(bind=engine, autoflush=True))
Base = declarative_base()
Base.query = session.query_property()
class ValueAttributeExtension(AttributeExtension):
active_history = True
def append(self, state, child, initiator):
assert False, "should not be called"
def remove(self, state, child, initiator):
assert False, "should not be called"
def set(self, state, value, oldvalue, initiator):
print 'set called', state.obj(), value, oldvalue
child = state.obj()
if not(child.parent is None):
child.parent.sum_of_children += -oldvalue + value
return value
class ChildrenAttributeExtension(AttributeExtension):
active_history = True
def append(self, state, child, initiator):
print 'append called', state.obj(), child
parent = state.obj()
parent.sum_of_children += child.value
return child
def remove(self, state, child, initiator):
print 'remove called', state.obj(), child
parent = state.obj()
parent.sum_of_children -= child.value
def set(self, state, child, oldchild, initiator):
print 'set called', state, child, oldchild
parent = state.obj()
parent.parent.sum_of_children += -oldchild.value + child.value
#parent.sum_of_children += -oldchild.value + child.value
return child
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)
value = ColumnProperty(Column(Integer, nullable=False, default=0),
extension=ValueAttributeExtension())
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
sum_of_children = Column(Integer, nullable=False, default=0)
children = relation('Child', backref='parent',
extension=ChildrenAttributeExtension())
Base.metadata.create_all(engine)
# Add a parent
p = Parent()
session.add(p)
session.commit()
p = Parent.query.first()
assert p.sum_of_children == 0
# Add a child
c = Child(parent=p, value=5)
session.add(c)
session.commit()
p = Parent.query.first()
assert p.sum_of_children == 5
# Change a child
#c = Child.query.first()
c.value = 3 # fixed bug: = instead of ==
session.commit() # extension.set() doesn't get called
p = Parent.query.first()
assert p.sum_of_children == 3 # Assertion is OK
|
Updating a de-normalized attribute automatically with an AttributeExtension
|
I am having some troubles with the AttributeExtension of SQLAlchemy.
Actually I am storing a de-normalized sum attribute in the Partent table, because I need it quite often for sorting purposes. However, I would like the attribute to get updated whenever the value of one of it's children is changed.
Unfortunately, the set() method of the AttributeExtension is never called and so, changes aren't recognized. Using a property-setter which updates also the parent might work, but I would like to know how to use the AttributeExtension of SQLAlchemy (version: 0.6beta2) correctly.
Here is a small (runnable) code snippet which demonstrates the problem:
from sqlalchemy import create_engine, Column, Integer, ForeignKey
from sqlalchemy.orm import relation, scoped_session, sessionmaker, \
AttributeExtension
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
session = scoped_session(sessionmaker(bind=engine, autoflush=True))
Base = declarative_base()
Base.query = session.query_property()
class ChildrenAttributeExtension(AttributeExtension):
active_history = True
def append(self, state, child, initiator):
parent = state.obj()
parent.sum_of_children += child.value
return child
def remove(self, state, child, initiator):
parent = state.obj()
parent.sum_of_children -= child.value
def set(self, state, child, oldchild, initiator):
print 'set called' # gets never printed
parent = state.obj()
parent.sum_of_children += -oldchild.value + child.value
return child
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)
value = Column(Integer, nullable=False, default=0)
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
sum_of_children = Column(Integer, nullable=False, default=0)
children = relation('Child', backref='parent',
extension=ChildrenAttributeExtension())
Base.metadata.create_all(engine)
# Add a parent
p = Parent()
session.add(p)
session.commit()
p = Parent.query.first()
assert p.sum_of_children == 0
# Add a child
c = Child(parent=p, value=5)
session.add(c)
session.commit()
p = Parent.query.first()
assert p.sum_of_children == 5
# Change a child
c = Child.query.first()
c.value = 3
session.commit() # extension.set() doesn't get called
p = Parent.query.first()
assert p.sum_of_children == 3 # Assertion fails
Thanks for your help!
Christoph
|
[
"As far as I can see, you are looking for events on child, but change child.value. Something like this should do the trick:\nclass ValueAttributeExtension(AttributeExtension):\n ...\n\nclass Child(Base):\n ...\n value = ColumnProperty(Column(Integer, nullable=False, default=0), \n extension=ValueAttributeExtension()) \n\nEDIT-1: full working example below:\nfrom sqlalchemy import create_engine, Column, Integer, ForeignKey\nfrom sqlalchemy.orm import relation, scoped_session, sessionmaker, AttributeExtension, ColumnProperty\nfrom sqlalchemy.ext.declarative import declarative_base\n\nengine = create_engine('sqlite:///:memory:', echo=False)\nsession = scoped_session(sessionmaker(bind=engine, autoflush=True))\nBase = declarative_base()\nBase.query = session.query_property()\n\nclass ValueAttributeExtension(AttributeExtension):\n active_history = True\n\n def append(self, state, child, initiator):\n assert False, \"should not be called\"\n\n def remove(self, state, child, initiator):\n assert False, \"should not be called\"\n\n def set(self, state, value, oldvalue, initiator):\n print 'set called', state.obj(), value, oldvalue\n child = state.obj()\n if not(child.parent is None):\n child.parent.sum_of_children += -oldvalue + value\n return value\n\nclass ChildrenAttributeExtension(AttributeExtension):\n active_history = True\n\n def append(self, state, child, initiator):\n print 'append called', state.obj(), child\n parent = state.obj()\n parent.sum_of_children += child.value\n return child\n\n def remove(self, state, child, initiator):\n print 'remove called', state.obj(), child\n parent = state.obj()\n parent.sum_of_children -= child.value\n\n def set(self, state, child, oldchild, initiator):\n print 'set called', state, child, oldchild\n parent = state.obj()\n parent.parent.sum_of_children += -oldchild.value + child.value\n #parent.sum_of_children += -oldchild.value + child.value\n return child\n\nclass Child(Base):\n __tablename__ = 'child'\n id = Column(Integer, primary_key=True)\n parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)\n value = ColumnProperty(Column(Integer, nullable=False, default=0),\n extension=ValueAttributeExtension())\n\nclass Parent(Base):\n __tablename__ = 'parent'\n id = Column(Integer, primary_key=True)\n sum_of_children = Column(Integer, nullable=False, default=0)\n\n children = relation('Child', backref='parent',\n extension=ChildrenAttributeExtension())\n\nBase.metadata.create_all(engine)\n\n# Add a parent\np = Parent()\nsession.add(p)\nsession.commit()\n\np = Parent.query.first()\nassert p.sum_of_children == 0\n\n\n# Add a child\nc = Child(parent=p, value=5)\nsession.add(c)\nsession.commit()\n\np = Parent.query.first()\nassert p.sum_of_children == 5\n\n# Change a child\n#c = Child.query.first()\nc.value = 3 # fixed bug: = instead of ==\nsession.commit() # extension.set() doesn't get called\n\np = Parent.query.first()\nassert p.sum_of_children == 3 # Assertion is OK\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0002296502_python_sqlalchemy.txt
|
Q:
Django(postgresql) + lighttpd. Any issues with threading and python's postgresql driver?
I'd like to deploy my Django app (which uses postgresql as database) on lighttpd using FastCGI.
For postgresql i see that Django has 2 backends available 'postgresql_psycopg2' and 'postgresql'.
My question is that lighttpd being a threaded server are there any issues with any of this backends? Are they thread safe? And which one of them is better/recommended?
My questions comes because i read something (don't remember now where) that postgresql's driver for python isn't thread safe.
LE: After some more reading i just figured it out that the threading issue is present only when running manage.py method=threaded and not when running manage.py method=prefork as this is FastCGI process bound and not webserver bound(i.e: doesn't matter how the webserver is, threaded or process based but only how the fastcgi server is running)
Anyway in this case it seems it doesn't matter if it's threaded or prefosk as how Milen A. Radev answered postgresql_psycopg2 is thread safe.
A:
http://initd.org/psycopg/docs/usage.html#thread-safety
|
Django(postgresql) + lighttpd. Any issues with threading and python's postgresql driver?
|
I'd like to deploy my Django app (which uses postgresql as database) on lighttpd using FastCGI.
For postgresql i see that Django has 2 backends available 'postgresql_psycopg2' and 'postgresql'.
My question is that lighttpd being a threaded server are there any issues with any of this backends? Are they thread safe? And which one of them is better/recommended?
My questions comes because i read something (don't remember now where) that postgresql's driver for python isn't thread safe.
LE: After some more reading i just figured it out that the threading issue is present only when running manage.py method=threaded and not when running manage.py method=prefork as this is FastCGI process bound and not webserver bound(i.e: doesn't matter how the webserver is, threaded or process based but only how the fastcgi server is running)
Anyway in this case it seems it doesn't matter if it's threaded or prefosk as how Milen A. Radev answered postgresql_psycopg2 is thread safe.
|
[
"http://initd.org/psycopg/docs/usage.html#thread-safety\n"
] |
[
2
] |
[] |
[] |
[
"django",
"lighttpd",
"postgresql",
"python",
"thread_safety"
] |
stackoverflow_0002297030_django_lighttpd_postgresql_python_thread_safety.txt
|
Q:
how to have global variables among different modules in Python
I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck.
thanks in advance!
A:
You can access global variables from other modules by importing them explicitly.
In module foo:
joe = 5
In module bar:
from foo import joe
print joe
Note that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.
A:
Python does not support globals shared between several modules: this is a feature. Code that implicitly modifies variables used far away is confusing and unmaintainable. The real solution is to encapsulate all state within a class and pass its instance to anything that has to modify it. This can make code clearer, more maintainable, more testable, more modular, and more expendable.
A:
Scopes beyond the local must be written to via a reference to the scope, or after a global or nonlocal (3.x+) directive.
|
how to have global variables among different modules in Python
|
I investigated that scope of global variables in python is limited to the module. But I need the scope to be global among different modules. Is there such a thing? I played around __builtin__ but no luck.
thanks in advance!
|
[
"You can access global variables from other modules by importing them explicitly.\nIn module foo:\n joe = 5\n\nIn module bar:\n from foo import joe\n print joe\n\nNote that this isn't recommended, though. It's much better to hide access to a module's variables by using functions.\n",
"Python does not support globals shared between several modules: this is a feature. Code that implicitly modifies variables used far away is confusing and unmaintainable. The real solution is to encapsulate all state within a class and pass its instance to anything that has to modify it. This can make code clearer, more maintainable, more testable, more modular, and more expendable.\n",
"Scopes beyond the local must be written to via a reference to the scope, or after a global or nonlocal (3.x+) directive.\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"global_variables",
"python",
"scope"
] |
stackoverflow_0002296550_global_variables_python_scope.txt
|
Q:
Local App Engine datastore is slow once loaded up, any suggestions?
I've loaded up a local datastore with 40,000+ entries. Unfortunately,
recalling any data from it at all is very slow on my fairly new
Macbook Pro. Any suggestions on speeding things up, short of buying a
new piece of hardware?
A:
This question addresses a few alternatives you could try.
For speeding up unit testing, you can set the datastore to stay in memory only, and not flush to disk. This may not help you if you need 40,000 entities to meaningfully test your system of course :)
|
Local App Engine datastore is slow once loaded up, any suggestions?
|
I've loaded up a local datastore with 40,000+ entries. Unfortunately,
recalling any data from it at all is very slow on my fairly new
Macbook Pro. Any suggestions on speeding things up, short of buying a
new piece of hardware?
|
[
"This question addresses a few alternatives you could try.\nFor speeding up unit testing, you can set the datastore to stay in memory only, and not flush to disk. This may not help you if you need 40,000 entities to meaningfully test your system of course :)\n"
] |
[
0
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0002298280_google_app_engine_google_cloud_datastore_python.txt
|
Q:
PyQt4,How to add a batch of widget (QPushButton) at one time and lets them to execute on SLOT
if i want to add 10 QPushButton at one time:
NumCount=20
for i in range(NumCount):
btn=QPushButton("%s %s" %("Button" i+1),self)
btn.clicked.connect(self.btnclick)
def btnclick(self):
# here is my question
# how to define which button clicked?
# how to print btn.text?
as stated in the def(btnclick).
A:
When you are in a slot, you can use sender() method (just call self.sender()) and you will receive a reference to the object, from which signal was emitted. Here is documentation about it.
A:
I'd subclass QPushButton and define my own sender and slot. The QObject.sender() method is tempting, but it gives me the heebie-jeebies.
class MyPushButton(QPushButton):
def __init__(self, text = '', parent = None):
QPushButton.__init__(self, text, parent)
self.clicked.connect(self._handle_click)
my_click = QtCore.pyqtSignal(QObject)
def _handle_click(self):
my_click.emit(self)
def btnclick(btn):
print 'Handle button %s' % btn
for i in xrange(20):
btn = MyPushButton('%s %s' % ('Button', i + 1), self)
btn.my_click.connect(btnclick)
A slightly more Pythonic way of doing this could define the behavior within the class, like so:
class MyPushButton(QPushButton):
def __init__(self, button_number, parent = None):
QPushButton.__init__(self, '%s %s' % ('Button', button_number), parent)
self.button_number = button_number
self.clicked.connect(self._handle_click)
def _handle_click(self):
print 'Handle button %s' % self
for i in xrange(20):
btn = MyPushButton(i + 1, self)
A:
As gruszcsy said, there's self.sender() (in QObject) to get that exact info.
There's also the QSignalMapper class that provides a higher-level mapping from several signal senders to one slot. It helps for the basic cases of many-to-one signal/slot mapping.
Chris B's suggestion about defining a new slot that transmits the sender as a parameter is a bit more complicated, but cleaner in terms of program structure and separation between classes. I tend to use that method when the target slot is in another object. For mapping inside a class's private slot, sender() is both neat and quite appropriate, IMO.
A:
Here is a small app demonstrating one possible solution:
from PyQt4.QtGui import QPushButton, QWidget
from PyQt4.QtGui import QVBoxLayout, QApplication
def smart_connect(btn, btn_click_slot):
proxy_slot = lambda checked: btn_click_slot(btn)
btn.clicked.connect(proxy_slot)
class MyWidget(QWidget):
btn_count = 4
def __init__(self):
super(MyWidget, self).__init__()
lt = QVBoxLayout(self)
for i in range(self.btn_count):
btn = QPushButton("Button %s"%(i+1))
smart_connect(btn, self.btn_click)
lt.addWidget(btn)
def btn_click(self, btn):
print "Button '%s' was clicked."%btn.text()
app = QApplication([])
wgt = MyWidget()
wgt.show()
app.exec_()
Please enjoy :)
|
PyQt4,How to add a batch of widget (QPushButton) at one time and lets them to execute on SLOT
|
if i want to add 10 QPushButton at one time:
NumCount=20
for i in range(NumCount):
btn=QPushButton("%s %s" %("Button" i+1),self)
btn.clicked.connect(self.btnclick)
def btnclick(self):
# here is my question
# how to define which button clicked?
# how to print btn.text?
as stated in the def(btnclick).
|
[
"When you are in a slot, you can use sender() method (just call self.sender()) and you will receive a reference to the object, from which signal was emitted. Here is documentation about it.\n",
"I'd subclass QPushButton and define my own sender and slot. The QObject.sender() method is tempting, but it gives me the heebie-jeebies.\nclass MyPushButton(QPushButton):\n def __init__(self, text = '', parent = None):\n QPushButton.__init__(self, text, parent)\n self.clicked.connect(self._handle_click)\n\n my_click = QtCore.pyqtSignal(QObject)\n\n def _handle_click(self):\n my_click.emit(self)\n\ndef btnclick(btn):\n print 'Handle button %s' % btn\n\nfor i in xrange(20):\n btn = MyPushButton('%s %s' % ('Button', i + 1), self)\n btn.my_click.connect(btnclick)\n\nA slightly more Pythonic way of doing this could define the behavior within the class, like so:\nclass MyPushButton(QPushButton):\n def __init__(self, button_number, parent = None):\n QPushButton.__init__(self, '%s %s' % ('Button', button_number), parent)\n self.button_number = button_number\n self.clicked.connect(self._handle_click)\n\n def _handle_click(self):\n print 'Handle button %s' % self\n\nfor i in xrange(20):\n btn = MyPushButton(i + 1, self)\n\n",
"As gruszcsy said, there's self.sender() (in QObject) to get that exact info.\nThere's also the QSignalMapper class that provides a higher-level mapping from several signal senders to one slot. It helps for the basic cases of many-to-one signal/slot mapping.\nChris B's suggestion about defining a new slot that transmits the sender as a parameter is a bit more complicated, but cleaner in terms of program structure and separation between classes. I tend to use that method when the target slot is in another object. For mapping inside a class's private slot, sender() is both neat and quite appropriate, IMO.\n",
"Here is a small app demonstrating one possible solution:\nfrom PyQt4.QtGui import QPushButton, QWidget\nfrom PyQt4.QtGui import QVBoxLayout, QApplication\n\ndef smart_connect(btn, btn_click_slot):\n proxy_slot = lambda checked: btn_click_slot(btn)\n btn.clicked.connect(proxy_slot)\n\nclass MyWidget(QWidget):\n btn_count = 4\n def __init__(self):\n super(MyWidget, self).__init__()\n lt = QVBoxLayout(self)\n for i in range(self.btn_count):\n btn = QPushButton(\"Button %s\"%(i+1))\n smart_connect(btn, self.btn_click)\n lt.addWidget(btn)\n def btn_click(self, btn):\n print \"Button '%s' was clicked.\"%btn.text()\n\napp = QApplication([])\nwgt = MyWidget()\nwgt.show()\napp.exec_()\n\nPlease enjoy :)\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"pyqt",
"python",
"sender",
"signals"
] |
stackoverflow_0002108049_pyqt_python_sender_signals.txt
|
Q:
Garbage collection of object after exception
I have observed that after an exception I have an object for which constructor is not called, which causes a lock to be held. What is the best way to improve the situation? Would calling del in an except block be the solution?
b=BigHash(DB_DIR, url)
meta = bdecode(b.get())
return meta
b holds a lock which is released on destruction (it's a C++ object)
an exception is thrown by b.get().
A:
No matter what, you want the lock to be released - whether or not an exception is thrown. In that case, it's probably best to release the lock/delete b in a finally: clause:
b=BigHash(DB_DIR, url)
try:
meta = bdecode(b.get())
finally:
del b # or whatever you need to do to release the lock
return meta
You could also use a context manager - http://docs.python.org/library/stdtypes.html#typecontextmanager. Simply add code to free the lock in the BigHash.__exit__ function, which will be called after leaving the with block in the following code:
with BigHash(DB_DIR, url) as b:
meta = bdecode(b.get())
return meta
A:
You need to do something like this to make sure b in unlocked
b=BigHash(DB_DIR, url)
try:
meta = bdecode(b.get())
return meta
finally:
#unlock b here
A cleaner way would be if BigHash can work as a context, so you can write
with b as BigHash(DB_DIR, url):
meta = bdecode(b.get())
return meta
You might have to add some code to BigHash to make it work as a context though
A:
Calling del on a name is something you prettymuch never should do. Calling del does not guarantee anything useful about what will happen to the underlying object. You should never depend on a __del__ method for something you need to happen.
del only gets rid of one reference to an object, which can be confusing when you may have made more without thinking. Therefore, del is useful for cleaning up a namespace, not for controlling the lifetime of objects, and it's not even great for that—the proper way to control a name's lifetime is to put it in a function and have it go out of scope or put it in a with block.
You need to equip BigHash with the ability to release the lock explicitly, with an release or unlock or close method. If you want to use this with a context manager (with), you can define __exit__, which will get called at a predictable, useful time.
|
Garbage collection of object after exception
|
I have observed that after an exception I have an object for which constructor is not called, which causes a lock to be held. What is the best way to improve the situation? Would calling del in an except block be the solution?
b=BigHash(DB_DIR, url)
meta = bdecode(b.get())
return meta
b holds a lock which is released on destruction (it's a C++ object)
an exception is thrown by b.get().
|
[
"No matter what, you want the lock to be released - whether or not an exception is thrown. In that case, it's probably best to release the lock/delete b in a finally: clause:\nb=BigHash(DB_DIR, url)\ntry:\n meta = bdecode(b.get())\nfinally:\n del b # or whatever you need to do to release the lock\nreturn meta\n\nYou could also use a context manager - http://docs.python.org/library/stdtypes.html#typecontextmanager. Simply add code to free the lock in the BigHash.__exit__ function, which will be called after leaving the with block in the following code:\nwith BigHash(DB_DIR, url) as b:\n meta = bdecode(b.get())\nreturn meta\n\n",
"You need to do something like this to make sure b in unlocked\nb=BigHash(DB_DIR, url)\ntry:\n meta = bdecode(b.get())\n return meta\nfinally:\n #unlock b here\n\nA cleaner way would be if BigHash can work as a context, so you can write\nwith b as BigHash(DB_DIR, url):\n meta = bdecode(b.get())\n return meta\n\nYou might have to add some code to BigHash to make it work as a context though\n",
"Calling del on a name is something you prettymuch never should do. Calling del does not guarantee anything useful about what will happen to the underlying object. You should never depend on a __del__ method for something you need to happen.\ndel only gets rid of one reference to an object, which can be confusing when you may have made more without thinking. Therefore, del is useful for cleaning up a namespace, not for controlling the lifetime of objects, and it's not even great for that—the proper way to control a name's lifetime is to put it in a function and have it go out of scope or put it in a with block.\nYou need to equip BigHash with the ability to release the lock explicitly, with an release or unlock or close method. If you want to use this with a context manager (with), you can define __exit__, which will get called at a predictable, useful time. \n"
] |
[
3,
1,
0
] |
[] |
[] |
[
"destructor",
"exception_handling",
"python"
] |
stackoverflow_0002295978_destructor_exception_handling_python.txt
|
Q:
disabling "joining" when process shuts down
Is there a way to stop the multiprocessing Python module from trying to call & wait on join() on child processes of a parent process shutting down?
2010-02-18 10:58:34,750 INFO calling join() for process procRx1
I want the process to which I sent a SIGTERM to exit as quickly as possible (i.e. "fail fast") instead of waiting for several seconds before finally giving up on the join attempt.
Clarifications: I have a "central process" which creates a bunch of "child processes". I am looking for a way to cleanly process a "SIGTERM" signal from any process in order to bring down the whole process tree.
A:
Have you tried to explicitly using Process.terminate?
A:
You could try joining in a loop with a timeout (1 sec?) and checking if the thread is still alive, something like:
while True:
a_thread.join(1)
if not a_thread.isAlive(): break
Terminating the a_thread will trigger break clause.
A:
Sounds like setting your subprocess' flag Process.daemon = False may be what you want:
Process.daemon:
The process’s daemon flag, a Boolean value. This must be set before start() is called.
The initial value is inherited from the creating process.
When a process exits, it attempts to terminate all of its daemonic child processes.
Note that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-dameonic processes have exited.
|
disabling "joining" when process shuts down
|
Is there a way to stop the multiprocessing Python module from trying to call & wait on join() on child processes of a parent process shutting down?
2010-02-18 10:58:34,750 INFO calling join() for process procRx1
I want the process to which I sent a SIGTERM to exit as quickly as possible (i.e. "fail fast") instead of waiting for several seconds before finally giving up on the join attempt.
Clarifications: I have a "central process" which creates a bunch of "child processes". I am looking for a way to cleanly process a "SIGTERM" signal from any process in order to bring down the whole process tree.
|
[
"Have you tried to explicitly using Process.terminate?\n",
"You could try joining in a loop with a timeout (1 sec?) and checking if the thread is still alive, something like:\nwhile True:\n a_thread.join(1)\n if not a_thread.isAlive(): break\n\nTerminating the a_thread will trigger break clause.\n",
"Sounds like setting your subprocess' flag Process.daemon = False may be what you want:\nProcess.daemon:\nThe process’s daemon flag, a Boolean value. This must be set before start() is called.\nThe initial value is inherited from the creating process.\nWhen a process exits, it attempts to terminate all of its daemonic child processes. \nNote that a daemonic process is not allowed to create child processes. Otherwise a daemonic process would leave its children orphaned if it gets terminated when its parent process exits. Additionally, these are not Unix daemons or services, they are normal processes that will be terminated (and not joined) if non-dameonic processes have exited.\n"
] |
[
0,
0,
0
] |
[] |
[] |
[
"fail_fast",
"multiprocessing",
"python"
] |
stackoverflow_0002290043_fail_fast_multiprocessing_python.txt
|
Q:
PyQt4: Hide widget and resize window
I'm working with several widgets but the solution just won't come out. What I have is a series of buttons in series of QHBoxLayouts. Some buttons are hidden by default, but they will appear when needed. To solve space issues, all buttons have a minimum and maximum size so they always look well packed. Also I have a QTextEdit, visible by default, which is in a QVBoxLayout with the QHBoxLayout that hold the buttons
So the problem is this: When I hide the QTextEdit and show the other buttons, the window won't resize.
After searching I found that using self.ui.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize) will do the trick, but the problem is that it takes the maximum size from all widgets, therefore I end a huge window. Doing self.ui.layout().setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize) won't resize the window
I already tried using self.ui.resize(0,0), and when doing a self.ui.layout().update() I got False (which I find odd, http://doc.trolltech.com/4.6/qlayout.html#activate), and also tried to override sizeHint() but it keeps using the max size for all widgets.
Is there a way to resize the window and while taking care of the min and max size of a widget?
Thanks in advance
A:
The answer was quite lame... Just needed to change the QVBoxLayout for a QGridLayout and use self.ui.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)
|
PyQt4: Hide widget and resize window
|
I'm working with several widgets but the solution just won't come out. What I have is a series of buttons in series of QHBoxLayouts. Some buttons are hidden by default, but they will appear when needed. To solve space issues, all buttons have a minimum and maximum size so they always look well packed. Also I have a QTextEdit, visible by default, which is in a QVBoxLayout with the QHBoxLayout that hold the buttons
So the problem is this: When I hide the QTextEdit and show the other buttons, the window won't resize.
After searching I found that using self.ui.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize) will do the trick, but the problem is that it takes the maximum size from all widgets, therefore I end a huge window. Doing self.ui.layout().setSizeConstraint(QtGui.QLayout.SetMinAndMaxSize) won't resize the window
I already tried using self.ui.resize(0,0), and when doing a self.ui.layout().update() I got False (which I find odd, http://doc.trolltech.com/4.6/qlayout.html#activate), and also tried to override sizeHint() but it keeps using the max size for all widgets.
Is there a way to resize the window and while taking care of the min and max size of a widget?
Thanks in advance
|
[
"The answer was quite lame... Just needed to change the QVBoxLayout for a QGridLayout and use self.ui.layout().setSizeConstraint(QtGui.QLayout.SetFixedSize)\n"
] |
[
4
] |
[] |
[] |
[
"pyqt4",
"python",
"qt4"
] |
stackoverflow_0002293708_pyqt4_python_qt4.txt
|
Q:
Most optimal way to programmatically check if site is running locally or on a server with Django?
Currently I have this in my settings.py file:
DEBUG = True
LOCAL = True
TEMPLATE_DEBUG = DEBUG
SITE_TITLE = 'Stack Overflow Question'
REMOTE_SITE_URL = "http://************:8080"
LOCAL_SITE_URL = "http://************:8000"
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
if LOCAL:
SITE_URL = LOCAL_SITE_URL
ROOT_URL = '/mnt/hgfs/Sites/************'
engine = 'sqlite3'
dbName = '************.db'
dbUser = ''
dbPassword = ''
dbHost = ''
dbPort = ''
else:
SITE_URL = REMOTE_SITE_URL
ROOT_URL = '/var/www/vhosts/www.*************.com/public/'
engine = 'mysql'
dbName = '************'
dbUser = 'www-data'
dbPassword = '************'
dbHost = ''
dbPort = ''
The idea is that if I modify LOCAL=True to false, I can switch between the sqlite3 database and the mysql that's kept on the server. But this is cumbersome when using SVN. What I want is the ability for settings.py to intelligently know if it's on the server or running locally. Is there a way to sniff the URL, IP or simply check a file that exists on the server and not locally? Not only am I looking for a solution, but one that doesn't tax the server. Checking if a file exists might be a bit heavy of a process if it occurs every time Django renders a page. Any suggestions?
A:
Checking if a file exists will not occur every time a render occurs. It will actually only occur whenever you interpreter process is started, which all depends on your deployment configuration. This will depend on a variety on your webserver setup, but if you are using apache, chiefly MaxRequestPerChild and StartServers, and related parameters. For example, if I have
StartServers 8
MaxrequestsPerChild 4000
in a preforked apache, I will test that file for the first 8 requests, listen to 32,000 more requests, then test that file 8 more times. (Yes, I know it's much more complicated than this.)
The point is, most implementations that load your code will not re-source the settings.py file very often. With that in mind, how about:
import os
if os.uname()[1] == 'my.development.server.com':
LOCAL = True
else:
LOCAL = False
|
Most optimal way to programmatically check if site is running locally or on a server with Django?
|
Currently I have this in my settings.py file:
DEBUG = True
LOCAL = True
TEMPLATE_DEBUG = DEBUG
SITE_TITLE = 'Stack Overflow Question'
REMOTE_SITE_URL = "http://************:8080"
LOCAL_SITE_URL = "http://************:8000"
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
if LOCAL:
SITE_URL = LOCAL_SITE_URL
ROOT_URL = '/mnt/hgfs/Sites/************'
engine = 'sqlite3'
dbName = '************.db'
dbUser = ''
dbPassword = ''
dbHost = ''
dbPort = ''
else:
SITE_URL = REMOTE_SITE_URL
ROOT_URL = '/var/www/vhosts/www.*************.com/public/'
engine = 'mysql'
dbName = '************'
dbUser = 'www-data'
dbPassword = '************'
dbHost = ''
dbPort = ''
The idea is that if I modify LOCAL=True to false, I can switch between the sqlite3 database and the mysql that's kept on the server. But this is cumbersome when using SVN. What I want is the ability for settings.py to intelligently know if it's on the server or running locally. Is there a way to sniff the URL, IP or simply check a file that exists on the server and not locally? Not only am I looking for a solution, but one that doesn't tax the server. Checking if a file exists might be a bit heavy of a process if it occurs every time Django renders a page. Any suggestions?
|
[
"Checking if a file exists will not occur every time a render occurs. It will actually only occur whenever you interpreter process is started, which all depends on your deployment configuration. This will depend on a variety on your webserver setup, but if you are using apache, chiefly MaxRequestPerChild and StartServers, and related parameters. For example, if I have\nStartServers 8\nMaxrequestsPerChild 4000\n\nin a preforked apache, I will test that file for the first 8 requests, listen to 32,000 more requests, then test that file 8 more times. (Yes, I know it's much more complicated than this.)\nThe point is, most implementations that load your code will not re-source the settings.py file very often. With that in mind, how about:\nimport os\nif os.uname()[1] == 'my.development.server.com':\n LOCAL = True\nelse:\n LOCAL = False\n\n"
] |
[
5
] |
[] |
[] |
[
"database",
"django",
"python"
] |
stackoverflow_0002298657_database_django_python.txt
|
Q:
pycurl install :( already have min. libcurl version
I'm running python 2.6 on an Intel Mac OS X 10.5
I'm trying to install pycurl 7.16.2.1 (as recommended here http://curl.haxx.se/mail/curlpython-2009-03/0009.html), but for some reason, the installation sees my libcurl 7.16.3, yet it still insist I install 7.16.2 or greater (doesn't 7.16.3 satisfy that?)
Here's the error output:
Running pycurl-7.16.2.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-3emZIB/pycurl-7.16.2.1/egg-dist-tmp-K10rbP
Using curl-config (libcurl 7.16.3)
src/pycurl.c:54:4:src/pycurl.c:54:4: error: #error "Need libcurl version 7.16.2 or greater to compile pycurl."
error: #error "Need libcurl version 7.16.2 or greater to compile pycurl."
To be certain curl-config --version yields libcurl 7.16.3
Any advice? Should I upgrade libcurl, or stick with the factory default lib?
== added more details after response ==
AFAIK the python I have is factory default (I didn't get it myself from python.org)
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
And this is my curl version. Looks misleading because I'm using an Intel Macbook, not PPC.
curl 7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
Protocols: tftp ftp telnet dict ldap http file https ftps
Features: GSS-Negotiate IPv6 Largefile NTLM SSL libz
I'll take whichever pycurl works with my existing python interpreter
I do have ports:
sudo port -u install py26-pycurl
Error: Port py26-pycurl not found
A:
If you are using the python.org Python 2.6, it is built using the 10.4 SDK so as to be able to run on multiple versions of OS X. In that case, the pycurl build is likely trying to link against the 10.4 version of libcurl, which appears to be 7.13.1. The thread you link to is talking about using the 10.5 Apple-supplied Python 2.5 which is built using 10.5 libraries and, with that, pycurl 7.16.2.1 does seem to build and install correctly.
You can try to manually install pycurl; there is a documented --curl-config argument to its setup.py which allows you to specify the path to the curl-config to use. Unfortunately, that does not seem to work with /usr/bin/curl-config; the proper include files directories are not being added. Short of hacking the setup.py file, a better approach is to install a newer libcurl and use the latest pycurl. The easiest way to do that is to use MacPorts. Even easier is to install pycurl and python2.6 from MacPorts. If you don't already use MacPorts, download and install the base files. Then:
sudo port selfupdate
sudo port -u install py26-curl #edited
The MacPorts python2.6 will be at /opt/local/bin/python2.6.
If you'd rather stick with the python2.6 you've installed, install the curl package:
sudo port selfupdate
sudo port -u install curl
Then manually install pycurl using something like:
curl http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz | tar xz
cd pycurl-7.19.0
python2.6 setup.py install --curl-config=/opt/local/bin/curl-config
A:
I got my pycurl from Sourceforge. Seems they'd have installable builds backwards and forwards that would match any "shipped with" Mac OS X configuration there is. I believe the URL is http://pycurl.sourceforge.net but don't quote me on that.
BZT
|
pycurl install :( already have min. libcurl version
|
I'm running python 2.6 on an Intel Mac OS X 10.5
I'm trying to install pycurl 7.16.2.1 (as recommended here http://curl.haxx.se/mail/curlpython-2009-03/0009.html), but for some reason, the installation sees my libcurl 7.16.3, yet it still insist I install 7.16.2 or greater (doesn't 7.16.3 satisfy that?)
Here's the error output:
Running pycurl-7.16.2.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-3emZIB/pycurl-7.16.2.1/egg-dist-tmp-K10rbP
Using curl-config (libcurl 7.16.3)
src/pycurl.c:54:4:src/pycurl.c:54:4: error: #error "Need libcurl version 7.16.2 or greater to compile pycurl."
error: #error "Need libcurl version 7.16.2 or greater to compile pycurl."
To be certain curl-config --version yields libcurl 7.16.3
Any advice? Should I upgrade libcurl, or stick with the factory default lib?
== added more details after response ==
AFAIK the python I have is factory default (I didn't get it myself from python.org)
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
And this is my curl version. Looks misleading because I'm using an Intel Macbook, not PPC.
curl 7.16.3 (powerpc-apple-darwin9.0) libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
Protocols: tftp ftp telnet dict ldap http file https ftps
Features: GSS-Negotiate IPv6 Largefile NTLM SSL libz
I'll take whichever pycurl works with my existing python interpreter
I do have ports:
sudo port -u install py26-pycurl
Error: Port py26-pycurl not found
|
[
"If you are using the python.org Python 2.6, it is built using the 10.4 SDK so as to be able to run on multiple versions of OS X. In that case, the pycurl build is likely trying to link against the 10.4 version of libcurl, which appears to be 7.13.1. The thread you link to is talking about using the 10.5 Apple-supplied Python 2.5 which is built using 10.5 libraries and, with that, pycurl 7.16.2.1 does seem to build and install correctly.\nYou can try to manually install pycurl; there is a documented --curl-config argument to its setup.py which allows you to specify the path to the curl-config to use. Unfortunately, that does not seem to work with /usr/bin/curl-config; the proper include files directories are not being added. Short of hacking the setup.py file, a better approach is to install a newer libcurl and use the latest pycurl. The easiest way to do that is to use MacPorts. Even easier is to install pycurl and python2.6 from MacPorts. If you don't already use MacPorts, download and install the base files. Then:\nsudo port selfupdate\nsudo port -u install py26-curl #edited\n\nThe MacPorts python2.6 will be at /opt/local/bin/python2.6.\nIf you'd rather stick with the python2.6 you've installed, install the curl package:\nsudo port selfupdate\nsudo port -u install curl\n\nThen manually install pycurl using something like:\ncurl http://pycurl.sourceforge.net/download/pycurl-7.19.0.tar.gz | tar xz\ncd pycurl-7.19.0\npython2.6 setup.py install --curl-config=/opt/local/bin/curl-config\n\n",
"I got my pycurl from Sourceforge. Seems they'd have installable builds backwards and forwards that would match any \"shipped with\" Mac OS X configuration there is. I believe the URL is http://pycurl.sourceforge.net but don't quote me on that.\nBZT\n"
] |
[
7,
0
] |
[] |
[] |
[
"libcurl",
"macos",
"pycurl",
"python"
] |
stackoverflow_0002279014_libcurl_macos_pycurl_python.txt
|
Q:
Is nested dictionary in design ok?
My data is structured in a way that I ended up creating a nested dictionary in my design like:
my_dict = {"a": {"b": {"c":"I am c"}}}
my_dict["a"]["b"]["c"]
Is it usual! or we have some other better alternatives (using objects!)?
A:
You could use a tuple to store your values in a flat dictionary:
d = {}
d[a, b, c] = e
It all depends on what you are doing, but remember that The Zen of Python says that flat is better than nested :)
A:
There is nothing inherently wrong with nested dicts. Anything can be a dict value, and it can make sense for a dict to be one.
A lot of the time when people make nested dicts, their problems could be solved slightly more easily by using a dict with tuples for keys. Instead of accessing a value as d[a][b][c], then, the value would be accessed as d[a, b, c]. This is often easier to set up and work with.
A:
At first they may seem like a good idea, but usually you'll find yourself needing more information/functionality from them. If that happens, your first reaction may be "I need more hashes", but all this can be avoided by using a simpler hierarchy ... it would be easier too.
A:
I would not build complex data structures like that in the code itself. There is too great a risk of making a mistake with punctuation, and anyone reading the code will tend to get confused by this. Far better to put your constant data in some simple form, with no nesting of data structures. Then if you need to have a nested dictionary in the app, build it with code.
a = {"a":"I am a"}
b = {"b":"I am b"}
c = {"c":"I am c"}
mydict = {}
mydict["a"] = a
mydict["b"] = b
mydict["c"] = c
print mydict
{'a': {'a': 'I am a'}, 'c': {'c': 'I am c'}, 'b': {'b': 'I am b'}}
A:
Maybe one nested dictionary is okay... but even then you're asking to get confused later and there's a pretty good chance that if you're already doing nested stuff you're gonna want more information in it later.
In general I'd say take a step back and see if all that information in the dictionaries is needed. Try to simplify it first. If it really is all needed, I'd try to make a simple class for it. Might be a little overkill but like I said, if you're going down that road already, you're probably gonna end up adding more information later. It's easier to modify a class than it is to try and figure out all that nested information and make your code work with it later.
|
Is nested dictionary in design ok?
|
My data is structured in a way that I ended up creating a nested dictionary in my design like:
my_dict = {"a": {"b": {"c":"I am c"}}}
my_dict["a"]["b"]["c"]
Is it usual! or we have some other better alternatives (using objects!)?
|
[
"You could use a tuple to store your values in a flat dictionary:\nd = {}\nd[a, b, c] = e\n\nIt all depends on what you are doing, but remember that The Zen of Python says that flat is better than nested :)\n",
"There is nothing inherently wrong with nested dicts. Anything can be a dict value, and it can make sense for a dict to be one.\nA lot of the time when people make nested dicts, their problems could be solved slightly more easily by using a dict with tuples for keys. Instead of accessing a value as d[a][b][c], then, the value would be accessed as d[a, b, c]. This is often easier to set up and work with.\n",
"At first they may seem like a good idea, but usually you'll find yourself needing more information/functionality from them. If that happens, your first reaction may be \"I need more hashes\", but all this can be avoided by using a simpler hierarchy ... it would be easier too.\n",
"I would not build complex data structures like that in the code itself. There is too great a risk of making a mistake with punctuation, and anyone reading the code will tend to get confused by this. Far better to put your constant data in some simple form, with no nesting of data structures. Then if you need to have a nested dictionary in the app, build it with code.\na = {\"a\":\"I am a\"}\nb = {\"b\":\"I am b\"}\nc = {\"c\":\"I am c\"}\nmydict = {}\nmydict[\"a\"] = a\nmydict[\"b\"] = b\nmydict[\"c\"] = c\nprint mydict\n\n{'a': {'a': 'I am a'}, 'c': {'c': 'I am c'}, 'b': {'b': 'I am b'}}\n\n",
"Maybe one nested dictionary is okay... but even then you're asking to get confused later and there's a pretty good chance that if you're already doing nested stuff you're gonna want more information in it later.\nIn general I'd say take a step back and see if all that information in the dictionaries is needed. Try to simplify it first. If it really is all needed, I'd try to make a simple class for it. Might be a little overkill but like I said, if you're going down that road already, you're probably gonna end up adding more information later. It's easier to modify a class than it is to try and figure out all that nested information and make your code work with it later.\n"
] |
[
8,
7,
1,
0,
0
] |
[] |
[] |
[
"data_structures",
"dictionary",
"python"
] |
stackoverflow_0002298723_data_structures_dictionary_python.txt
|
Q:
How to upload all .html files to a remote server using FTP and preserving file structure?
I have edited about 100 html files locally, and now I want to push them to my live server, which I can only access via ftp.
The HTML files are in many different directories, but hte directory structure on the remote machine is the same as on the local machine.
How can I recursively descend from my top-level directory ftp-ing all of the .html files to the corresponding directory/filename on the remote machine?
Thanks!
A:
If you want to do it in Python (rather than using other pre-packaged existing tools), you can use os.walk to read everything in the local subtree, and ftplib to perform all the FTP operations. In particular, storbinary is the method you'll usually use to transfer entire files without line-end conversions (storlines if you do want line-end conversions, for files that are text, not binary, and that you know need such treatment).
A:
umm, maybe by pressing F5 in mc for linux or total commander for windows?
A:
After searching PyPI, I found ftptool (http://pypi.python.org/pypi/ftptool/0.4.2). Its mirror_to_remote method could be what you need. I don't have an FTP server handy, though, so I couldn't test it.
A:
if you have a mac, you can try cyberduck. It's good for syncing remote directory structures via ftp.
|
How to upload all .html files to a remote server using FTP and preserving file structure?
|
I have edited about 100 html files locally, and now I want to push them to my live server, which I can only access via ftp.
The HTML files are in many different directories, but hte directory structure on the remote machine is the same as on the local machine.
How can I recursively descend from my top-level directory ftp-ing all of the .html files to the corresponding directory/filename on the remote machine?
Thanks!
|
[
"If you want to do it in Python (rather than using other pre-packaged existing tools), you can use os.walk to read everything in the local subtree, and ftplib to perform all the FTP operations. In particular, storbinary is the method you'll usually use to transfer entire files without line-end conversions (storlines if you do want line-end conversions, for files that are text, not binary, and that you know need such treatment).\n",
"umm, maybe by pressing F5 in mc for linux or total commander for windows?\n",
"After searching PyPI, I found ftptool (http://pypi.python.org/pypi/ftptool/0.4.2). Its mirror_to_remote method could be what you need. I don't have an FTP server handy, though, so I couldn't test it.\n",
"if you have a mac, you can try cyberduck. It's good for syncing remote directory structures via ftp.\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"ftp",
"networking",
"python",
"scripting"
] |
stackoverflow_0002263782_ftp_networking_python_scripting.txt
|
Q:
Django: When using register.inclusion_tag() where/what order is the template searched for?
When using the register.inclusion_tag() shortcut on a Custom Template Tag, assuming you define the template as 'some_fragment.html', in what directories/order does Django try to find that template?
Assume as many 'defaults' as is reasonable.
The Custom Template Tag portion of the documentation doesn't list anything specific, except that the template there is one that is defined by the template tag author, not the designer.
I read that and assume that it might look in your custom template tags directory first, but haven't tried it yet, but I have a feeling that it does the 'usual defaults' for templates, and nothing magical or special... but it is pony powered, so I had to ask.
A:
It follows exactly the same rules as for any other template. That is, it will use the directories specified in your TEMPLATE_DIRS setting in order - then, depending on the contents of your TEMPLATE_LOADERS setting, will also look in templates subdirectories under each of your apps. It won't ever look in the templatetags directory itself.
|
Django: When using register.inclusion_tag() where/what order is the template searched for?
|
When using the register.inclusion_tag() shortcut on a Custom Template Tag, assuming you define the template as 'some_fragment.html', in what directories/order does Django try to find that template?
Assume as many 'defaults' as is reasonable.
The Custom Template Tag portion of the documentation doesn't list anything specific, except that the template there is one that is defined by the template tag author, not the designer.
I read that and assume that it might look in your custom template tags directory first, but haven't tried it yet, but I have a feeling that it does the 'usual defaults' for templates, and nothing magical or special... but it is pony powered, so I had to ask.
|
[
"It follows exactly the same rules as for any other template. That is, it will use the directories specified in your TEMPLATE_DIRS setting in order - then, depending on the contents of your TEMPLATE_LOADERS setting, will also look in templates subdirectories under each of your apps. It won't ever look in the templatetags directory itself.\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0002299779_django_django_templates_python.txt
|
Q:
Building a wiki application?
I'm building this app in Python with Django.
I would like to give parts of the site wiki like functionality,
but I don't know how to go on about reliability and security.
Make sure that good content is not ruined
Check for quality
Prevent spam from invading the site
The items requiring wiki like functionality are just a few: a couple of text fields.
Can anyone help on this one?
Would be very much appreciated. :)
A:
You could try using Django Wikiapp, which gives you most of the features you want in a wiki, including history and the ability to revert to older versions of an article. I have personally used this app and it's pretty self-explanatory; they also have a bit of documentation at http://code.google.com/p/django-wikiapp/source/browse/trunk/docs.
In terms of spam protection you can to one of two things or both: password protect the pages that have to do with editing the wiki, and use Akismet to filter for spam. I'm working on something similar and this is probably what we'll end up doing.
A:
Assuming that there will be a community of users you can provide good tools for them to spot problems and easily undo damage. The most important of these is to provide a Recent Changes page that summarizes recent edits. Then each page that can be edited should retain prior versions of the page that can be used to replace any damaging edit. This makes it easier to undo damage than it is to damage things.
Then think about how you are going to handle either locking resources or handling simultaneous edits.
If you can tie edits to users you can provide some administrative functions for undoing all edits by a particular user, and banning that user.
Checking for quality would be tied to the particular data that your application is using.
A:
Make sure that good content is not ruined = version each edit and allow roll-backs.
Check for quality = get people to help with that
Prevent spam from invading the site = get people to help with that, require login, add a captcha if need be, use nofollow for all links
|
Building a wiki application?
|
I'm building this app in Python with Django.
I would like to give parts of the site wiki like functionality,
but I don't know how to go on about reliability and security.
Make sure that good content is not ruined
Check for quality
Prevent spam from invading the site
The items requiring wiki like functionality are just a few: a couple of text fields.
Can anyone help on this one?
Would be very much appreciated. :)
|
[
"You could try using Django Wikiapp, which gives you most of the features you want in a wiki, including history and the ability to revert to older versions of an article. I have personally used this app and it's pretty self-explanatory; they also have a bit of documentation at http://code.google.com/p/django-wikiapp/source/browse/trunk/docs.\nIn terms of spam protection you can to one of two things or both: password protect the pages that have to do with editing the wiki, and use Akismet to filter for spam. I'm working on something similar and this is probably what we'll end up doing.\n",
"Assuming that there will be a community of users you can provide good tools for them to spot problems and easily undo damage. The most important of these is to provide a Recent Changes page that summarizes recent edits. Then each page that can be edited should retain prior versions of the page that can be used to replace any damaging edit. This makes it easier to undo damage than it is to damage things.\nThen think about how you are going to handle either locking resources or handling simultaneous edits.\nIf you can tie edits to users you can provide some administrative functions for undoing all edits by a particular user, and banning that user.\nChecking for quality would be tied to the particular data that your application is using.\n",
"\nMake sure that good content is not ruined = version each edit and allow roll-backs. \nCheck for quality = get people to help with that\nPrevent spam from invading the site = get people to help with that, require login, add a captcha if need be, use nofollow for all links\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"django",
"django_models",
"python",
"wiki"
] |
stackoverflow_0002299697_django_django_models_python_wiki.txt
|
Q:
why python associative map member variable is shared between objects
For class A, why is aMap member variable being shared between object and object b?
>>> class A:
... aMap = {}
>>> a = A()
>>> a.aMap["hello"] = 1
>>> b = A()
>>> b.aMap["world"] = 2
>>> c = []
>>> c.append(a)
>>> c.append(b)
>>> for i in c:
... for j in i.aMap.items():
... print j
('world', 2)
('hello', 1)
('world', 2)
('hello', 1)
A:
Because you defined it as a class attribute, not instance attribute.
If you wish to have it as instance attribute and not be shared between instances, you have to define it like this:
class A(object):
def __init__(self):
self.aMap = {}
A:
Because its a class attribute, not an instance attribute ("member variable").
To make it a instance attribute, assign it on an instance, e.g. in the constructor:
class A:
def __init__(self):
self.aMap = {}
But you could also do:
a = A()
a.aMap = {}
A:
Because you are effectively defining a class variable instead of an instance variable.
To define an instance variable, you should do it on a method referring the object itself (generally self):
class A(object):
class_variable = 0
def __init__(self, a, b):
self.instance_variable = a
class_variable = b
>>> a=A(1,2)
>>> print a.instance_variable
1
>>> print a.class_variable
2
>>> b=A(2,1)
>>> print b.instance_variable
2
>>> print b.class_variable
1
>>> print a.instance_variable
1
>>> print a.class_variable
1
|
why python associative map member variable is shared between objects
|
For class A, why is aMap member variable being shared between object and object b?
>>> class A:
... aMap = {}
>>> a = A()
>>> a.aMap["hello"] = 1
>>> b = A()
>>> b.aMap["world"] = 2
>>> c = []
>>> c.append(a)
>>> c.append(b)
>>> for i in c:
... for j in i.aMap.items():
... print j
('world', 2)
('hello', 1)
('world', 2)
('hello', 1)
|
[
"Because you defined it as a class attribute, not instance attribute.\nIf you wish to have it as instance attribute and not be shared between instances, you have to define it like this:\nclass A(object):\n def __init__(self):\n self.aMap = {}\n\n",
"Because its a class attribute, not an instance attribute (\"member variable\").\nTo make it a instance attribute, assign it on an instance, e.g. in the constructor:\nclass A:\n def __init__(self):\n self.aMap = {}\n\nBut you could also do:\na = A()\na.aMap = {}\n\n",
"Because you are effectively defining a class variable instead of an instance variable.\nTo define an instance variable, you should do it on a method referring the object itself (generally self):\nclass A(object):\n class_variable = 0\n\n def __init__(self, a, b):\n self.instance_variable = a\n class_variable = b\n\n>>> a=A(1,2)\n>>> print a.instance_variable\n1\n>>> print a.class_variable\n2\n>>> b=A(2,1)\n>>> print b.instance_variable\n2\n>>> print b.class_variable\n1\n>>> print a.instance_variable\n1\n>>> print a.class_variable\n1\n\n"
] |
[
5,
3,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002299801_python.txt
|
Q:
Problem with asyn icmp ping
I'm writing service in python that async ping domains. So it must be able to ping many ip's at the same time. I wrote it on epoll ioloop, but have problem with packets loss.
When there are many simultaneous ICMP requests much part of replies on them didn't reach my servise. What may cause this situation and how i can make my service ping many hosts at the same time without packet loss?
Thanks)
A:
A problem you might be having is due to the fact that ICMP is layer 3 of the OSI model and does not use a port for communication. In short, ICMP isn't really designed for this. The desired behavior is still possible but perhaps the IP Stack you are using is getting in the way and if this is on a Windows system then 100% sure this is your problem. I would fire up Wireshark to make sure you are actually getting incoming packets, if this is the case then I would use libpcap to track in ICMP replies. If the problem is with sending then you'll have to use raw sockets and build your own ICMP packets.
|
Problem with asyn icmp ping
|
I'm writing service in python that async ping domains. So it must be able to ping many ip's at the same time. I wrote it on epoll ioloop, but have problem with packets loss.
When there are many simultaneous ICMP requests much part of replies on them didn't reach my servise. What may cause this situation and how i can make my service ping many hosts at the same time without packet loss?
Thanks)
|
[
"A problem you might be having is due to the fact that ICMP is layer 3 of the OSI model and does not use a port for communication. In short, ICMP isn't really designed for this. The desired behavior is still possible but perhaps the IP Stack you are using is getting in the way and if this is on a Windows system then 100% sure this is your problem. I would fire up Wireshark to make sure you are actually getting incoming packets, if this is the case then I would use libpcap to track in ICMP replies. If the problem is with sending then you'll have to use raw sockets and build your own ICMP packets. \n"
] |
[
0
] |
[] |
[] |
[
"icmp",
"ping",
"python"
] |
stackoverflow_0002299751_icmp_ping_python.txt
|
Q:
gdb python scripting: where has `parse_and_eval` gone?
I had some scripts in Python to help me debugging with GDB that used the function gdb.parse_and_eval (still documented) to get the inferior values from the arguments passed to a scripted command, and now the module doesn't seem to have any trace of that function. Doing python import gdb; print dir(gdb) from GDB clearly shows that this function is missing.
I wrote the scripts some time ago for the GDB 6.8 in the archer branch, and now I cannot find any information about if it's been deprecated or what happened in GDB 7.
Any information about it?
Thanks!
A:
I don't know where it went or why, but Qt implemented this workaround in their code, which may be practically useful to you:
def parseAndEvaluate(exp):
if gdb.VERSION.startswith("6.8.50.2009"):
return gdb.parse_and_eval(exp)
# Work around non-existing gdb.parse_and_eval as in released 7.0
gdb.execute("set logging redirect on")
gdb.execute("set logging on")
gdb.execute("print %s" % exp)
gdb.execute("set logging off")
return gdb.history(0)
A:
parse_and_eval was checked in on the Archer branch, but has not been merged into mainline in time for 7.0 release. It has been merged now:
2009-12-03 Tom Tromey <tromey@redhat.com>
* python/python.c (gdbpy_parse_and_eval): New function.
(GdbMethods): Add "parse_and_eval".
and will be available in the upcoming 7.1 release.
|
gdb python scripting: where has `parse_and_eval` gone?
|
I had some scripts in Python to help me debugging with GDB that used the function gdb.parse_and_eval (still documented) to get the inferior values from the arguments passed to a scripted command, and now the module doesn't seem to have any trace of that function. Doing python import gdb; print dir(gdb) from GDB clearly shows that this function is missing.
I wrote the scripts some time ago for the GDB 6.8 in the archer branch, and now I cannot find any information about if it's been deprecated or what happened in GDB 7.
Any information about it?
Thanks!
|
[
"I don't know where it went or why, but Qt implemented this workaround in their code, which may be practically useful to you:\ndef parseAndEvaluate(exp):\n if gdb.VERSION.startswith(\"6.8.50.2009\"):\n return gdb.parse_and_eval(exp)\n # Work around non-existing gdb.parse_and_eval as in released 7.0\n gdb.execute(\"set logging redirect on\")\n gdb.execute(\"set logging on\")\n gdb.execute(\"print %s\" % exp)\n gdb.execute(\"set logging off\")\n return gdb.history(0)\n\n",
"parse_and_eval was checked in on the Archer branch, but has not been merged into mainline in time for 7.0 release. It has been merged now:\n2009-12-03 Tom Tromey <tromey@redhat.com>\n\n * python/python.c (gdbpy_parse_and_eval): New function.\n (GdbMethods): Add \"parse_and_eval\".\n\nand will be available in the upcoming 7.1 release.\n"
] |
[
4,
4
] |
[] |
[] |
[
"gdb",
"python"
] |
stackoverflow_0002290842_gdb_python.txt
|
Q:
Combining words in Python (permutations?)
Suppose I have 4 words, as a string.
How do I join them all like this?
s = orange apple grapes pear
The result would be a String:
"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"
I am thinking:
list_words = s.split(' ')
for l in list_words:
And then use enumerate? Is that what you would use to do this function?
A:
Maybe this is what you want?
s = "orange apple grapes pear"
from itertools import product
l = s.split()
r='/'.join(''.join(k*v for k,v in zip(l, x))
for x in product(range(2), repeat=len(l))
if sum(x) > 1)
print r
If run on 'a b c' (for clarity) the result is:
bc/ac/ab/abc
(Updated after comment from poster.)
A:
>>> from itertools import combinations
>>> s = "orange apple grapes pear".split()
>>> '/'.join([''.join(y) for y in [ x for z in range(len(s)) for x in combinations(s,z)] if len(y)>1])
'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear'
A:
s = 'orange apple grapes pear'
list_words = s.split()
num = len(list_words)
ans = []
for i in xrange(1,2**num-1):
cur = []
for j,word in enumerate(list_words):
if i & (1 << j):
cur.append(word)
if len(cur) > 1:
ans.append(''.join(cur))
print '/'.join(ans)
This gives all subsets of the list of words except the empty one, single words, and all of them.
For your example:
orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear
A:
>>> import itertools
>>> from itertools import combinations
>>> s = "orange apple grapes pear".split()
>>> res=[]
>>> for i in range(2,len(s)+1):
... res += [''.join(x) for x in combinations(s,i)]
...
>>> '/'.join(res)
'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear/orangeapplegrapespear'
A:
>>> s = "orange apple grapes pear".split()
>>> '/'.join(''.join(k) for k in [[s[j] for j in range(len(s)) if 1<<j&i] for i in range(1<<len(s))] if len(k)>1)
'orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear/orangeapplegrapespear'
|
Combining words in Python (permutations?)
|
Suppose I have 4 words, as a string.
How do I join them all like this?
s = orange apple grapes pear
The result would be a String:
"orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/applegrapespear"
I am thinking:
list_words = s.split(' ')
for l in list_words:
And then use enumerate? Is that what you would use to do this function?
|
[
"Maybe this is what you want?\ns = \"orange apple grapes pear\"\n\nfrom itertools import product\nl = s.split()\nr='/'.join(''.join(k*v for k,v in zip(l, x))\n for x in product(range(2), repeat=len(l))\n if sum(x) > 1)\nprint r\n\nIf run on 'a b c' (for clarity) the result is:\nbc/ac/ab/abc\n\n(Updated after comment from poster.)\n",
">>> from itertools import combinations\n>>> s = \"orange apple grapes pear\".split()\n>>> '/'.join([''.join(y) for y in [ x for z in range(len(s)) for x in combinations(s,z)] if len(y)>1])\n'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear'\n\n",
"s = 'orange apple grapes pear'\n\nlist_words = s.split()\n\nnum = len(list_words)\nans = []\nfor i in xrange(1,2**num-1):\n cur = []\n for j,word in enumerate(list_words):\n if i & (1 << j):\n cur.append(word)\n if len(cur) > 1: \n ans.append(''.join(cur))\nprint '/'.join(ans)\n\nThis gives all subsets of the list of words except the empty one, single words, and all of them.\nFor your example: \norangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear\n",
">>> import itertools\n>>> from itertools import combinations\n>>> s = \"orange apple grapes pear\".split()\n>>> res=[]\n>>> for i in range(2,len(s)+1):\n... res += [''.join(x) for x in combinations(s,i)]\n... \n>>> '/'.join(res)\n'orangeapple/orangegrapes/orangepear/applegrapes/applepear/grapespear/orangeapplegrapes/orangeapplepear/orangegrapespear/applegrapespear/orangeapplegrapespear'\n\n",
">>> s = \"orange apple grapes pear\".split()\n>>> '/'.join(''.join(k) for k in [[s[j] for j in range(len(s)) if 1<<j&i] for i in range(1<<len(s))] if len(k)>1)\n'orangeapple/orangegrapes/applegrapes/orangeapplegrapes/orangepear/applepear/orangeapplepear/grapespear/orangegrapespear/applegrapespear/orangeapplegrapespear'\n\n"
] |
[
4,
4,
1,
1,
1
] |
[] |
[] |
[
"permutation",
"python",
"string"
] |
stackoverflow_0002299671_permutation_python_string.txt
|
Q:
Python Thread/Queue issue
I'm creating a threaded python script that has a collection of files that is put into a queue and then an unknown amount of threads (default is 3) to start downloading. When each of the threads complete it updates the stdout with the queue status and a percentage. All the files are being downloaded but the status information is wrong on the 3rd thread and I'm not sure why. I've been considering creating a work_completed queue to use for the calculation but don't think I should have to/that it would matter. Could someone point me in the right direction here?
download_queue = queue.Queue()
class Downloader(threading.Thread):
def __init__(self,work_queue):
super().__init__()
self.current_job = 0
self.work_queue = work_queue
self.queue_size = work_queue.qsize()
def run(self):
while self.work_queue.qsize() > 0:
url = self.work_queue.get(True)
system_call = "wget -nc -q {0} -O {1}".format(url,local_file)
os.system(system_call)
self.current_job = int(self.queue_size) - int(self.work_queue.qsize())
self.percent = (self.current_job / self.queue_size) * 100
sys.stdout.flush()
status = "\rDownloading " + url.split('/')[-1] + " [status: " + str(self.current_job) + "/" + str(self.queue_size) + ", " + str(round(self.percent,2)) + "%]"
finally:
self.work_queue.task_done()
def main:
if download_queue.qsize() > 0:
if options.active_downloads:
active_downloads = options.active_downloads
else:
active_downloads = 3
for x in range(active_downloads):
downloader = Downloader(download_queue)
downloader.start()
download_queue.join()
A:
You can't check the queue size in one statement, and then .get() from the queue in the next. In the meantime the whole world may have changed. The .get() method call is the single atomic operation you need to call. If it raises Empty or blocks, the queue is empty.
Your threads can overwrite each other's output. I would have another thread with an input queue whos only job is to print the items in the queue to stdout. It can also count off the number of completed items and produce status information.
I also tend not to subclass Thread, but instead just supply a plain Thread instance with a target= parameter and .start() the thread.
based on your response, try this:
download_queue = queue.Queue()
class Downloader(threading.Thread):
def __init__(self,work_queue, original_size):
super().__init__()
self.current_job = 0
self.work_queue = work_queue
self.queue_size = original_size
def run(self):
while True:
try:
url = self.work_queue.get(False)
system_call = "wget -nc -q {0} -O {1}".format(url,local_file)
os.system(system_call)
# the following code is questionable. By the time we get here,
# many other items may have been taken off the queue.
self.current_job = int(self.queue_size) - int(self.work_queue.qsize())
self.percent = (self.current_job / self.queue_size) * 100
sys.stdout.flush()
status = ("\rDownloading " + url.split('/')[-1] +
" [status: " + str(self.current_job) +
"/" + str(self.queue_size) + ", " +
str(round(self.percent,2)) + "%]" )
except queue.Empty:
pass
finally:
self.work_queue.task_done()
def main:
if download_queue.qsize() > 0:
original_size = download_queue.qsize()
if options.active_downloads:
active_downloads = options.active_downloads
else:
active_downloads = 3
for x in range(active_downloads):
downloader = Downloader(download_queue, original_size)
downloader.start()
download_queue.join()
A:
If you'd like to use the multiprocessing module, it includes a very nice parallel imap_unordered, which would reduce your problem to the very elegant:
import multiprocessing, sys
class ParallelDownload:
def __init__(self, urls, processcount=3):
self.total_items = len(urls)
self.pool = multiprocessing.Pool(processcount)
for n, status in enumerate(self.pool.imap_unordered(self.download, urls)):
stats = (n, self.total_items, n/self.total_items)
sys.stdout.write(status + " [%d/%d = %0.2f %%]\n"%stats)
def download(self, url):
system_call = "wget -nc -q {0} -O {1}".format(url, local_file)
os.system(system_call)
status = "\rDownloaded " + url.split('/')[-1]
return status
|
Python Thread/Queue issue
|
I'm creating a threaded python script that has a collection of files that is put into a queue and then an unknown amount of threads (default is 3) to start downloading. When each of the threads complete it updates the stdout with the queue status and a percentage. All the files are being downloaded but the status information is wrong on the 3rd thread and I'm not sure why. I've been considering creating a work_completed queue to use for the calculation but don't think I should have to/that it would matter. Could someone point me in the right direction here?
download_queue = queue.Queue()
class Downloader(threading.Thread):
def __init__(self,work_queue):
super().__init__()
self.current_job = 0
self.work_queue = work_queue
self.queue_size = work_queue.qsize()
def run(self):
while self.work_queue.qsize() > 0:
url = self.work_queue.get(True)
system_call = "wget -nc -q {0} -O {1}".format(url,local_file)
os.system(system_call)
self.current_job = int(self.queue_size) - int(self.work_queue.qsize())
self.percent = (self.current_job / self.queue_size) * 100
sys.stdout.flush()
status = "\rDownloading " + url.split('/')[-1] + " [status: " + str(self.current_job) + "/" + str(self.queue_size) + ", " + str(round(self.percent,2)) + "%]"
finally:
self.work_queue.task_done()
def main:
if download_queue.qsize() > 0:
if options.active_downloads:
active_downloads = options.active_downloads
else:
active_downloads = 3
for x in range(active_downloads):
downloader = Downloader(download_queue)
downloader.start()
download_queue.join()
|
[
"You can't check the queue size in one statement, and then .get() from the queue in the next. In the meantime the whole world may have changed. The .get() method call is the single atomic operation you need to call. If it raises Empty or blocks, the queue is empty.\nYour threads can overwrite each other's output. I would have another thread with an input queue whos only job is to print the items in the queue to stdout. It can also count off the number of completed items and produce status information.\nI also tend not to subclass Thread, but instead just supply a plain Thread instance with a target= parameter and .start() the thread.\nbased on your response, try this: \ndownload_queue = queue.Queue()\n\n\nclass Downloader(threading.Thread):\n def __init__(self,work_queue, original_size):\n super().__init__()\n self.current_job = 0\n self.work_queue = work_queue\n self.queue_size = original_size\n\n def run(self):\n while True:\n try:\n url = self.work_queue.get(False)\n system_call = \"wget -nc -q {0} -O {1}\".format(url,local_file)\n os.system(system_call)\n # the following code is questionable. By the time we get here,\n # many other items may have been taken off the queue. \n self.current_job = int(self.queue_size) - int(self.work_queue.qsize())\n self.percent = (self.current_job / self.queue_size) * 100\n sys.stdout.flush()\n status = (\"\\rDownloading \" + url.split('/')[-1] + \n \" [status: \" + str(self.current_job) + \n \"/\" + str(self.queue_size) + \", \" + \n str(round(self.percent,2)) + \"%]\" ) \n except queue.Empty:\n pass\n finally: \n self.work_queue.task_done()\n\n\n\n\ndef main:\n if download_queue.qsize() > 0:\n original_size = download_queue.qsize()\n if options.active_downloads:\n active_downloads = options.active_downloads\n else:\n active_downloads = 3\n for x in range(active_downloads):\n downloader = Downloader(download_queue, original_size)\n downloader.start()\n download_queue.join()\n\n",
"If you'd like to use the multiprocessing module, it includes a very nice parallel imap_unordered, which would reduce your problem to the very elegant:\nimport multiprocessing, sys\n\nclass ParallelDownload:\n def __init__(self, urls, processcount=3):\n self.total_items = len(urls)\n self.pool = multiprocessing.Pool(processcount)\n for n, status in enumerate(self.pool.imap_unordered(self.download, urls)):\n stats = (n, self.total_items, n/self.total_items)\n sys.stdout.write(status + \" [%d/%d = %0.2f %%]\\n\"%stats)\n\n\n def download(self, url):\n system_call = \"wget -nc -q {0} -O {1}\".format(url, local_file)\n os.system(system_call)\n status = \"\\rDownloaded \" + url.split('/')[-1]\n return status\n\n"
] |
[
4,
2
] |
[] |
[] |
[
"multithreading",
"python",
"queue"
] |
stackoverflow_0002299478_multithreading_python_queue.txt
|
Q:
Opinions on Unladen Swallow?
What are your opinions and expectations on Google's Unladen Swallow? From their project plan:
We want to make Python faster, but we
also want to make it easy for large,
well-established applications to
switch to Unladen Swallow.
Produce a version of Python at least 5x faster than CPython.
Python application performance should be stable.
Maintain source-level compatibility with CPython
applications.
Maintain source-level compatibility with CPython extension
modules.
We do not want to maintain a Python implementation forever; we view
our work as a branch, not a fork.
And even sweeter:
In addition, we intend to remove the
GIL and fix the state of
multithreading in Python. We believe
this is possible through the
implementation of a more sophisticated
GC
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
Jesse Noller: "Pycon: Unladen-Swallow"
ArsTechnica: "Google searches for holy grail of Python performance"
Update: as DNS pointed out, there was related question: What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
A:
I have high hopes for it.
This is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.
Off the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.
Most importantly, they have a working version. They're using a version of unladen swallow right now for Youtube stuff.
They seem to have their shit together. They have a relatively detailed plan for a project at this stage, and they have a list of tests they use to gauge performance improvements and regressions.
I'm not holding my breath on GIL removal, but even if they never get around to that, the speed increases alone make it awesome.
A:
I'm sorry to disappoint you, but when you read PEP 3146 things look bad.
The improvement is by now minimal and therfore the compiler-code gets more complicated.
Also removing the GIL has many downsides.
Btw. PyPy seems to be faster then Unladen Swallow in some tests.
A:
I think the project has noble goals and with enough time (2-3 years), they will probably reach most of them.
They may not be able to merge their branch back into the trunk because Guido's current view is that cpython should be a reference implementation (ie. it shouldn't do things that are impossible for IronPython and jython to copy.) I've seen reports that this is what kept the cool parts of stackless from being merged into cpython.
A:
This question discussed many of the same things. My opinion is that it sounds great, but I'm waiting to see what it looks like, and how long it takes to become stable.
I'm particularly concerned with compatibility with existing code and libraries, and how the library-writing community responds to it. Ultimately, aside from personal hobby projects, it's of zero value to me until it can run all my third-party libraries.
A:
Guido just posted an article to his twitter account that is an update to the Jesse Noller article posted earlier. http://jessenoller.com/2010/01/06/unladen-swallow-python-3s-best-feature/. Sounds like they are moving ahead as previously mentioned with python 3.
A:
They have a quarterly release. So not far away, wait and watch, let them come up with some thing more than just a plan.
If it indeed comes to be true, easy to do away with C and C++ even for performance intensive operations.
Even tho' it is a Google sponsored Open Source project, surprisingly doesn't involve Guido anywhere.
A:
I think that a 5 times speed improvement is not all that important for me personally.
It is not an order of magnitude change. Although if you consume CPU power at the scale of Google it can be a worth while investment to have some of your staff work on it.
Many of the speed improvements will likely make it into cpython eventually.
Getting rid of the GIL is interesting in principle but will likely reveal lots of problems with modules that are not thread safe once the GIL is removed.
I do not think I will use Unladen Swallow any time soon but like how giving attention to performance may improve the regular Python versions.
|
Opinions on Unladen Swallow?
|
What are your opinions and expectations on Google's Unladen Swallow? From their project plan:
We want to make Python faster, but we
also want to make it easy for large,
well-established applications to
switch to Unladen Swallow.
Produce a version of Python at least 5x faster than CPython.
Python application performance should be stable.
Maintain source-level compatibility with CPython
applications.
Maintain source-level compatibility with CPython extension
modules.
We do not want to maintain a Python implementation forever; we view
our work as a branch, not a fork.
And even sweeter:
In addition, we intend to remove the
GIL and fix the state of
multithreading in Python. We believe
this is possible through the
implementation of a more sophisticated
GC
It almost looks too good to be true, like the best of PyPy and Stackless combined.
More info:
Jesse Noller: "Pycon: Unladen-Swallow"
ArsTechnica: "Google searches for holy grail of Python performance"
Update: as DNS pointed out, there was related question: What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
|
[
"I have high hopes for it.\n\nThis is being worked on by several people from Google. Seeing as how the BDFL is also employed there, this is a positive.\nOff the bat, they state that this is a branch, and not a fork. As such, it's within the realm of possibility that this will eventually get merged into trunk.\nMost importantly, they have a working version. They're using a version of unladen swallow right now for Youtube stuff.\n\nThey seem to have their shit together. They have a relatively detailed plan for a project at this stage, and they have a list of tests they use to gauge performance improvements and regressions.\nI'm not holding my breath on GIL removal, but even if they never get around to that, the speed increases alone make it awesome.\n",
"I'm sorry to disappoint you, but when you read PEP 3146 things look bad.\nThe improvement is by now minimal and therfore the compiler-code gets more complicated.\nAlso removing the GIL has many downsides.\nBtw. PyPy seems to be faster then Unladen Swallow in some tests.\n",
"I think the project has noble goals and with enough time (2-3 years), they will probably reach most of them.\nThey may not be able to merge their branch back into the trunk because Guido's current view is that cpython should be a reference implementation (ie. it shouldn't do things that are impossible for IronPython and jython to copy.) I've seen reports that this is what kept the cool parts of stackless from being merged into cpython.\n",
"This question discussed many of the same things. My opinion is that it sounds great, but I'm waiting to see what it looks like, and how long it takes to become stable.\nI'm particularly concerned with compatibility with existing code and libraries, and how the library-writing community responds to it. Ultimately, aside from personal hobby projects, it's of zero value to me until it can run all my third-party libraries.\n",
"Guido just posted an article to his twitter account that is an update to the Jesse Noller article posted earlier. http://jessenoller.com/2010/01/06/unladen-swallow-python-3s-best-feature/. Sounds like they are moving ahead as previously mentioned with python 3.\n",
"They have a quarterly release. So not far away, wait and watch, let them come up with some thing more than just a plan.\nIf it indeed comes to be true, easy to do away with C and C++ even for performance intensive operations.\nEven tho' it is a Google sponsored Open Source project, surprisingly doesn't involve Guido anywhere.\n",
"I think that a 5 times speed improvement is not all that important for me personally.\nIt is not an order of magnitude change. Although if you consume CPU power at the scale of Google it can be a worth while investment to have some of your staff work on it.\nMany of the speed improvements will likely make it into cpython eventually.\nGetting rid of the GIL is interesting in principle but will likely reveal lots of problems with modules that are not thread safe once the GIL is removed.\nI do not think I will use Unladen Swallow any time soon but like how giving attention to performance may improve the regular Python versions.\n"
] |
[
17,
12,
4,
4,
1,
0,
0
] |
[] |
[] |
[
"llvm",
"python",
"unladen_swallow"
] |
stackoverflow_0000714242_llvm_python_unladen_swallow.txt
|
Q:
How to I extract floats from a file in Python?
So, I have a file that looks like this:
# 3e98.mtz MR_AUTO with model 200la_.pdb
SPACegroup HALL P 2yb #P 1 21 1
SOLU SET RFZ=3.0 TFZ=4.7 PAK=0 LLG=30
SOLU 6DIM ENSE 200la_ EULER 321.997 124.066 234.744 FRAC -0.14681 0.50245 -0.05722
SOLU SET RFZ=3.3 TFZ=4.2 PAK=0 LLG=30
SOLU 6DIM ENSE 200la_ EULER 329.492 34.325 209.775 FRAC 0.70297 0.00106 -0.24023
SOLU SET RFZ=3.6 TFZ=3.6 PAK=0 LLG=30
SOLU 6DIM ENSE 200la_ EULER 177.344 78.287 187.356 FRAC 0.04890 0.00090 -0.57497
What's the best way to iterate through this file and extract only the floating point numbers?
The 'best' scenario in this case, would be extracting only the numbers similar to "321.997" (which are virus cell structure coordinates) and adding them to a list. In each file that I am looking at, there is 6 numbers like that in each line. After I pull those numbers, I can use the list in a method I've already written to calculate new coordinates for rotating the cell structure to match others in a data set.
A:
Here's one way.
def floats( aList ):
for v in aList:
try:
yield float(v)
except ValueError:
pass
a = list( floats( [....] ) )
A:
floats = []
all = ['#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb', '#P', '1', '21', '1', 'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722', 'SOLU', 'SET', 'RFZ=3.3', 'TFZ=4.2', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '329.492', '34.325', '209.775', 'FRAC', '0.70297', '0.00106', '-0.24023', 'SOLU', 'SET', 'RFZ=3.6', 'TFZ=3.6', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '177.344', '78.287', '187.356', 'FRAC', '0.04890', '0.00090', '-0.57497']
for element in all:
try:
floats.append(float(element))
except ValueError:
pass
A:
def is_float(i):
try:
float(i)
return True
except ValueError:
return False
L=['#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb', '#P', '1', '21', '1', 'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722', 'SOLU', 'SET', 'RFZ=3.3', 'TFZ=4.2', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '329.492', '34.325', '209.775', 'FRAC', '0.70297', '0.00106', '-0.24023', 'SOLU', 'SET', 'RFZ=3.6', 'TFZ=3.6', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '177.344', '78.287', '187.356', 'FRAC', '0.04890', '0.00090', '-0.57497']
print filter(is_float,L)
A:
If you display your input in a manner that discourages answerers from examining its structure, and you ask questions like "how do I extract only the floating point numbers", and bury useful information like "In each file that I am looking at, there is 6 numbers like that in each line" in comments, you will get knee-jerk answers providing exactly what you asked for: a list of "floats" that includes 3 spurious numbers (1.0, 21.0, and 1.0) at the front of the list.
If you display your data in a slightly more congenial fashion, like:
alist = [
'#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb',
'#P', '1', '21', '1',
'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_',
'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722',
'SOLU', 'SET', 'RFZ=3.3', 'TFZ=4.2', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_',
'EULER', '329.492', '34.325', '209.775', 'FRAC', '0.70297', '0.00106', '-0.24023',
'SOLU', 'SET', 'RFZ=3.6', 'TFZ=3.6', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_',
'EULER', '177.344', '78.287', '187.356', 'FRAC', '0.04890', '0.00090', '-0.57497'
]
there is some chance that people will notice the structure (EULER followed by three numbers then FRAC followed by three numbers) repeated and go "Oho, six numbers per line in his file" and come back with some more useful advice, like:
Start at the beginning, tell us what your file structure is. There is likely to be a better way of getting your information than smashing your file into a list of strings and then attempting to recover from that.
Update In the meantime, here is an answer that uses the structure that is evident in your data and comments and will be more debuggable if there are variations in the structure:
TAG0 = 'EULER'
TAG1 = 'FRAC'
def extract_rows(tokens):
pos = 0
while True:
try:
pos = tokens.index(TAG0, pos)
except ValueError:
return
assert pos + 8 <= len(tokens)
assert tokens[pos+4] == TAG1
yield (
tuple(map(float, tokens[pos+1:pos+4])),
tuple(map(float, tokens[pos+5:pos+8])),
)
pos += 8
for rowx, row in enumerate (extract_rows(alist)):
print rowx, 'TAG0', row[0]
print rowx, 'TAG1', row[1]
Results:
0 TAG0 (321.99700000000001, 124.066, 234.744)
0 TAG1 (-0.14681, 0.50244999999999995, -0.05722)
1 TAG0 (329.49200000000002, 34.325000000000003, 209.77500000000001)
1 TAG1 (0.70296999999999998, 0.00106, -0.24023)
2 TAG0 (177.34399999999999, 78.287000000000006, 187.35599999999999)
2 TAG1 (0.048899999999999999, 0.00089999999999999998, -0.57496999999999998)
Update 2 Based on your example file, the following simple code (untested) should do what you want:
for line in open('my_file.txt'):
row = line.split()
if row[0] == 'SOLU' and row[1] == '6DIM' and row[4] == 'EULER' and row[8] == 'FRAC':
euler = map(float, row[5:8])
frac = map(float, row[9:12])
do_something_with(euler, frac)
Note: it's only a coincidence that what you are looking for is "all of the floating point numbers" (which ignores the floating point numbers in RFZ=3.0 TFZ=4.7 anyway!). What you have is a file with STRUCTURE: two types of SOLU records, and you want the 3 numbers that appear after EULER and the 3 after FRAC in the SOLU 6DIM records. You DON'T want a list of all of those numbers and have to split them up again into (3 EULER numbers and 3 FRAC numbers) times N.
|
How to I extract floats from a file in Python?
|
So, I have a file that looks like this:
# 3e98.mtz MR_AUTO with model 200la_.pdb
SPACegroup HALL P 2yb #P 1 21 1
SOLU SET RFZ=3.0 TFZ=4.7 PAK=0 LLG=30
SOLU 6DIM ENSE 200la_ EULER 321.997 124.066 234.744 FRAC -0.14681 0.50245 -0.05722
SOLU SET RFZ=3.3 TFZ=4.2 PAK=0 LLG=30
SOLU 6DIM ENSE 200la_ EULER 329.492 34.325 209.775 FRAC 0.70297 0.00106 -0.24023
SOLU SET RFZ=3.6 TFZ=3.6 PAK=0 LLG=30
SOLU 6DIM ENSE 200la_ EULER 177.344 78.287 187.356 FRAC 0.04890 0.00090 -0.57497
What's the best way to iterate through this file and extract only the floating point numbers?
The 'best' scenario in this case, would be extracting only the numbers similar to "321.997" (which are virus cell structure coordinates) and adding them to a list. In each file that I am looking at, there is 6 numbers like that in each line. After I pull those numbers, I can use the list in a method I've already written to calculate new coordinates for rotating the cell structure to match others in a data set.
|
[
"Here's one way.\ndef floats( aList ):\n for v in aList:\n try:\n yield float(v)\n except ValueError:\n pass\n\na = list( floats( [....] ) )\n\n",
"floats = []\nall = ['#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb', '#P', '1', '21', '1', 'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722', 'SOLU', 'SET', 'RFZ=3.3', 'TFZ=4.2', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '329.492', '34.325', '209.775', 'FRAC', '0.70297', '0.00106', '-0.24023', 'SOLU', 'SET', 'RFZ=3.6', 'TFZ=3.6', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '177.344', '78.287', '187.356', 'FRAC', '0.04890', '0.00090', '-0.57497']\nfor element in all:\n try:\n floats.append(float(element))\n except ValueError:\n pass\n\n",
"def is_float(i):\n try:\n float(i)\n return True\n except ValueError:\n return False\n\n\nL=['#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb', '#P', '1', '21', '1', 'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722', 'SOLU', 'SET', 'RFZ=3.3', 'TFZ=4.2', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '329.492', '34.325', '209.775', 'FRAC', '0.70297', '0.00106', '-0.24023', 'SOLU', 'SET', 'RFZ=3.6', 'TFZ=3.6', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', 'EULER', '177.344', '78.287', '187.356', 'FRAC', '0.04890', '0.00090', '-0.57497']\nprint filter(is_float,L)\n\n",
"If you display your input in a manner that discourages answerers from examining its structure, and you ask questions like \"how do I extract only the floating point numbers\", and bury useful information like \"In each file that I am looking at, there is 6 numbers like that in each line\" in comments, you will get knee-jerk answers providing exactly what you asked for: a list of \"floats\" that includes 3 spurious numbers (1.0, 21.0, and 1.0) at the front of the list.\nIf you display your data in a slightly more congenial fashion, like:\nalist = [\n '#', '3e98.mtz', 'MR_AUTO', 'with', 'model', '200la_.pdb', 'SPACegroup', 'HALL', 'P', '2yb',\n '#P', '1', '21', '1', \n 'SOLU', 'SET', 'RFZ=3.0', 'TFZ=4.7', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_',\n 'EULER', '321.997', '124.066', '234.744', 'FRAC', '-0.14681', '0.50245', '-0.05722',\n 'SOLU', 'SET', 'RFZ=3.3', 'TFZ=4.2', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_',\n 'EULER', '329.492', '34.325', '209.775', 'FRAC', '0.70297', '0.00106', '-0.24023',\n 'SOLU', 'SET', 'RFZ=3.6', 'TFZ=3.6', 'PAK=0', 'LLG=30', 'SOLU', '6DIM', 'ENSE', '200la_', \n 'EULER', '177.344', '78.287', '187.356', 'FRAC', '0.04890', '0.00090', '-0.57497'\n ]\n\nthere is some chance that people will notice the structure (EULER followed by three numbers then FRAC followed by three numbers) repeated and go \"Oho, six numbers per line in his file\" and come back with some more useful advice, like:\nStart at the beginning, tell us what your file structure is. There is likely to be a better way of getting your information than smashing your file into a list of strings and then attempting to recover from that.\nUpdate In the meantime, here is an answer that uses the structure that is evident in your data and comments and will be more debuggable if there are variations in the structure:\nTAG0 = 'EULER'\nTAG1 = 'FRAC'\n\ndef extract_rows(tokens):\n pos = 0\n while True:\n try:\n pos = tokens.index(TAG0, pos)\n except ValueError:\n return\n assert pos + 8 <= len(tokens)\n assert tokens[pos+4] == TAG1\n yield (\n tuple(map(float, tokens[pos+1:pos+4])),\n tuple(map(float, tokens[pos+5:pos+8])),\n )\n pos += 8\n\nfor rowx, row in enumerate (extract_rows(alist)):\n print rowx, 'TAG0', row[0]\n print rowx, 'TAG1', row[1]\n\nResults:\n0 TAG0 (321.99700000000001, 124.066, 234.744)\n0 TAG1 (-0.14681, 0.50244999999999995, -0.05722)\n1 TAG0 (329.49200000000002, 34.325000000000003, 209.77500000000001)\n1 TAG1 (0.70296999999999998, 0.00106, -0.24023)\n2 TAG0 (177.34399999999999, 78.287000000000006, 187.35599999999999)\n2 TAG1 (0.048899999999999999, 0.00089999999999999998, -0.57496999999999998)\n\nUpdate 2 Based on your example file, the following simple code (untested) should do what you want:\nfor line in open('my_file.txt'):\n row = line.split()\n if row[0] == 'SOLU' and row[1] == '6DIM' and row[4] == 'EULER' and row[8] == 'FRAC':\n euler = map(float, row[5:8])\n frac = map(float, row[9:12])\n do_something_with(euler, frac)\n\nNote: it's only a coincidence that what you are looking for is \"all of the floating point numbers\" (which ignores the floating point numbers in RFZ=3.0 TFZ=4.7 anyway!). What you have is a file with STRUCTURE: two types of SOLU records, and you want the 3 numbers that appear after EULER and the 3 after FRAC in the SOLU 6DIM records. You DON'T want a list of all of those numbers and have to split them up again into (3 EULER numbers and 3 FRAC numbers) times N.\n"
] |
[
11,
7,
3,
0
] |
[] |
[] |
[
"floating_point",
"list",
"loops",
"python"
] |
stackoverflow_0002299609_floating_point_list_loops_python.txt
|
Q:
retrieving the keys of all variables on an object
If I had:
class A(object):
varA = 1
inst = A()
Then how would I retrieve the keys of all variables on inst? I'd want something like ["varA"]
So far, I've gotten this:
vars(inst.__class__).keys() #returns ['__dict__', '__weakref__', '__module__', 'varA', '__doc__']
I'm fine with that, I'd just ignore the double-under vars. My problem is with multiple layers of inheritance like:
class A(object):
varA = 1
class B(A):
varB = 2
inst = B()
vars(inst.__class__).keys() #returns ['__module__', '__doc__', 'varB']
but I want to retrieve both varB and varA. Any idea how I would go about doing this?
I also tried:
vars(super(B, inst).__class__).keys()+vars(inst.__class__).keys()
But that didn't do what I expected.
If it matters, I'm using Python 2.6.
Edit: I actually just stumbled across a very easy way to do this:
dir(inst)
A:
There is a python module, called inspect for runtime introspection. Maybe inspect.getmembers can help you ...
|
retrieving the keys of all variables on an object
|
If I had:
class A(object):
varA = 1
inst = A()
Then how would I retrieve the keys of all variables on inst? I'd want something like ["varA"]
So far, I've gotten this:
vars(inst.__class__).keys() #returns ['__dict__', '__weakref__', '__module__', 'varA', '__doc__']
I'm fine with that, I'd just ignore the double-under vars. My problem is with multiple layers of inheritance like:
class A(object):
varA = 1
class B(A):
varB = 2
inst = B()
vars(inst.__class__).keys() #returns ['__module__', '__doc__', 'varB']
but I want to retrieve both varB and varA. Any idea how I would go about doing this?
I also tried:
vars(super(B, inst).__class__).keys()+vars(inst.__class__).keys()
But that didn't do what I expected.
If it matters, I'm using Python 2.6.
Edit: I actually just stumbled across a very easy way to do this:
dir(inst)
|
[
"There is a python module, called inspect for runtime introspection. Maybe inspect.getmembers can help you ...\n"
] |
[
1
] |
[] |
[] |
[
"class",
"multiple_inheritance",
"python"
] |
stackoverflow_0002300383_class_multiple_inheritance_python.txt
|
Q:
Installing Mercurial 1.4.3 - Python Requirement?
Is it ok if I install Python 2.6.4 instead of the 2.4 requirement listed on the Mercurial website?
I'm fairly new to Mercurial and Python. My general impression of Python is that newer versions break compatibility with older versions.
If Python is currently at 2.6.4 and Mercurial 1.4.3 lists Python 2.4 as a requirement, maybe they are strictly limiting to Python 2.4 only?
A:
2.4 is a minimum requirement. 2.6.4 is fine.
|
Installing Mercurial 1.4.3 - Python Requirement?
|
Is it ok if I install Python 2.6.4 instead of the 2.4 requirement listed on the Mercurial website?
I'm fairly new to Mercurial and Python. My general impression of Python is that newer versions break compatibility with older versions.
If Python is currently at 2.6.4 and Mercurial 1.4.3 lists Python 2.4 as a requirement, maybe they are strictly limiting to Python 2.4 only?
|
[
"2.4 is a minimum requirement. 2.6.4 is fine.\n"
] |
[
4
] |
[] |
[] |
[
"mercurial",
"python"
] |
stackoverflow_0002300636_mercurial_python.txt
|
Q:
If you are really good at Python and Regex, please help fix function
def boldword(text, needle):
return mark_safe(re.compile(r"\b(%s)\b" % "|".join(map(re.escape, needle.split(' '))), re.I).sub(r'<strong>\1</strong>', text))
This is currently my function to bold a string text given a needle. (Like Google...they bold the text for you when you do a search).
When the needle is "the show", it will not highlight "www.theshow.com".
When the needle is "my show (video)", it will not highlight "my show (video)"...it only highlights my show.
When the needle is "apple's ipad", it will not highlight "apple ipad"...it only highlights ipad.
Expected output:
www.theshow.com
,Current output:
www.theshow.com
Expected output:
my show (video)
,Current output:
my show (video)
Expected:
apple ipad
,Current:
apple ipad
I think the main problem is when I'm splitting the space vs other punctuation. right?
Can someone modify my current function to take into account those factors?
Thanks
A:
Your biggest problem seems to be the word boundaries. If the tokens you're searching for can begin or end with non-word characters (e.g., (video)), enclosing the regex in \b prevents matching. They also prevent matching of two or more contiguous tokens (e.g., theshow in www.theshow.com). However, instead of losing the word boundaries, I suggest you ignore punctuation characters in the search expression and construct the regex so as to match one or more tokens at a time:
re.compile(r"\b((?:%s)+)\b" % "|".join(re.split(r"\W+", needle)), re.I)
Splitting on /\W+/ removes all punctuation as well as whitespace, so there's no need to escape anything. My results seem to match the ones you wanted, except the parentheses in (video) are not highlighted, only the word video is. If the search expression is "the show", it highlights theshow in www.theshow.com, but not in www.footheshowbar.com.
A:
What your description told me is that A) The input variable isn't being correctly split by spaces and B) It's not being properly escaped.
I think it may be an instance of under parenthesized expressions:
Try this:
return mark_safe(re.compile((r"\b(%s)\b" % ("|".join(map(re.escape, needle.split(' '))), re.I))).sub(r'<strong>\1</strong>', text))
A:
Here's some duct tape I added to help you pass the cases you listed -- this problem is actually pretty interesting. There are probably some cases that won't be correct (e.g. Google will highlight duck if you search for ducks, this will only work for duck's).
Without a more general set of guidelines, it is tough to write a regex that will cover every case - but depending on how close you need it to be will ultimately decide on how complex you will need to make it.
import re, string
def boldword(text,needle):
n = re.sub('[%s]s*' % re.escape(string.punctuation), '', needle)
patterns = map(re.escape, n.split(' '))
patterns.append(n.replace(' ', ''))
regex = re.compile(r"\b(%s)\b" % '|'.join(patterns), re.I)
match = re.match(regex, text.replace(' ',''))
if match:
return "<strong>%s</strong>" % text
return re.sub(regex, r'<strong>\1</strong>', text)
print boldword("www.theshow.com", "the show")
print boldword("my show (video)", "my show (video)")
print boldword("apple ipad", "apple's ipad")
print boldword("stack overflow", "stackoverflow")
Output
>> www.<strong>theshow</strong>.com
>> <strong>my</strong> <strong>show</strong> (<strong>video</strong>)
>> <strong>apple ipad</strong>
>> <strong>stack overflow</strong>
|
If you are really good at Python and Regex, please help fix function
|
def boldword(text, needle):
return mark_safe(re.compile(r"\b(%s)\b" % "|".join(map(re.escape, needle.split(' '))), re.I).sub(r'<strong>\1</strong>', text))
This is currently my function to bold a string text given a needle. (Like Google...they bold the text for you when you do a search).
When the needle is "the show", it will not highlight "www.theshow.com".
When the needle is "my show (video)", it will not highlight "my show (video)"...it only highlights my show.
When the needle is "apple's ipad", it will not highlight "apple ipad"...it only highlights ipad.
Expected output:
www.theshow.com
,Current output:
www.theshow.com
Expected output:
my show (video)
,Current output:
my show (video)
Expected:
apple ipad
,Current:
apple ipad
I think the main problem is when I'm splitting the space vs other punctuation. right?
Can someone modify my current function to take into account those factors?
Thanks
|
[
"Your biggest problem seems to be the word boundaries. If the tokens you're searching for can begin or end with non-word characters (e.g., (video)), enclosing the regex in \\b prevents matching. They also prevent matching of two or more contiguous tokens (e.g., theshow in www.theshow.com). However, instead of losing the word boundaries, I suggest you ignore punctuation characters in the search expression and construct the regex so as to match one or more tokens at a time:\nre.compile(r\"\\b((?:%s)+)\\b\" % \"|\".join(re.split(r\"\\W+\", needle)), re.I)\n\nSplitting on /\\W+/ removes all punctuation as well as whitespace, so there's no need to escape anything. My results seem to match the ones you wanted, except the parentheses in (video) are not highlighted, only the word video is. If the search expression is \"the show\", it highlights theshow in www.theshow.com, but not in www.footheshowbar.com.\n",
"What your description told me is that A) The input variable isn't being correctly split by spaces and B) It's not being properly escaped.\nI think it may be an instance of under parenthesized expressions:\nTry this:\nreturn mark_safe(re.compile((r\"\\b(%s)\\b\" % (\"|\".join(map(re.escape, needle.split(' '))), re.I))).sub(r'<strong>\\1</strong>', text))\n\n",
"Here's some duct tape I added to help you pass the cases you listed -- this problem is actually pretty interesting. There are probably some cases that won't be correct (e.g. Google will highlight duck if you search for ducks, this will only work for duck's).\nWithout a more general set of guidelines, it is tough to write a regex that will cover every case - but depending on how close you need it to be will ultimately decide on how complex you will need to make it.\nimport re, string\n\ndef boldword(text,needle):\n n = re.sub('[%s]s*' % re.escape(string.punctuation), '', needle)\n patterns = map(re.escape, n.split(' '))\n patterns.append(n.replace(' ', ''))\n regex = re.compile(r\"\\b(%s)\\b\" % '|'.join(patterns), re.I)\n match = re.match(regex, text.replace(' ',''))\n if match:\n return \"<strong>%s</strong>\" % text\n return re.sub(regex, r'<strong>\\1</strong>', text)\n\nprint boldword(\"www.theshow.com\", \"the show\")\nprint boldword(\"my show (video)\", \"my show (video)\")\nprint boldword(\"apple ipad\", \"apple's ipad\")\nprint boldword(\"stack overflow\", \"stackoverflow\")\n\nOutput\n>> www.<strong>theshow</strong>.com\n>> <strong>my</strong> <strong>show</strong> (<strong>video</strong>)\n>> <strong>apple ipad</strong>\n>> <strong>stack overflow</strong>\n\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002300563_python_regex.txt
|
Q:
Problem in calculating checksum : casting int to signed int32
I need to convert the following c code (to calculate checksum for a file) to python. I had written, the corresponding code in python but the result didn't match the c version. The problem was that python autmatically promotes int to long whenever overflow occurs and this results in wrong checksums.
Any idea how to overcome this problem ? or is there a python function that converts long to signed int32 ?
Thanks
int calcChecksum(const guchar *data, gsize len)
{
const guchar *p = data;
int checksum = 0, g, i = len;
while(i--) {
checksum = (checksum << 4) + *p++;
if((g = (checksum & 0xf0000000)) != 0)
checksum ^= g >> 23;
checksum &= ~g;
}
return checksum;
}
Solution:
Thanks for all the help. Here's the function that worked for me -
def int32(x):
x = 0xffffffff & x
if x > 0x7fffffff :
return - ( ~(x - 1) & 0xffffffff )
else : return x
A:
Use numpy.int32 or numpy.uint32 if you need to restrict the range. Or mod it by 1 << 32 after operations that could "overflow".
|
Problem in calculating checksum : casting int to signed int32
|
I need to convert the following c code (to calculate checksum for a file) to python. I had written, the corresponding code in python but the result didn't match the c version. The problem was that python autmatically promotes int to long whenever overflow occurs and this results in wrong checksums.
Any idea how to overcome this problem ? or is there a python function that converts long to signed int32 ?
Thanks
int calcChecksum(const guchar *data, gsize len)
{
const guchar *p = data;
int checksum = 0, g, i = len;
while(i--) {
checksum = (checksum << 4) + *p++;
if((g = (checksum & 0xf0000000)) != 0)
checksum ^= g >> 23;
checksum &= ~g;
}
return checksum;
}
Solution:
Thanks for all the help. Here's the function that worked for me -
def int32(x):
x = 0xffffffff & x
if x > 0x7fffffff :
return - ( ~(x - 1) & 0xffffffff )
else : return x
|
[
"Use numpy.int32 or numpy.uint32 if you need to restrict the range. Or mod it by 1 << 32 after operations that could \"overflow\".\n"
] |
[
2
] |
[] |
[] |
[
"casting",
"checksum",
"python"
] |
stackoverflow_0002300740_casting_checksum_python.txt
|
Q:
Basic Django - Custom Managers
I'm going through the Django book and I'm currently on chapter 10. I'm having a problem understanding the third line in this fragment of code:
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
I understand that this custom manager instance is overriding the superclass' get_query_set method, but why is the super call passing in both DahlBookManager as well as self? Aren't self and DahlBookManager the same thing?
A:
No, self is an instance of DahlBookManager. super() uses the class to handle things like MRO, inheritance, etc.
A:
This is about the builtin Super() function in Python.
You can get a reference here: http://docs.python.org/library/functions.html
If the second argument is omitted, the
super object returned is unbound.
|
Basic Django - Custom Managers
|
I'm going through the Django book and I'm currently on chapter 10. I'm having a problem understanding the third line in this fragment of code:
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
I understand that this custom manager instance is overriding the superclass' get_query_set method, but why is the super call passing in both DahlBookManager as well as self? Aren't self and DahlBookManager the same thing?
|
[
"No, self is an instance of DahlBookManager. super() uses the class to handle things like MRO, inheritance, etc.\n",
"This is about the builtin Super() function in Python.\nYou can get a reference here: http://docs.python.org/library/functions.html\n\nIf the second argument is omitted, the\n super object returned is unbound.\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002300737_django_python.txt
|
Q:
Using list.reverse() on a subset of a list. "NoneType" object is not iterable
So, I'm trying to append to one list the reverse of a subset of another list. For some reason, the interpreter doesn't seem to be liking it. Here's what I'm doing.
list1.extend(list2[someInt:someOtherInt].reverse())
Why is this not legit? It seems reasonable to me..
A:
list methods operate in-place, which means that they return None.
A:
In addition to Ignacio's answer, here's a solution. Try:
list1.extend(reversed(list2[someInt:someOtherInt]))
Alternatively, you can use a slice with reversed indexes, but be careful with off-by-one errors!
list1.extend(list2[someOtherInt - 1: someInt - 1: -1])
It's probably better to stick to the first method, especially as the second method will fail with 0 indexes.
Related to reversed, another trick is instead of list1.sort() you can use sorted(list1).
|
Using list.reverse() on a subset of a list. "NoneType" object is not iterable
|
So, I'm trying to append to one list the reverse of a subset of another list. For some reason, the interpreter doesn't seem to be liking it. Here's what I'm doing.
list1.extend(list2[someInt:someOtherInt].reverse())
Why is this not legit? It seems reasonable to me..
|
[
"list methods operate in-place, which means that they return None.\n",
"In addition to Ignacio's answer, here's a solution. Try:\nlist1.extend(reversed(list2[someInt:someOtherInt]))\n\nAlternatively, you can use a slice with reversed indexes, but be careful with off-by-one errors!\nlist1.extend(list2[someOtherInt - 1: someInt - 1: -1])\n\nIt's probably better to stick to the first method, especially as the second method will fail with 0 indexes.\nRelated to reversed, another trick is instead of list1.sort() you can use sorted(list1).\n"
] |
[
5,
3
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002300872_list_python.txt
|
Q:
Maintaining session in an Eventlet page scraper?
I'm trying to do some scraping of a site that requires authentication (not http auth). The script I'm using is based on this eventlet example. Basically,
urls = ["https://mysecuresite.com/data.aspx?itemid=blah1",
"https://mysecuresite.com/data.aspx?itemid=blah2",
"https://mysecuresite.com/data.aspx?itemid=blah3"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
print "opening", url
body = urllib2.urlopen(url).read()
print "done with", url
return url, body
pool = eventlet.GreenPool(10)
for url, body in pool.imap(fetch, urls):
print "got body from", url, "of length", len(body)
Establishing the session is not simple at all; I have to load the login page, extract some variables from the login form, then send a POST request with the auth details and those variables. After the session is good, the rest of the requests are simple GET requests.
Using the above code as a reference point, how would I create a session that the rest of the pool would use? (I need the subsequent requests to be made in parallel)
A:
I'm not an expert on this by any means, but it looks like the standard way to maintain session state with urllib2 is to create a custom opener instance for each session. That looks like this:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
Then you use that opener to do whatever authentication you have to, and all the session state will remain within the opener object itself. Then you can pass the opener object as an argument for the parallel requests.
Here is an example script that logs in to secondlife.com for multiple users in parallel, and makes multiple page requests for each user, also in parallel. The login procedure for this particular site is tricky because it involves capturing a CSRF token from the first request before being able to log in with the second. For that reason, the login method is quite messy. The principle should be the same, though, for whatever site you're interested in.
import eventlet
from eventlet.green import urllib2
import re
login_url = 'https://secure-web28.secondlife.com/my/account/login.php?lang=en&type=second-life-member&nextpage=/my/index.php?lang=en'
pool = eventlet.GreenPool(10)
def fetch_title(opener, url):
match = re.search(r'<title>(.*)</title>', opener.open(url).read())
if match:
return match.group(1)
else:
return "no title"
def login(login_url, fullname, password):
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
login_page = opener.open(login_url).read()
csrf_token = re.search(r'<input type="hidden" name="CSRFToken" value="(.*)"/>', login_page).group(1)
username, lastname = fullname.split()
auth = "CSRFToken=%s&form[type]=second-life-member&form[nextpage]=/my/index.php?lang=en&form[persistent]=Y&form[form_action]=Log%%20In&form[form_lang]=en&form[username]=%s&form[lastname]=%s&form[password]=%s&submit=Submit" % (
csrf_token, username, lastname, password)
logged_in = opener.open(login_url, auth).read()
return opener
def login_and_fetch(login_url, fullname, password, page_urls):
opener = login(login_url, fullname, password)
# note that this deliberately uses the global pool
pile = eventlet.GreenPile(pool)
for url in page_urls:
pile.spawn(fetch_title, opener, url)
return pile
login_urls = [login_url] *2
usernames = [...]
passwords = [...]
page_urls = [['https://secure-web28.secondlife.com/my/account/?lang=en-US',
'https://secure-web28.secondlife.com/my/community/events/index.php?lang=en-US']] * 2
for user_iter in pool.imap(login_and_fetch, login_urls, usernames, passwords, page_urls):
for title in user_iter:
print "got title", title
A:
Like suggested below, use mechanize. It'll take care of the low-level details, like cookie management for you.
However, to make a 3rd party library work with eventlet you need to replace socket and ssl objects from stdlib with something that is asynchronous under the hood.
This is doable in eventlet, but it's not very straightforward here.
I recommend using gevent, where all you have to do is
from gevent import monkey; monkey.patch_all()
and then 3rd party libraries should just work.
Here's an example.
A:
You can use the mechanize library to make the session establishing easier, then use one of the different threading/multiprocessing techniques like this threading pool recipe (first hit on Google, probably a bit overkill, make sure you read the comments).
|
Maintaining session in an Eventlet page scraper?
|
I'm trying to do some scraping of a site that requires authentication (not http auth). The script I'm using is based on this eventlet example. Basically,
urls = ["https://mysecuresite.com/data.aspx?itemid=blah1",
"https://mysecuresite.com/data.aspx?itemid=blah2",
"https://mysecuresite.com/data.aspx?itemid=blah3"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
print "opening", url
body = urllib2.urlopen(url).read()
print "done with", url
return url, body
pool = eventlet.GreenPool(10)
for url, body in pool.imap(fetch, urls):
print "got body from", url, "of length", len(body)
Establishing the session is not simple at all; I have to load the login page, extract some variables from the login form, then send a POST request with the auth details and those variables. After the session is good, the rest of the requests are simple GET requests.
Using the above code as a reference point, how would I create a session that the rest of the pool would use? (I need the subsequent requests to be made in parallel)
|
[
"I'm not an expert on this by any means, but it looks like the standard way to maintain session state with urllib2 is to create a custom opener instance for each session. That looks like this:\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor())\n\nThen you use that opener to do whatever authentication you have to, and all the session state will remain within the opener object itself. Then you can pass the opener object as an argument for the parallel requests.\nHere is an example script that logs in to secondlife.com for multiple users in parallel, and makes multiple page requests for each user, also in parallel. The login procedure for this particular site is tricky because it involves capturing a CSRF token from the first request before being able to log in with the second. For that reason, the login method is quite messy. The principle should be the same, though, for whatever site you're interested in.\nimport eventlet\nfrom eventlet.green import urllib2\nimport re\n\nlogin_url = 'https://secure-web28.secondlife.com/my/account/login.php?lang=en&type=second-life-member&nextpage=/my/index.php?lang=en'\n\npool = eventlet.GreenPool(10)\n\ndef fetch_title(opener, url):\n match = re.search(r'<title>(.*)</title>', opener.open(url).read())\n if match:\n return match.group(1)\n else:\n return \"no title\"\n\ndef login(login_url, fullname, password):\n opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())\n login_page = opener.open(login_url).read()\n csrf_token = re.search(r'<input type=\"hidden\" name=\"CSRFToken\" value=\"(.*)\"/>', login_page).group(1)\n username, lastname = fullname.split()\n auth = \"CSRFToken=%s&form[type]=second-life-member&form[nextpage]=/my/index.php?lang=en&form[persistent]=Y&form[form_action]=Log%%20In&form[form_lang]=en&form[username]=%s&form[lastname]=%s&form[password]=%s&submit=Submit\" % (\n csrf_token, username, lastname, password)\n logged_in = opener.open(login_url, auth).read()\n return opener\n\n\ndef login_and_fetch(login_url, fullname, password, page_urls):\n opener = login(login_url, fullname, password)\n # note that this deliberately uses the global pool\n pile = eventlet.GreenPile(pool)\n for url in page_urls:\n pile.spawn(fetch_title, opener, url)\n\n return pile\n\nlogin_urls = [login_url] *2\nusernames = [...]\npasswords = [...]\npage_urls = [['https://secure-web28.secondlife.com/my/account/?lang=en-US',\n 'https://secure-web28.secondlife.com/my/community/events/index.php?lang=en-US']] * 2\n\nfor user_iter in pool.imap(login_and_fetch, login_urls, usernames, passwords, page_urls):\n for title in user_iter:\n print \"got title\", title\n\n",
"Like suggested below, use mechanize. It'll take care of the low-level details, like cookie management for you. \nHowever, to make a 3rd party library work with eventlet you need to replace socket and ssl objects from stdlib with something that is asynchronous under the hood.\nThis is doable in eventlet, but it's not very straightforward here. \nI recommend using gevent, where all you have to do is \n\nfrom gevent import monkey; monkey.patch_all()\n\nand then 3rd party libraries should just work.\nHere's an example.\n",
"You can use the mechanize library to make the session establishing easier, then use one of the different threading/multiprocessing techniques like this threading pool recipe (first hit on Google, probably a bit overkill, make sure you read the comments).\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"parallel_processing",
"python",
"screen_scraping"
] |
stackoverflow_0002294869_parallel_processing_python_screen_scraping.txt
|
Q:
python - syntax error
Hi:) I am not able to figure out what the error in the program is could you please help me out with it. Thank you..:)
The input file contains the following:
3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है।
57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्देश्य से असम आए।
( its basically sample sentences for which i need to get word positions in the output appended to each word in hindi)
for e.g the output for the first sentence would look like this:
3. भारत(1) का(2) इतिहास(3) काफी(4) समृद्ध(5) एवं(6) विस्तृत(7) है(8) ।(9)
I should get a similar op for the following sentence(s)
The code looks like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
separators = [u'।', ',', '.']
text = open("hinstest1.txt").read()
#This converts the encoded text to an internal unicode object, where
# all characters are properly recognized as an entity:
text = text.decode("UTF-8")
#this breaks the text on the white spaces, yielding a list of words:
words = text.split()
counter = 1
output = ""
#if the last char is a separator, and is joined to the word:
for word in words:
if word[-1] in separators and len(word) > 1:
#word up to the second to last char:
output += word[:-1] + u'(%d) ' % counter
counter += 1
#last char
output += word[-1] + u'(%d) ' % counter
else:
output += word + u'(%d) ' % counter
counter += 1
print output
The error I am getting is:
File "pyth_hinwp.py", line 22
output += word[-1] + u'(%d) ' % counter
^
SyntaxError: invalid syntax
I know this question is something similar to what I have asked earlier, but since I am not able to successfully execute some of the answers given to me earlier hence I am kinda restructuring the question to the place where I am currently getting stuck.
A:
What is posted here does not have the error. Note that what is posted has TWO space characters between the + and the u in output += word[-1] + u'(%d) ' % counter. What is probably happening is that you have a whitespace character other than a space in there. A possibility is NBSP (U+00A0) aka "no-break space". What SO does to format your code is likely to scrub away such things.
Diagnosis: At the Python interactive prompt, type
open("pyth_hinwp.py").readlines()[22-1]
What do you see between the + and the u?
Fix: in your editor, delete both characters between the + and the u. Insert a single space.
By the way, with a syntax error, the problem is entirely within the named SOURCE file; the code has not been run (because it couldn't be compiled) and so what is in your INPUT file has no bearing on the problem.
A:
If you have syntax error, your editor may be showing it before even running it? I any case why don't you try removing that char where error is being indicated, because I am not able to replicate problem, after copying your code.
|
python - syntax error
|
Hi:) I am not able to figure out what the error in the program is could you please help me out with it. Thank you..:)
The input file contains the following:
3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है।
57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्देश्य से असम आए।
( its basically sample sentences for which i need to get word positions in the output appended to each word in hindi)
for e.g the output for the first sentence would look like this:
3. भारत(1) का(2) इतिहास(3) काफी(4) समृद्ध(5) एवं(6) विस्तृत(7) है(8) ।(9)
I should get a similar op for the following sentence(s)
The code looks like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
separators = [u'।', ',', '.']
text = open("hinstest1.txt").read()
#This converts the encoded text to an internal unicode object, where
# all characters are properly recognized as an entity:
text = text.decode("UTF-8")
#this breaks the text on the white spaces, yielding a list of words:
words = text.split()
counter = 1
output = ""
#if the last char is a separator, and is joined to the word:
for word in words:
if word[-1] in separators and len(word) > 1:
#word up to the second to last char:
output += word[:-1] + u'(%d) ' % counter
counter += 1
#last char
output += word[-1] + u'(%d) ' % counter
else:
output += word + u'(%d) ' % counter
counter += 1
print output
The error I am getting is:
File "pyth_hinwp.py", line 22
output += word[-1] + u'(%d) ' % counter
^
SyntaxError: invalid syntax
I know this question is something similar to what I have asked earlier, but since I am not able to successfully execute some of the answers given to me earlier hence I am kinda restructuring the question to the place where I am currently getting stuck.
|
[
"What is posted here does not have the error. Note that what is posted has TWO space characters between the + and the u in output += word[-1] + u'(%d) ' % counter. What is probably happening is that you have a whitespace character other than a space in there. A possibility is NBSP (U+00A0) aka \"no-break space\". What SO does to format your code is likely to scrub away such things.\nDiagnosis: At the Python interactive prompt, type\nopen(\"pyth_hinwp.py\").readlines()[22-1]\n\nWhat do you see between the + and the u?\nFix: in your editor, delete both characters between the + and the u. Insert a single space.\nBy the way, with a syntax error, the problem is entirely within the named SOURCE file; the code has not been run (because it couldn't be compiled) and so what is in your INPUT file has no bearing on the problem.\n",
"If you have syntax error, your editor may be showing it before even running it? I any case why don't you try removing that char where error is being indicated, because I am not able to replicate problem, after copying your code.\n"
] |
[
3,
0
] |
[] |
[] |
[
"nlp",
"python"
] |
stackoverflow_0002301214_nlp_python.txt
|
Q:
Bash alias to Python script -- is it possible?
The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by taking my ideas and making them Python scripts.
Coincident with this idea is another notion I had to make a feature of legacy Mac OS (officially known as "OS 9" or "Classic") pertaining to downloads platform-independent: writing the URL to some part of the file visible from one's file navigator {Konqueror, Dolphin, Nautilus, Finder or Explorer}. I know that only a scant few file types support this kind of thing using some other command-line tools (exiv2, wrjpgcom, etc). Which is perfectly fine with me as I only use this alias to download single-page image files such as JPEGs anyways.
I reckon I might as well take full advantage of the power of Python by having the script pass the string which is the source URL of the download (entered by the user and used first by cUrl) to something like exiv2 which could write it to the Comment block, EXIF User Comment block, and (taking as a first and worst example) Windows XP's File Description field. Starting small is sometimes a good way to start.
Hope someone has advice or suggestions.
BZT
A:
The relevant section from the Bash manual states:
Aliases allow a string to be
substituted for a word when it is used
as the first word of a simple command.
So, there should be nothing preventing you from doing e.g.
$ alias geturl="python /some/cool/script.py"
Then you could use it like any other shell command:
$ geturl http://example.com/excitingstuff.jpg
And this would simply call your Python program.
A:
I thought Pycurl might be the answer. Ahh Daniel Sternberg and his innocent presumptions that everybody knows what he does. I asked on the list whether or not pycurl had a "curl -o" analogue, and then asked 'If so: How would one go about coding it/them in a Python script?' His reply was the following:
"curl.setopt(pycurl.WRITEDATA, fp)
possibly combined with:
curl.setopt(pycurl.WRITEFUNCITON, callback) "
...along with Sourceforge links to two revisions of retriever.py. I can barely recall where easy_install put the one I've got; how am I supposed to compare them?
It's pretty apparent this gentleman never had a helpdesk or phone tech support job in the Western Hemisphere, where you have to assume the 'customer' just learned how to use their comb yesterday and be prepared to walk them through everything and anything. One-liners (or three-liners with abstruse links as chasers) don't do it for me.
BZT
|
Bash alias to Python script -- is it possible?
|
The particular alias I'm looking to "class up" into a Python script happens to be one that makes use of the cUrl -o (output to file) option. I suppose I could as easily turn it into a BASH function, but someone advised me that I could avoid the quirks and pitfalls of the different versions and "flavors" of BASH by taking my ideas and making them Python scripts.
Coincident with this idea is another notion I had to make a feature of legacy Mac OS (officially known as "OS 9" or "Classic") pertaining to downloads platform-independent: writing the URL to some part of the file visible from one's file navigator {Konqueror, Dolphin, Nautilus, Finder or Explorer}. I know that only a scant few file types support this kind of thing using some other command-line tools (exiv2, wrjpgcom, etc). Which is perfectly fine with me as I only use this alias to download single-page image files such as JPEGs anyways.
I reckon I might as well take full advantage of the power of Python by having the script pass the string which is the source URL of the download (entered by the user and used first by cUrl) to something like exiv2 which could write it to the Comment block, EXIF User Comment block, and (taking as a first and worst example) Windows XP's File Description field. Starting small is sometimes a good way to start.
Hope someone has advice or suggestions.
BZT
|
[
"The relevant section from the Bash manual states:\n\nAliases allow a string to be\n substituted for a word when it is used\n as the first word of a simple command.\n\nSo, there should be nothing preventing you from doing e.g.\n$ alias geturl=\"python /some/cool/script.py\"\n\nThen you could use it like any other shell command:\n$ geturl http://example.com/excitingstuff.jpg\n\nAnd this would simply call your Python program.\n",
"I thought Pycurl might be the answer. Ahh Daniel Sternberg and his innocent presumptions that everybody knows what he does. I asked on the list whether or not pycurl had a \"curl -o\" analogue, and then asked 'If so: How would one go about coding it/them in a Python script?' His reply was the following:\n\"curl.setopt(pycurl.WRITEDATA, fp)\npossibly combined with:\ncurl.setopt(pycurl.WRITEFUNCITON, callback) \"\n...along with Sourceforge links to two revisions of retriever.py. I can barely recall where easy_install put the one I've got; how am I supposed to compare them?\nIt's pretty apparent this gentleman never had a helpdesk or phone tech support job in the Western Hemisphere, where you have to assume the 'customer' just learned how to use their comb yesterday and be prepared to walk them through everything and anything. One-liners (or three-liners with abstruse links as chasers) don't do it for me.\nBZT\n"
] |
[
18,
0
] |
[] |
[] |
[
"bash",
"curl",
"multiplatform",
"python",
"scripting"
] |
stackoverflow_0002279749_bash_curl_multiplatform_python_scripting.txt
|
Q:
Returning a list from a function in Python
I'm creating a game for my sister, and I want a function to return a list variable, so I can pass it to another variable.
The relevant code is as follows:
def startNewGame():
while 1:
#Introduction:
print
print """Hello,
You will now be guided through the setup process.
There are 7 steps to this.
You can cancel setup at any time by typing 'cancelSetup'
Thankyou"""
#Step 1 (Name):
print
print """Step 1 of 7:
Type in a name for your PotatoHead:
"""
inputPHName = raw_input('|Enter Name:|')
if inputPHName == 'cancelSetup':
sys.exit()
#Step 2 (Gender):
print
print """Step 2 of 7:
Choose the gender of your PotatoHead:
input either 'm' or 'f'
"""
inputPHGender = raw_input('|Enter Gender:|')
if inputPHGender == 'cancelSetup':
sys.exit()
#Step 3 (Colour):
print
print """Step 3 of 7:
Choose the colour your PotatoHead will be:
Only Red, Blue, Green and Yellow are currently supported
"""
inputPHColour = raw_input('|Enter Colour:|')
if inputPHColour == 'cancelSetup':
sys.exit()
#Step 4 (Favourite Thing):
print
print """Step 4 of 7:
Type your PotatoHead's favourite thing:
"""
inputPHFavThing = raw_input('|Enter Favourite Thing:|')
if inputPHFavThing == 'cancelSetup':
sys.exit()
# Step 5 (First Toy):
print
print """Step 5 of 7:
Choose a first toy for your PotatoHead:
"""
inputPHFirstToy = raw_input('|Enter First Toy:|')
if inputPHFirstToy == 'cancelSetup':
sys.exit()
#Step 6 (Check stats):
while 1:
print
print """Step 6 of 7:
Check the following details to make sure that they are correct:
"""
print
print """Name:\t\t\t""" + inputPHName + """
Gender:\t\t\t""" + inputPHGender + """
Colour:\t\t\t""" + inputPHColour + """
Favourite Thing:\t""" + inputPHFavThing + """
First Toy:\t\t""" + inputPHFirstToy + """
"""
print
print "Enter 'y' or 'n'"
inputMCheckStats = raw_input('|Is this information correct?|')
if inputMCheckStats == 'cancelSetup':
sys.exit()
elif inputMCheckStats == 'y':
break
elif inputMCheckStats == 'n':
print "Re-enter info: ..."
print
break
else:
"The value you entered was incorrect, please re-enter your choice"
if inputMCheckStats == 'y':
break
#Step 7 (Define variables for the creation of the PotatoHead):
MFCreatePH = []
print
print """Step 7 of 7:
Your PotatoHead will now be created...
Creating variables...
"""
MFCreatePH = [inputPHName, inputPHGender, inputPHColour, inputPHFavThing, inputPHFirstToy]
time.sleep(1)
print "inputPHName"
print
time.sleep(1)
print "inputPHFirstToy"
print
return MFCreatePH
print "Your PotatoHead varibles have been successfully created!"
Then it is passed to another function that was imported from another module
from potatohead import *
...
welcomeMessage()
MCreatePH = startGame()
myPotatoHead = PotatoHead(MCreatePH)
the code for the PotatoHead object is in the potatohead.py module which was imported above, and is as follows:
class PotatoHead:
#Initialise the PotatoHead object:
def __init__(self, data):
self.data = data #Takes the data from the start new game function - see main.py
#Defines the PotatoHead starting attributes:
self.name = data[0]
self.gender = data[1]
self.colour = data[2]
self.favouriteThing = data[3]
self.firstToy = data[4]
self.age = '0.0'
self.education = [self.eduScience, self.eduEnglish, self.eduMaths] = '0.0', '0.0', '0.0'
self.fitness = '0.0'
self.happiness = '10.0'
self.health = '10.0'
self.hunger = '0.0'
self.tiredness = 'Not in this version'
self.toys = []
self.toys.append(self.firstToy)
self.time = '0'
#Sets data lists for saving, loading and general use:
self.phData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy)
self.phAdvData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy,
self.age, self.education, self.fitness, self.happiness, self.health, self.hunger,
self.tiredness, self.toys)
However, when I run the program this error appears:
Traceback (most recent call last):
File "/Users/Jasper/Documents/Programming/Potato Head Game/Current/main.py", line 158, in <module>
myPotatoHead = PotatoHead(MCreatePH)
File "/Users/Jasper/Documents/Programming/Potato Head Game/Current/potatohead.py", line 15, in __init__
self.name = data[0]
TypeError: 'NoneType' object is unsubscriptable
What am i doing wrong?
-----EDIT-----
The program finishes as so:
Step 7 of 7:
Your PotatoHead will now be created...
Creating variables...
inputPHName
inputPHFirstToy
Then it goes to the Tracback
-----EDIT2-----
This is the EXACT code I'm running in its entirety:
#+--------------------------------------+#
#| main.py |#
#| A main module for the Potato Head |#
#| Game to pull the other modules |#
#| together and control through user |#
#| input |#
#| Author: |#
#| Date Created / Modified: |#
#| 3/2/10 | 20/2/10 |#
#+--------------------------------------+# Tested: No
#Import the required modules:
import time
import random
import sys
from potatohead import *
from toy import *
#Start the Game:
def welcomeMessage():
print "----- START NEW GAME -----------------------"
print "==Print Welcome Message=="
print "loading... \t loading... \t loading..."
time.sleep(1)
print "loading..."
time.sleep(1)
print "LOADED..."
print; print; print;
print """Hello,
Welcome to the Potato Head Game. In this game you can create
a Potato Head, and look after it, like a Virtual Pet.
This game is constantly being updated and expanded. Please
look out for updates.
"""
#Choose whether to start a new game or load a previously saved game:
def startGame():
while 1:
print "--------------------"
print """ Choose an option:
New_Game
or
Load_Game
"""
startGameInput = raw_input('>>> >')
if startGameInput == 'New_Game':
startNewGame()
break
elif startGameInput == 'Load_Game':
print "This function is not yet supported"
print "Try Again"
print
else:
print "You must have mistyped the command: Type either 'New_Game' or 'Load_Game'"
print
#Set the new game up:
def startNewGame():
while 1:
#Introduction:
print
print """Hello,
You will now be guided through the setup process.
There are 7 steps to this.
You can cancel setup at any time by typing 'cancelSetup'
Thankyou"""
#Step 1 (Name):
print
print """Step 1 of 7:
Type in a name for your PotatoHead:
"""
inputPHName = raw_input('|Enter Name:|')
if inputPHName == 'cancelSetup':
sys.exit()
#Step 2 (Gender):
print
print """Step 2 of 7:
Choose the gender of your PotatoHead:
input either 'm' or 'f'
"""
inputPHGender = raw_input('|Enter Gender:|')
if inputPHGender == 'cancelSetup':
sys.exit()
#Step 3 (Colour):
print
print """Step 3 of 7:
Choose the colour your PotatoHead will be:
Only Red, Blue, Green and Yellow are currently supported
"""
inputPHColour = raw_input('|Enter Colour:|')
if inputPHColour == 'cancelSetup':
sys.exit()
#Step 4 (Favourite Thing):
print
print """Step 4 of 7:
Type your PotatoHead's favourite thing:
"""
inputPHFavThing = raw_input('|Enter Favourite Thing:|')
if inputPHFavThing == 'cancelSetup':
sys.exit()
# Step 5 (First Toy):
print
print """Step 5 of 7:
Choose a first toy for your PotatoHead:
"""
inputPHFirstToy = raw_input('|Enter First Toy:|')
if inputPHFirstToy == 'cancelSetup':
sys.exit()
#Step 6 (Check stats):
while 1:
print
print """Step 6 of 7:
Check the following details to make sure that they are correct:
"""
print
print """Name:\t\t\t""" + inputPHName + """
Gender:\t\t\t""" + inputPHGender + """
Colour:\t\t\t""" + inputPHColour + """
Favourite Thing:\t""" + inputPHFavThing + """
First Toy:\t\t""" + inputPHFirstToy + """
"""
print
print "Enter 'y' or 'n'"
inputMCheckStats = raw_input('|Is this information correct?|')
if inputMCheckStats == 'cancelSetup':
sys.exit()
elif inputMCheckStats == 'y':
break
elif inputMCheckStats == 'n':
print "Re-enter info: ..."
print
break
else:
"The value you entered was incorrect, please re-enter your choice"
if inputMCheckStats == 'y':
break
#Step 7 (Define variables for the creation of the PotatoHead):
MFCreatePH = []
print
print """Step 7 of 7:
Your PotatoHead will now be created...
Creating variables...
"""
MFCreatePH = [inputPHName, inputPHGender, inputPHColour, inputPHFavThing, inputPHFirstToy]
time.sleep(1)
print "inputPHName"
print
time.sleep(1)
print "inputPHFirstToy"
print
return MFCreatePH
print "Your PotatoHead varibles have been successfully created!"
#Run Program:
welcomeMessage()
MCreatePH = startGame()
myPotatoHead = PotatoHead(MCreatePH)
The potatohead.py module is as follows:
#+--------------------------------------+#
#| potatohead.py |#
#| A module for the Potato Head Game |#
#| Author: |#
#| Date Created / Modified: |#
#| 24/1/10 | 24/1/10 |#
#+--------------------------------------+# Tested: Yes (24/1/10)
#Create the PotatoHead class:
class PotatoHead:
#Initialise the PotatoHead object:
def __init__(self, data):
self.data = data #Takes the data from the start new game function - see main.py
#Defines the PotatoHead starting attributes:
self.name = data[0]
self.gender = data[1]
self.colour = data[2]
self.favouriteThing = data[3]
self.firstToy = data[4]
self.age = '0.0'
self.education = [self.eduScience, self.eduEnglish, self.eduMaths] = '0.0', '0.0', '0.0'
self.fitness = '0.0'
self.happiness = '10.0'
self.health = '10.0'
self.hunger = '0.0'
self.tiredness = 'Not in this version'
self.toys = []
self.toys.append(self.firstToy)
self.time = '0'
#Sets data lists for saving, loading and general use:
self.phData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy)
self.phAdvData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy,
self.age, self.education, self.fitness, self.happiness, self.health, self.hunger,
self.tiredness, self.toys)
#Define the phStats variable, enabling easy display of PotatoHead attributes:
def phDefStats(self):
self.phStats = """Your Potato Head's Stats are as follows:
----------------------------------------
Name: \t\t""" + self.name + """
Gender: \t\t""" + self.gender + """
Colour: \t\t""" + self.colour + """
Favourite Thing: \t""" + self.favouriteThing + """
First Toy: \t""" + self.firstToy + """
Age: \t\t""" + self.age + """
Education: \t""" + str(float(self.eduScience) + float(self.eduEnglish) + float(self.eduMaths)) + """
-> Science: \t""" + self.eduScience + """
-> English: \t""" + self.eduEnglish + """
-> Maths: \t""" + self.eduMaths + """
Fitness: \t""" + self.fitness + """
Happiness: \t""" + self.happiness + """
Health: \t""" + self.health + """
Hunger: \t""" + self.hunger + """
Tiredness: \t""" + self.tiredness + """
Toys: \t\t""" + str(self.toys) + """
Time: \t\t""" + self.time + """
"""
#Change the PotatoHead's favourite thing:
def phChangeFavouriteThing(self, newFavouriteThing):
self.favouriteThing = newFavouriteThing
phChangeFavouriteThingMsg = "Your Potato Head's favourite thing is " + self.favouriteThing + "."
#"Feed" the Potato Head i.e. Reduce the 'self.hunger' attribute's value:
def phFeed(self):
if float(self.hunger) >=3.0:
self.hunger = str(float(self.hunger) - 3.0)
elif float(self.hunger) < 3.0:
self.hunger = '0.0'
self.time = str(int(self.time) + 1) #Pass time
#"Exercise" the Potato Head if between the ages of 5 and 25:
def phExercise(self):
if float(self.age) < 5.1 or float(self.age) > 25.1:
print "This Potato Head is either too young or too old for this activity!"
else:
if float(self.fitness) <= 8.0:
self.fitness = str(float(self.fitness) + 2.0)
elif float(self.fitness) > 8.0:
self.fitness = '10.0'
self.time = str(int(self.time) + 1) #Pass time
#"Teach" the Potato Head:
def phTeach(self, subject):
if subject == 'Science':
if float(self.eduScience) <= 9.0:
self.eduScience = str(float(self.eduScience) + 1.0)
elif float(self.eduScience) > 9.0 and float(self.eduScience) < 10.0:
self.eduScience = '10.0'
elif float(self.eduScience) == 10.0:
print "Your Potato Head has gained the highest level of qualifications in this subject! It cannot learn any more!"
elif subject == 'English':
if float(self.eduEnglish) <= 9.0:
self.eduEnglish = str(float(self.eduEnglish) + 1.0)
elif float(self.eduEnglish) > 9.0 and float(self.eduEnglish) < 10.0:
self.eduEnglish = '10.0'
elif float(self.eduEnglish) == 10.0:
print "Your Potato Head has gained the highest level of qualifications in this subject! It cannot learn any more!"
elif subject == 'Maths':
if float(self.eduMaths) <= 9.0:
self.eduMaths = str(float(self.eduMaths) + 1.0)
elif float(self.eduMaths) > 9.0 and float(self.eduMaths) < 10.0:
self.eduMaths = '10.0'
elif float(self.eduMaths) == 10.0:
print "Your Potato Head has gained the highest level of qualifications in this subject! It cannot learn any more!"
else:
print "That subject is not an option..."
print "Please choose either Science, English or Maths"
self.time = str(int(self.time) + 1) #Pass time
#Increase Health:
def phGoToDoctor(self):
self.health = '10.0'
self.time = str(int(self.time) + 1) #Pass time
#Sleep: Age, change stats: #(Time Passes)
def phSleep(self):
self.time = '0' #Resets time for next 'day' (can do more things next day)
#Increase hunger:
if float(self.hunger) <= 5.0:
self.hunger = str(float(self.hunger) + 5.0)
elif float(self.hunger) > 5.0:
self.hunger = '10.0'
#Lower Fitness:
if float(self.fitness) >= 0.5:
self.fitness = str(float(self.fitness) - 0.5)
elif float(self.fitness) < 0.5:
self.fitness = '0.0'
#Lower Health:
if float(self.health) >= 0.5:
self.health = str(float(self.health) - 0.5)
elif float(self.health) < 0.5:
self.health = '0.0'
#Lower Happiness:
if float(self.happiness) >= 2.0:
self.happiness = str(float(self.happiness) - 2.0)
elif float(self.happiness) < 2.0:
self.happiness = '0.0'
#Increase the Potato Head's age:
self.age = str(float(self.age) + 0.1)
The game is still under development - There may be parts of modules that aren't complete, but I don't think they're causing the problem
A:
First all, i must say you are writing good code for a beginner, though you can improve startNewGame by writing a function, for getting user input in a loop, instead of writing same code again and again.
I copied your code and it runs without problem, though i did a small change
you are doing
MCreatePH = startGame()
but you haven't defined startGame? so if replace that with startNewGame it works
MCreatePH = startNewGame()
so may be you have defined startGame somewhere and it returns nothing?
A:
At first I thought you were just calling a function that didn't exist because your "relevant code" snippet shows us the definition of startNewGame() followed by this:
welcomeMessage()
MCreatePH = startGame()
myPotatoHead = PotatoHead(MCreatePH)
However, then I read the full code and saw that startGame() is also a function.
In the startGame() function you have a case that will call startNewGame(), but nothing ever returns the data from startNewGame() when startGame() is called. That is why the __init__ method of the PotatoHead instance you are creating fails trying to index into data. In the startGame() function, you can put "return " in front of where you call startNewGame() and I think everything should link up nicely.
|
Returning a list from a function in Python
|
I'm creating a game for my sister, and I want a function to return a list variable, so I can pass it to another variable.
The relevant code is as follows:
def startNewGame():
while 1:
#Introduction:
print
print """Hello,
You will now be guided through the setup process.
There are 7 steps to this.
You can cancel setup at any time by typing 'cancelSetup'
Thankyou"""
#Step 1 (Name):
print
print """Step 1 of 7:
Type in a name for your PotatoHead:
"""
inputPHName = raw_input('|Enter Name:|')
if inputPHName == 'cancelSetup':
sys.exit()
#Step 2 (Gender):
print
print """Step 2 of 7:
Choose the gender of your PotatoHead:
input either 'm' or 'f'
"""
inputPHGender = raw_input('|Enter Gender:|')
if inputPHGender == 'cancelSetup':
sys.exit()
#Step 3 (Colour):
print
print """Step 3 of 7:
Choose the colour your PotatoHead will be:
Only Red, Blue, Green and Yellow are currently supported
"""
inputPHColour = raw_input('|Enter Colour:|')
if inputPHColour == 'cancelSetup':
sys.exit()
#Step 4 (Favourite Thing):
print
print """Step 4 of 7:
Type your PotatoHead's favourite thing:
"""
inputPHFavThing = raw_input('|Enter Favourite Thing:|')
if inputPHFavThing == 'cancelSetup':
sys.exit()
# Step 5 (First Toy):
print
print """Step 5 of 7:
Choose a first toy for your PotatoHead:
"""
inputPHFirstToy = raw_input('|Enter First Toy:|')
if inputPHFirstToy == 'cancelSetup':
sys.exit()
#Step 6 (Check stats):
while 1:
print
print """Step 6 of 7:
Check the following details to make sure that they are correct:
"""
print
print """Name:\t\t\t""" + inputPHName + """
Gender:\t\t\t""" + inputPHGender + """
Colour:\t\t\t""" + inputPHColour + """
Favourite Thing:\t""" + inputPHFavThing + """
First Toy:\t\t""" + inputPHFirstToy + """
"""
print
print "Enter 'y' or 'n'"
inputMCheckStats = raw_input('|Is this information correct?|')
if inputMCheckStats == 'cancelSetup':
sys.exit()
elif inputMCheckStats == 'y':
break
elif inputMCheckStats == 'n':
print "Re-enter info: ..."
print
break
else:
"The value you entered was incorrect, please re-enter your choice"
if inputMCheckStats == 'y':
break
#Step 7 (Define variables for the creation of the PotatoHead):
MFCreatePH = []
print
print """Step 7 of 7:
Your PotatoHead will now be created...
Creating variables...
"""
MFCreatePH = [inputPHName, inputPHGender, inputPHColour, inputPHFavThing, inputPHFirstToy]
time.sleep(1)
print "inputPHName"
print
time.sleep(1)
print "inputPHFirstToy"
print
return MFCreatePH
print "Your PotatoHead varibles have been successfully created!"
Then it is passed to another function that was imported from another module
from potatohead import *
...
welcomeMessage()
MCreatePH = startGame()
myPotatoHead = PotatoHead(MCreatePH)
the code for the PotatoHead object is in the potatohead.py module which was imported above, and is as follows:
class PotatoHead:
#Initialise the PotatoHead object:
def __init__(self, data):
self.data = data #Takes the data from the start new game function - see main.py
#Defines the PotatoHead starting attributes:
self.name = data[0]
self.gender = data[1]
self.colour = data[2]
self.favouriteThing = data[3]
self.firstToy = data[4]
self.age = '0.0'
self.education = [self.eduScience, self.eduEnglish, self.eduMaths] = '0.0', '0.0', '0.0'
self.fitness = '0.0'
self.happiness = '10.0'
self.health = '10.0'
self.hunger = '0.0'
self.tiredness = 'Not in this version'
self.toys = []
self.toys.append(self.firstToy)
self.time = '0'
#Sets data lists for saving, loading and general use:
self.phData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy)
self.phAdvData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy,
self.age, self.education, self.fitness, self.happiness, self.health, self.hunger,
self.tiredness, self.toys)
However, when I run the program this error appears:
Traceback (most recent call last):
File "/Users/Jasper/Documents/Programming/Potato Head Game/Current/main.py", line 158, in <module>
myPotatoHead = PotatoHead(MCreatePH)
File "/Users/Jasper/Documents/Programming/Potato Head Game/Current/potatohead.py", line 15, in __init__
self.name = data[0]
TypeError: 'NoneType' object is unsubscriptable
What am i doing wrong?
-----EDIT-----
The program finishes as so:
Step 7 of 7:
Your PotatoHead will now be created...
Creating variables...
inputPHName
inputPHFirstToy
Then it goes to the Tracback
-----EDIT2-----
This is the EXACT code I'm running in its entirety:
#+--------------------------------------+#
#| main.py |#
#| A main module for the Potato Head |#
#| Game to pull the other modules |#
#| together and control through user |#
#| input |#
#| Author: |#
#| Date Created / Modified: |#
#| 3/2/10 | 20/2/10 |#
#+--------------------------------------+# Tested: No
#Import the required modules:
import time
import random
import sys
from potatohead import *
from toy import *
#Start the Game:
def welcomeMessage():
print "----- START NEW GAME -----------------------"
print "==Print Welcome Message=="
print "loading... \t loading... \t loading..."
time.sleep(1)
print "loading..."
time.sleep(1)
print "LOADED..."
print; print; print;
print """Hello,
Welcome to the Potato Head Game. In this game you can create
a Potato Head, and look after it, like a Virtual Pet.
This game is constantly being updated and expanded. Please
look out for updates.
"""
#Choose whether to start a new game or load a previously saved game:
def startGame():
while 1:
print "--------------------"
print """ Choose an option:
New_Game
or
Load_Game
"""
startGameInput = raw_input('>>> >')
if startGameInput == 'New_Game':
startNewGame()
break
elif startGameInput == 'Load_Game':
print "This function is not yet supported"
print "Try Again"
print
else:
print "You must have mistyped the command: Type either 'New_Game' or 'Load_Game'"
print
#Set the new game up:
def startNewGame():
while 1:
#Introduction:
print
print """Hello,
You will now be guided through the setup process.
There are 7 steps to this.
You can cancel setup at any time by typing 'cancelSetup'
Thankyou"""
#Step 1 (Name):
print
print """Step 1 of 7:
Type in a name for your PotatoHead:
"""
inputPHName = raw_input('|Enter Name:|')
if inputPHName == 'cancelSetup':
sys.exit()
#Step 2 (Gender):
print
print """Step 2 of 7:
Choose the gender of your PotatoHead:
input either 'm' or 'f'
"""
inputPHGender = raw_input('|Enter Gender:|')
if inputPHGender == 'cancelSetup':
sys.exit()
#Step 3 (Colour):
print
print """Step 3 of 7:
Choose the colour your PotatoHead will be:
Only Red, Blue, Green and Yellow are currently supported
"""
inputPHColour = raw_input('|Enter Colour:|')
if inputPHColour == 'cancelSetup':
sys.exit()
#Step 4 (Favourite Thing):
print
print """Step 4 of 7:
Type your PotatoHead's favourite thing:
"""
inputPHFavThing = raw_input('|Enter Favourite Thing:|')
if inputPHFavThing == 'cancelSetup':
sys.exit()
# Step 5 (First Toy):
print
print """Step 5 of 7:
Choose a first toy for your PotatoHead:
"""
inputPHFirstToy = raw_input('|Enter First Toy:|')
if inputPHFirstToy == 'cancelSetup':
sys.exit()
#Step 6 (Check stats):
while 1:
print
print """Step 6 of 7:
Check the following details to make sure that they are correct:
"""
print
print """Name:\t\t\t""" + inputPHName + """
Gender:\t\t\t""" + inputPHGender + """
Colour:\t\t\t""" + inputPHColour + """
Favourite Thing:\t""" + inputPHFavThing + """
First Toy:\t\t""" + inputPHFirstToy + """
"""
print
print "Enter 'y' or 'n'"
inputMCheckStats = raw_input('|Is this information correct?|')
if inputMCheckStats == 'cancelSetup':
sys.exit()
elif inputMCheckStats == 'y':
break
elif inputMCheckStats == 'n':
print "Re-enter info: ..."
print
break
else:
"The value you entered was incorrect, please re-enter your choice"
if inputMCheckStats == 'y':
break
#Step 7 (Define variables for the creation of the PotatoHead):
MFCreatePH = []
print
print """Step 7 of 7:
Your PotatoHead will now be created...
Creating variables...
"""
MFCreatePH = [inputPHName, inputPHGender, inputPHColour, inputPHFavThing, inputPHFirstToy]
time.sleep(1)
print "inputPHName"
print
time.sleep(1)
print "inputPHFirstToy"
print
return MFCreatePH
print "Your PotatoHead varibles have been successfully created!"
#Run Program:
welcomeMessage()
MCreatePH = startGame()
myPotatoHead = PotatoHead(MCreatePH)
The potatohead.py module is as follows:
#+--------------------------------------+#
#| potatohead.py |#
#| A module for the Potato Head Game |#
#| Author: |#
#| Date Created / Modified: |#
#| 24/1/10 | 24/1/10 |#
#+--------------------------------------+# Tested: Yes (24/1/10)
#Create the PotatoHead class:
class PotatoHead:
#Initialise the PotatoHead object:
def __init__(self, data):
self.data = data #Takes the data from the start new game function - see main.py
#Defines the PotatoHead starting attributes:
self.name = data[0]
self.gender = data[1]
self.colour = data[2]
self.favouriteThing = data[3]
self.firstToy = data[4]
self.age = '0.0'
self.education = [self.eduScience, self.eduEnglish, self.eduMaths] = '0.0', '0.0', '0.0'
self.fitness = '0.0'
self.happiness = '10.0'
self.health = '10.0'
self.hunger = '0.0'
self.tiredness = 'Not in this version'
self.toys = []
self.toys.append(self.firstToy)
self.time = '0'
#Sets data lists for saving, loading and general use:
self.phData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy)
self.phAdvData = (self.name, self.gender, self.colour, self.favouriteThing, self.firstToy,
self.age, self.education, self.fitness, self.happiness, self.health, self.hunger,
self.tiredness, self.toys)
#Define the phStats variable, enabling easy display of PotatoHead attributes:
def phDefStats(self):
self.phStats = """Your Potato Head's Stats are as follows:
----------------------------------------
Name: \t\t""" + self.name + """
Gender: \t\t""" + self.gender + """
Colour: \t\t""" + self.colour + """
Favourite Thing: \t""" + self.favouriteThing + """
First Toy: \t""" + self.firstToy + """
Age: \t\t""" + self.age + """
Education: \t""" + str(float(self.eduScience) + float(self.eduEnglish) + float(self.eduMaths)) + """
-> Science: \t""" + self.eduScience + """
-> English: \t""" + self.eduEnglish + """
-> Maths: \t""" + self.eduMaths + """
Fitness: \t""" + self.fitness + """
Happiness: \t""" + self.happiness + """
Health: \t""" + self.health + """
Hunger: \t""" + self.hunger + """
Tiredness: \t""" + self.tiredness + """
Toys: \t\t""" + str(self.toys) + """
Time: \t\t""" + self.time + """
"""
#Change the PotatoHead's favourite thing:
def phChangeFavouriteThing(self, newFavouriteThing):
self.favouriteThing = newFavouriteThing
phChangeFavouriteThingMsg = "Your Potato Head's favourite thing is " + self.favouriteThing + "."
#"Feed" the Potato Head i.e. Reduce the 'self.hunger' attribute's value:
def phFeed(self):
if float(self.hunger) >=3.0:
self.hunger = str(float(self.hunger) - 3.0)
elif float(self.hunger) < 3.0:
self.hunger = '0.0'
self.time = str(int(self.time) + 1) #Pass time
#"Exercise" the Potato Head if between the ages of 5 and 25:
def phExercise(self):
if float(self.age) < 5.1 or float(self.age) > 25.1:
print "This Potato Head is either too young or too old for this activity!"
else:
if float(self.fitness) <= 8.0:
self.fitness = str(float(self.fitness) + 2.0)
elif float(self.fitness) > 8.0:
self.fitness = '10.0'
self.time = str(int(self.time) + 1) #Pass time
#"Teach" the Potato Head:
def phTeach(self, subject):
if subject == 'Science':
if float(self.eduScience) <= 9.0:
self.eduScience = str(float(self.eduScience) + 1.0)
elif float(self.eduScience) > 9.0 and float(self.eduScience) < 10.0:
self.eduScience = '10.0'
elif float(self.eduScience) == 10.0:
print "Your Potato Head has gained the highest level of qualifications in this subject! It cannot learn any more!"
elif subject == 'English':
if float(self.eduEnglish) <= 9.0:
self.eduEnglish = str(float(self.eduEnglish) + 1.0)
elif float(self.eduEnglish) > 9.0 and float(self.eduEnglish) < 10.0:
self.eduEnglish = '10.0'
elif float(self.eduEnglish) == 10.0:
print "Your Potato Head has gained the highest level of qualifications in this subject! It cannot learn any more!"
elif subject == 'Maths':
if float(self.eduMaths) <= 9.0:
self.eduMaths = str(float(self.eduMaths) + 1.0)
elif float(self.eduMaths) > 9.0 and float(self.eduMaths) < 10.0:
self.eduMaths = '10.0'
elif float(self.eduMaths) == 10.0:
print "Your Potato Head has gained the highest level of qualifications in this subject! It cannot learn any more!"
else:
print "That subject is not an option..."
print "Please choose either Science, English or Maths"
self.time = str(int(self.time) + 1) #Pass time
#Increase Health:
def phGoToDoctor(self):
self.health = '10.0'
self.time = str(int(self.time) + 1) #Pass time
#Sleep: Age, change stats: #(Time Passes)
def phSleep(self):
self.time = '0' #Resets time for next 'day' (can do more things next day)
#Increase hunger:
if float(self.hunger) <= 5.0:
self.hunger = str(float(self.hunger) + 5.0)
elif float(self.hunger) > 5.0:
self.hunger = '10.0'
#Lower Fitness:
if float(self.fitness) >= 0.5:
self.fitness = str(float(self.fitness) - 0.5)
elif float(self.fitness) < 0.5:
self.fitness = '0.0'
#Lower Health:
if float(self.health) >= 0.5:
self.health = str(float(self.health) - 0.5)
elif float(self.health) < 0.5:
self.health = '0.0'
#Lower Happiness:
if float(self.happiness) >= 2.0:
self.happiness = str(float(self.happiness) - 2.0)
elif float(self.happiness) < 2.0:
self.happiness = '0.0'
#Increase the Potato Head's age:
self.age = str(float(self.age) + 0.1)
The game is still under development - There may be parts of modules that aren't complete, but I don't think they're causing the problem
|
[
"First all, i must say you are writing good code for a beginner, though you can improve startNewGame by writing a function, for getting user input in a loop, instead of writing same code again and again.\nI copied your code and it runs without problem, though i did a small change\nyou are doing \nMCreatePH = startGame()\n\nbut you haven't defined startGame? so if replace that with startNewGame it works\nMCreatePH = startNewGame()\n\nso may be you have defined startGame somewhere and it returns nothing?\n",
"At first I thought you were just calling a function that didn't exist because your \"relevant code\" snippet shows us the definition of startNewGame() followed by this:\nwelcomeMessage()\n\nMCreatePH = startGame()\n\nmyPotatoHead = PotatoHead(MCreatePH)\n\nHowever, then I read the full code and saw that startGame() is also a function.\nIn the startGame() function you have a case that will call startNewGame(), but nothing ever returns the data from startNewGame() when startGame() is called. That is why the __init__ method of the PotatoHead instance you are creating fails trying to index into data. In the startGame() function, you can put \"return \" in front of where you call startNewGame() and I think everything should link up nicely.\n"
] |
[
5,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002300963_python.txt
|
Q:
Factor Analysis in python
is there a module that contains a function that calculate Factor Analysis (not PCA)
in python?
A:
Here is the direct link to the MDP Factor Analysis node.
The MDP homepage is here.
A:
Yes there is http://pypi.python.org/pypi/MDP/2.3. First result in Google on query Factor Analysis python ;-)
|
Factor Analysis in python
|
is there a module that contains a function that calculate Factor Analysis (not PCA)
in python?
|
[
"Here is the direct link to the MDP Factor Analysis node.\nThe MDP homepage is here. \n",
"Yes there is http://pypi.python.org/pypi/MDP/2.3. First result in Google on query Factor Analysis python ;-)\n"
] |
[
5,
0
] |
[] |
[] |
[
"analysis",
"factor_analysis",
"python"
] |
stackoverflow_0002301993_analysis_factor_analysis_python.txt
|
Q:
Would you use numpy if you were just manipulating a sequence of binary values?
Is there any advantage to using numpy when you're doing a large number of operations on lists of binary values? How about integers within a small range (like just the numbers 1,2, and 3?)
A:
Eliminating the loops is the the source of the performance gain (10x):
import profile
import numpy as NP
def np_test(a2darray) :
row_sums = NP.sum(a2darray, axis=1)
return NP.sum(row_sums)
def stdlib_test2(a2dlist) :
return sum([sum(row) for row in a2dlist])
A = NP.random.randint(1, 6, 1e7).reshape(1e4, 1e3)
B = NP.ndarray.tolist(A)
profile.run("np_test(A)")
profile.run("stdlib_test2(B)")
numpy:
10 function calls in 0.025 CPU
seconds
lists:
10005 function calls in 0.280 CPU
seconds
A:
If the number of input values is huge, or if you are doing a lot of operations, you might want to try bitarray. Or, see the bool/int8/uint8 dtype in Numpy's ndarray:
In [1]: import numpy as np
In [2]: data = np.array([0,1,1,0], dtype=bool)
In [3]: data
Out[3]: array([False, True, True, False], dtype=bool)
In [4]: data.size
Out[4]: 4
In [5]: data.nbytes
Out[5]: 4
|
Would you use numpy if you were just manipulating a sequence of binary values?
|
Is there any advantage to using numpy when you're doing a large number of operations on lists of binary values? How about integers within a small range (like just the numbers 1,2, and 3?)
|
[
"Eliminating the loops is the the source of the performance gain (10x):\nimport profile\nimport numpy as NP\n\ndef np_test(a2darray) :\n row_sums = NP.sum(a2darray, axis=1)\n return NP.sum(row_sums)\n\ndef stdlib_test2(a2dlist) :\n return sum([sum(row) for row in a2dlist])\n\nA = NP.random.randint(1, 6, 1e7).reshape(1e4, 1e3)\nB = NP.ndarray.tolist(A)\n\nprofile.run(\"np_test(A)\")\nprofile.run(\"stdlib_test2(B)\")\n\nnumpy:\n\n10 function calls in 0.025 CPU\nseconds\n\nlists:\n\n10005 function calls in 0.280 CPU\nseconds\n\n",
"If the number of input values is huge, or if you are doing a lot of operations, you might want to try bitarray. Or, see the bool/int8/uint8 dtype in Numpy's ndarray:\nIn [1]: import numpy as np\nIn [2]: data = np.array([0,1,1,0], dtype=bool)\nIn [3]: data\nOut[3]: array([False, True, True, False], dtype=bool)\nIn [4]: data.size\nOut[4]: 4\nIn [5]: data.nbytes\nOut[5]: 4\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"bit_manipulation",
"numpy",
"python",
"scipy"
] |
stackoverflow_0002301018_bit_manipulation_numpy_python_scipy.txt
|
Q:
Appending word position numbers to Unicode text in Python
I have a code which appends word positions to the words from the source file
but the output is not coming as desired:
The input file contains the following:
3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है।
57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्देश्य से असम आए।
The original source code is like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
separators = [u'।', ',', '.']
text = open("hinstest1.txt").read()
#This converts the encoded text to an internal unicode object, where
# all characters are properly recognized as an entity:
text = text.decode("UTF-8")
#this breaks the text on the white spaces, yielding a list of words:
words = text.split()
counter = 1
output = ""
#if the last char is a separator, and is joined to the word:
for word in words:
if word[-1] in separators and len(word) > 1:
#word up to the second to last char:
output += word[:-1] + u'(%d) ' % counter
counter += 1
#last char
output += word[-1] +u'(%d) ' % counter
else:
output += word + u'(%d) ' % counter
counter += 1
#for ch in word:
# if ch is '\n':
print output
#counter = 1
The output for this code is like this:
3(1) .(2)
3(1) .(2) भारत(2)
3(1) .(2) भारत(2) का(3)
3(1) .(2) भारत(2) का(3) इतिहास(4)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28) से(29)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28) से(29) असम(30)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28) से(29) असम(30) आए(31) ।(32)
I have tried to modify the above code so that the counter detects a new line and reinitializes the word positions to start from 1 for every new line, I also need to make sure that no word positions is displayed for the serial nos.
My modified code is not 100% correct could you please help me correct it to get the desired output:
Modified code looks like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
import fileinput
list1 = []
separators = [u'।', ',', '.']
chknwlin = ['\n']
text = open("hinstest1.txt").read()
output_file = ("ophwp1.txt")
#This converts the encoded text to an internal unicode object, where
# all characters are properly recognized as an entity:
text = text.decode("UTF-8")
#this breaks the text on the white spaces, yielding a list of words:
words = text.split()
counter = 1
output = ""
#if the last char is a separator, and is joined to the word:
for line in words:
for word in line:
for ch in line:
if word[-1] in separators and len(word) > 1:
#word up to the second to last char:
output += word[:-1] + u'(%d) ' % counter
counter += 1
#last char
output += word[-1] +u'(%d) ' % counter
else :
output += word + u'(%d) ' % counter
counter += 1
# if ch is '\n':
if ch in chknwlin:
#for ch in words:
print output
counter = 1
list1.append(output)
#words.close()
f1=open(output_file,'w')
f1.write(' '.join(list1))
f1.close()
I finally want the output to look like this:
3. भारत(1) का(2) इतिहास(3) काफी(4) समृद्ध(5) एवं(6) विस्तृत(7) है(8) ।(9)
57. जैसे(1) आज(2) के(3) झारखंड(4) प्रदेश(5) से(6) ,(7) उन(8) दिनों(9) ,(10) बहुत(11) से(12) लोग(13) चाय(14) बागानों(15) में(16) मजदूरी(17) करने(18) के(19) उद्देश्य(20) से(21) असम(22) आए(23) ।(24)
The modified code is not giving me any output on the console and is also copying nothing to the output file.
A:
I think your code should something like:
# the input part is fine as is
lines = text.split('\n')
outlines = []
for line in lines:
lout = []
counter = 1
for i, word in enumerate(lines.split()):
if i == 0: # leave 1st word of line alone, it's a marker:
lout.append(word)
continue
# process each and every other word
if word[-1] in separators and len(word) > 1:
lout.append(word[:-1] + (u'(%d) ' % counter) +
word[-1] + (u'(%d) ' % counter+1))
counter += 1
else :
lout.append(word + u'(%d)' % counter)
counter += 1
outlines.append(' '.join(lout))
f1=open(output_file,'w')
f1.write('\n'.join(outlines))
f1.close()
Can't test this code, so there might be minor issues left, but I think the main principles in it are sound: work on two levels (by line within fine, with \n as separator, and by word within line, with space as separator) and each time use lists (with append and join) rather than build up strings by pieces.
A:
This code will give you the desired output. I added a check for the number at the start of the line, which should not be numbered.
I adapted your original code, which was (mostly) working. You just needed to reset the counter at the end of an input line, and add a newline to your output as well.
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
import re
list1 = []
separators = [u'।', ',', '.']
text = open('hinstest1.txt').read().decode('UTF-8')
output_file = ('ophwp1.txt')
for line in text.splitlines():
counter = 1
output = ''
for word in line.split():
# Special case for the number at the start of the line
# The regex matches one or more decimal digits (\d+) followed by a dot (\.)
if re.match(r'\d+\.', word):
output += word + ' '
continue
# Special case: the last char is a separator joined to the word
if word[-1] in separators and len(word) > 1:
# word up to the second to last char
output += word[:-1] + u'(%d) ' % counter
counter += 1
# last char
output += word[-1] + u'(%d) ' % counter
counter += 1
else:
output += word + u'(%d) ' % counter
counter += 1
output += u'\n'
list1.append(output.encode('UTF-8'))
f1=open(output_file,'w')
f1.write(''.join(list1))
f1.close()
I tested this code on the input file you provided and, for the most part, I retained your coding style.
A:
Try changing:
counter = 1
for line in words:
# etc...
to:
for line in words:
counter = 1
# etc...
This will reset the counter to 1 for each new line.
|
Appending word position numbers to Unicode text in Python
|
I have a code which appends word positions to the words from the source file
but the output is not coming as desired:
The input file contains the following:
3. भारत का इतिहास काफी समृद्ध एवं विस्तृत है।
57. जैसे आज के झारखंड प्रदेश से, उन दिनों, बहुत से लोग चाय बागानों में मजदूरी करने के उद्देश्य से असम आए।
The original source code is like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
separators = [u'।', ',', '.']
text = open("hinstest1.txt").read()
#This converts the encoded text to an internal unicode object, where
# all characters are properly recognized as an entity:
text = text.decode("UTF-8")
#this breaks the text on the white spaces, yielding a list of words:
words = text.split()
counter = 1
output = ""
#if the last char is a separator, and is joined to the word:
for word in words:
if word[-1] in separators and len(word) > 1:
#word up to the second to last char:
output += word[:-1] + u'(%d) ' % counter
counter += 1
#last char
output += word[-1] +u'(%d) ' % counter
else:
output += word + u'(%d) ' % counter
counter += 1
#for ch in word:
# if ch is '\n':
print output
#counter = 1
The output for this code is like this:
3(1) .(2)
3(1) .(2) भारत(2)
3(1) .(2) भारत(2) का(3)
3(1) .(2) भारत(2) का(3) इतिहास(4)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28) से(29)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28) से(29) असम(30)
3(1) .(2) भारत(2) का(3) इतिहास(4) काफी(5) समृद्ध(6) एवं(7) विस्तृत(8) है(9) ।(10) 57(10) .(11) जैसे(11) आज(12) के(13) झारखंड(14) प्रदेश(15) से(16) ,(17) उन(17) दिनों(18) ,(19) बहुत(19) से(20) लोग(21) चाय(22) बागानों(23) में(24) मजदूरी(25) करने(26) के(27) उद्देश्य(28) से(29) असम(30) आए(31) ।(32)
I have tried to modify the above code so that the counter detects a new line and reinitializes the word positions to start from 1 for every new line, I also need to make sure that no word positions is displayed for the serial nos.
My modified code is not 100% correct could you please help me correct it to get the desired output:
Modified code looks like this:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8
import fileinput
list1 = []
separators = [u'।', ',', '.']
chknwlin = ['\n']
text = open("hinstest1.txt").read()
output_file = ("ophwp1.txt")
#This converts the encoded text to an internal unicode object, where
# all characters are properly recognized as an entity:
text = text.decode("UTF-8")
#this breaks the text on the white spaces, yielding a list of words:
words = text.split()
counter = 1
output = ""
#if the last char is a separator, and is joined to the word:
for line in words:
for word in line:
for ch in line:
if word[-1] in separators and len(word) > 1:
#word up to the second to last char:
output += word[:-1] + u'(%d) ' % counter
counter += 1
#last char
output += word[-1] +u'(%d) ' % counter
else :
output += word + u'(%d) ' % counter
counter += 1
# if ch is '\n':
if ch in chknwlin:
#for ch in words:
print output
counter = 1
list1.append(output)
#words.close()
f1=open(output_file,'w')
f1.write(' '.join(list1))
f1.close()
I finally want the output to look like this:
3. भारत(1) का(2) इतिहास(3) काफी(4) समृद्ध(5) एवं(6) विस्तृत(7) है(8) ।(9)
57. जैसे(1) आज(2) के(3) झारखंड(4) प्रदेश(5) से(6) ,(7) उन(8) दिनों(9) ,(10) बहुत(11) से(12) लोग(13) चाय(14) बागानों(15) में(16) मजदूरी(17) करने(18) के(19) उद्देश्य(20) से(21) असम(22) आए(23) ।(24)
The modified code is not giving me any output on the console and is also copying nothing to the output file.
|
[
"I think your code should something like:\n# the input part is fine as is\nlines = text.split('\\n')\noutlines = []\nfor line in lines:\n lout = []\n counter = 1\n for i, word in enumerate(lines.split()):\n if i == 0: # leave 1st word of line alone, it's a marker:\n lout.append(word)\n continue\n # process each and every other word\n if word[-1] in separators and len(word) > 1:\n lout.append(word[:-1] + (u'(%d) ' % counter) +\n word[-1] + (u'(%d) ' % counter+1))\n counter += 1\n else :\n lout.append(word + u'(%d)' % counter)\n counter += 1\n outlines.append(' '.join(lout))\n\nf1=open(output_file,'w')\nf1.write('\\n'.join(outlines))\nf1.close()\n\nCan't test this code, so there might be minor issues left, but I think the main principles in it are sound: work on two levels (by line within fine, with \\n as separator, and by word within line, with space as separator) and each time use lists (with append and join) rather than build up strings by pieces.\n",
"This code will give you the desired output. I added a check for the number at the start of the line, which should not be numbered.\nI adapted your original code, which was (mostly) working. You just needed to reset the counter at the end of an input line, and add a newline to your output as well.\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n# encoding: utf-8\n\nimport re\n\nlist1 = []\nseparators = [u'।', ',', '.']\ntext = open('hinstest1.txt').read().decode('UTF-8')\noutput_file = ('ophwp1.txt')\n\nfor line in text.splitlines():\n counter = 1\n output = ''\n for word in line.split():\n # Special case for the number at the start of the line\n # The regex matches one or more decimal digits (\\d+) followed by a dot (\\.)\n if re.match(r'\\d+\\.', word):\n output += word + ' '\n continue\n # Special case: the last char is a separator joined to the word\n if word[-1] in separators and len(word) > 1:\n # word up to the second to last char\n output += word[:-1] + u'(%d) ' % counter\n counter += 1\n # last char\n output += word[-1] + u'(%d) ' % counter\n counter += 1\n else:\n output += word + u'(%d) ' % counter\n counter += 1\n output += u'\\n'\n list1.append(output.encode('UTF-8'))\n\nf1=open(output_file,'w')\nf1.write(''.join(list1))\nf1.close()\n\nI tested this code on the input file you provided and, for the most part, I retained your coding style.\n",
"Try changing:\ncounter = 1\nfor line in words:\n # etc...\n\nto:\nfor line in words:\n counter = 1\n # etc...\n\nThis will reset the counter to 1 for each new line.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"nlp",
"python"
] |
stackoverflow_0002301918_nlp_python.txt
|
Q:
skipping unknown items while Serializing using json
I'm trying to serialize obj using json (Python). I wish to skip json's unknown type
I know I can add my own encoder, but what I'm interested in is to just skip the unknown type. I don't want to use None instead. I have tried
icon=QIcon()
arr=["blablal",icon]
str1=simplejson.dumps(arr,skipkeys=True)
I used the skipkeys option to skip the icon object which is unknown type for json but I keep getting TypeError exception. What am I doing wrong?
A:
Ok so i found the problem
icon isn't a key but a value
if icon was used as a key in a dict it would have been ignored
|
skipping unknown items while Serializing using json
|
I'm trying to serialize obj using json (Python). I wish to skip json's unknown type
I know I can add my own encoder, but what I'm interested in is to just skip the unknown type. I don't want to use None instead. I have tried
icon=QIcon()
arr=["blablal",icon]
str1=simplejson.dumps(arr,skipkeys=True)
I used the skipkeys option to skip the icon object which is unknown type for json but I keep getting TypeError exception. What am I doing wrong?
|
[
"Ok so i found the problem \nicon isn't a key but a value \nif icon was used as a key in a dict it would have been ignored\n"
] |
[
0
] |
[] |
[] |
[
"json",
"python"
] |
stackoverflow_0002302252_json_python.txt
|
Q:
cannot import name formats
what does it mean? i ve googled but found nothing =/
ImportError at /admin/
cannot import name formats
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Exception Type: ImportError
Exception Value:
cannot import name formats
Exception Location: /usr/lib/python2.6/site-packages/django/contrib/admin/util.py in <module>, line 3
Python Executable: /usr/bin/python
Python Version: 2.6.0
Python Path: ['/home/cad/project/lkd/gezegen/lkd_gezegen', '/usr/lib64/python26.zip', '/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old', '/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages', '/usr/lib64/python2.6/site-packages/Numeric', '/usr/lib64/python2.6/site-packages/PIL', '/usr/lib64/python2.6/site-packages/gst-0.10', '/usr/lib64/python2.6/site-packages/gtk-2.0', '/usr/lib64/python2.6/site-packages/wx-2.8-gtk2-unicode', '/usr/lib/python2.6/site-packages']
A:
What that line is trying to do (see the sources) is
3 from django.utils import formats
If you don't have the parent directory of the django/ directory on your sys.path, or the __init__.py files at either levels somehow went missing, that would explain your issues.
On a side note, the .0 in 2.6.0 is worrisome -- it's an old microrelease with known bugs. Can you upgrade to the current 2.6.4? I don't think this is related to the problems you're observing but sticking with the old buggy microrelease might give you other problems in the future.
|
cannot import name formats
|
what does it mean? i ve googled but found nothing =/
ImportError at /admin/
cannot import name formats
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Exception Type: ImportError
Exception Value:
cannot import name formats
Exception Location: /usr/lib/python2.6/site-packages/django/contrib/admin/util.py in <module>, line 3
Python Executable: /usr/bin/python
Python Version: 2.6.0
Python Path: ['/home/cad/project/lkd/gezegen/lkd_gezegen', '/usr/lib64/python26.zip', '/usr/lib64/python2.6', '/usr/lib64/python2.6/plat-linux2', '/usr/lib64/python2.6/lib-tk', '/usr/lib64/python2.6/lib-old', '/usr/lib64/python2.6/lib-dynload', '/usr/lib64/python2.6/site-packages', '/usr/lib64/python2.6/site-packages/Numeric', '/usr/lib64/python2.6/site-packages/PIL', '/usr/lib64/python2.6/site-packages/gst-0.10', '/usr/lib64/python2.6/site-packages/gtk-2.0', '/usr/lib64/python2.6/site-packages/wx-2.8-gtk2-unicode', '/usr/lib/python2.6/site-packages']
|
[
"What that line is trying to do (see the sources) is\n3 from django.utils import formats\n\nIf you don't have the parent directory of the django/ directory on your sys.path, or the __init__.py files at either levels somehow went missing, that would explain your issues.\nOn a side note, the .0 in 2.6.0 is worrisome -- it's an old microrelease with known bugs. Can you upgrade to the current 2.6.4? I don't think this is related to the problems you're observing but sticking with the old buggy microrelease might give you other problems in the future.\n"
] |
[
1
] |
[] |
[] |
[
"admin",
"django",
"python"
] |
stackoverflow_0002301703_admin_django_python.txt
|
Q:
Python multiple threads accessing same file
I have two threads, one which writes to a file, and another which periodically
moves the file to a different location. The writes always calls open before writing a message, and calls close after writing the message. The mover uses shutil.move to do the move.
I see that after the first move is done, the writer cannot write to the file anymore, i.e. the size of the file is always 0 after the first move. Am I doing something wrong?
A:
Locking is a possible solution, but I prefer the general architecture of having each external resource (including a file) dealt with by a single, separate thread. Other threads send work requests to the dedicated thread on a Queue.Queue instance (and provide a separate queue of their own as part of the work request's parameters if they need result back), the dedicated thread spends most of its time waiting on a .get on that queue and whenever it gets a requests goes on and executes it (and returns results on the passed-in queue if needed).
I've provided detailed examples of this approach e.g. in "Python in a Nutshell". Python's Queue is intrinsically thread-safe and simplifies your life enormously.
Among the advantages of this architecture is that it translates smoothly to multiprocessing if and when you decide to switch some work to a separate process instead of a separate thread (e.g. to take advantage of multiple cores) -- multiprocessing provides its own workalike Queue type to make such a transition smooth as silk;-).
A:
When two threads access the same resources, weird things happen. To avoid that, always lock the resource. Python has the convenient threading.Lock for that, as well as some other tools (see documentation of the threading module).
A:
Check out http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/
You can use a simple lock with his code, as written by Evan Fosmark in an older StackOverflow question:
from filelock import FileLock
with FileLock("myfile.txt"):
# work with the file as it is now locked
print("Lock acquired.")
One of the more elegant libraries I've ever seen.
|
Python multiple threads accessing same file
|
I have two threads, one which writes to a file, and another which periodically
moves the file to a different location. The writes always calls open before writing a message, and calls close after writing the message. The mover uses shutil.move to do the move.
I see that after the first move is done, the writer cannot write to the file anymore, i.e. the size of the file is always 0 after the first move. Am I doing something wrong?
|
[
"Locking is a possible solution, but I prefer the general architecture of having each external resource (including a file) dealt with by a single, separate thread. Other threads send work requests to the dedicated thread on a Queue.Queue instance (and provide a separate queue of their own as part of the work request's parameters if they need result back), the dedicated thread spends most of its time waiting on a .get on that queue and whenever it gets a requests goes on and executes it (and returns results on the passed-in queue if needed).\nI've provided detailed examples of this approach e.g. in \"Python in a Nutshell\". Python's Queue is intrinsically thread-safe and simplifies your life enormously.\nAmong the advantages of this architecture is that it translates smoothly to multiprocessing if and when you decide to switch some work to a separate process instead of a separate thread (e.g. to take advantage of multiple cores) -- multiprocessing provides its own workalike Queue type to make such a transition smooth as silk;-).\n",
"When two threads access the same resources, weird things happen. To avoid that, always lock the resource. Python has the convenient threading.Lock for that, as well as some other tools (see documentation of the threading module).\n",
"Check out http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/\nYou can use a simple lock with his code, as written by Evan Fosmark in an older StackOverflow question:\nfrom filelock import FileLock\n\nwith FileLock(\"myfile.txt\"):\n # work with the file as it is now locked\n print(\"Lock acquired.\")\n\nOne of the more elegant libraries I've ever seen.\n"
] |
[
29,
8,
4
] |
[] |
[] |
[
"file",
"multithreading",
"python"
] |
stackoverflow_0002301458_file_multithreading_python.txt
|
Q:
With multiple Python installs, how does MacPorts know which one to install MySQLdb for?
I just upgraded the default Python 2.5 on Leopard to 2.6 via the installer on www.python.org. Upon doing so, the MySQLdb I had installed was no longer found. So I tried reinstalling it via port install py-mysql, and it succeeded, but MySQLdb was still not importable. So then I tried to python install python26 with python_select python26 and it succeeded, but it doesn't appear that it is getting precedence over the python.org install:
$ which python
/Library/Frameworks/Python.framework/Versions/2.6/bin/python
When I would expect it to be something like /opt/local/bin/python
My path environment is: /Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/local/mysql/bin/:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/mysql/bin:/Users/bsr/bin
Anyway, when I try port install py-mysql but how does it know where to install the Python MySQL library?
A:
The MacPorts python ports generally follow a pattern: if the port name starts with just py-, it is configured to install into MacPorts python2.4. Likewise py25- requires python2.5. For the MacPorts python2.6, you want this port:
sudo port install py26-mysql
A:
You also need python_select (or is it select_python?) to change the default python used.
|
With multiple Python installs, how does MacPorts know which one to install MySQLdb for?
|
I just upgraded the default Python 2.5 on Leopard to 2.6 via the installer on www.python.org. Upon doing so, the MySQLdb I had installed was no longer found. So I tried reinstalling it via port install py-mysql, and it succeeded, but MySQLdb was still not importable. So then I tried to python install python26 with python_select python26 and it succeeded, but it doesn't appear that it is getting precedence over the python.org install:
$ which python
/Library/Frameworks/Python.framework/Versions/2.6/bin/python
When I would expect it to be something like /opt/local/bin/python
My path environment is: /Library/Frameworks/Python.framework/Versions/2.6/bin:/usr/local/mysql/bin/:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/mysql/bin:/Users/bsr/bin
Anyway, when I try port install py-mysql but how does it know where to install the Python MySQL library?
|
[
"The MacPorts python ports generally follow a pattern: if the port name starts with just py-, it is configured to install into MacPorts python2.4. Likewise py25- requires python2.5. For the MacPorts python2.6, you want this port:\nsudo port install py26-mysql\n\n",
"You also need python_select (or is it select_python?) to change the default python used.\n"
] |
[
2,
1
] |
[] |
[] |
[
"macos",
"mysql",
"python"
] |
stackoverflow_0001499572_macos_mysql_python.txt
|
Q:
Alternate row coloring in Scintilla
I'm using wxStyledTextCtrl from wxPython, a wrapper around the Scintilla component.
Is there any way to get alternate row coloring on it (odd rows in one background color and even rows in another color)?
I'm using the builtin python styler to highlight keywords.
A:
The background of lines can be changed, for example by markers (which is used for stuff like bookmarks or breakpoints, current execution point and the like in IDEs), but there is no built-in mode for changing the background colour of every other line.
You could simulate this by setting a special marker with a background colour for all odd or even line numbers (MarkerSetBackground() and MarkerAdd()). This would probably consume a lot of cycles, and each editing operation that splits or joins, inserts or deletes lines would need the markers to be reset. Still, it may be worth looking into, given that there seems to be no other way.
|
Alternate row coloring in Scintilla
|
I'm using wxStyledTextCtrl from wxPython, a wrapper around the Scintilla component.
Is there any way to get alternate row coloring on it (odd rows in one background color and even rows in another color)?
I'm using the builtin python styler to highlight keywords.
|
[
"The background of lines can be changed, for example by markers (which is used for stuff like bookmarks or breakpoints, current execution point and the like in IDEs), but there is no built-in mode for changing the background colour of every other line.\nYou could simulate this by setting a special marker with a background colour for all odd or even line numbers (MarkerSetBackground() and MarkerAdd()). This would probably consume a lot of cycles, and each editing operation that splits or joins, inserts or deletes lines would need the markers to be reset. Still, it may be worth looking into, given that there seems to be no other way.\n"
] |
[
6
] |
[] |
[] |
[
"python",
"scintilla",
"wxpython"
] |
stackoverflow_0002302165_python_scintilla_wxpython.txt
|
Q:
How can I fix the error on this Python code?
I have this superclass:
import wx
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.colorOver = ((89,89,89))
self.colorLeave = ((110,110,110))
self.SetBackgroundColour(self.colorLeave)
self.SetForegroundColour(self.colorLeave)
self.name = "plugin"
wx.StaticText(self, -1, self.getName(), style=wx.ALIGN_LEFT)
self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
self.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)
def onMouseOver(self, event):
self.SetBackgroundColour(self.colorOver)
self.Refresh()
def onMouseLeave(self, event):
self.SetBackgroundColour(self.colorLeave)
self.Refresh()
def OnClose(self, event):
self.Close()
app.Destroy()
def getName(self):
return self.name
and this subclass:
import plugin
import wx
class noisePlugin(plugin.Plugin):
self.name = "noise"
and it gives me this error compiling the subclass:
Traceback (most recent call last):
File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 4, in <module>
class noisePlugin(plugin.Plugin):
File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 5, in noisePlugin
self.name = "noise"
NameError: name 'self' is not defined
What can I do to fix this error?
I want getName() method to return the name of the instanciated class!
Thanks in advance :)
A:
Make the subclass
class noisePlugin(plugin.Plugin):
def __init__(self, *a, **k):
plugin.Plugin.__init__(self, *a, **k)
self.name = "noise"
Whenever you want to use self.something you have to be within a method, not at class level outside of methods!
A:
What makes you think this works?
class noisePlugin(plugin.Plugin):
self.name = "noise"
Why didn't you copy the
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
That comes before self.name=?
A:
For the pattern you seem to be trying for (where the name is associated more with the class than with the instance), this is often a better idiom to follow:
class A(object):
name = 'parent'
def __init__(self, ...):
... etc
class B(A):
name = 'child'
def __init__(self, ...):
A.__init__(self, ...)
... etc
Even though the name attribute is stored on the class rather than the instance, you can access it using self.name in all the instances. Generally if you find yourself assigning a static (unchanging) attribute that is the same in all instances of a given class you should just use a static class attribute like this.
On a slightly different topic, were you aware that all wxPython widgets already have a name attribute, which can be assigned using the name keyword argument at initialization time, and accessed using either GetName() or (in recent versions of wxPython) the property Name? If you don't assign it, it will default to some fairly generic class-specific value (like "text" or "textctrl" for wx.TextCtrl). Depending on what you're trying to do, maybe you can just use it instead of your own name and getName(). wxPython itself does not make any use of this value, as it's intended for you the programmer to use as you see fit.
|
How can I fix the error on this Python code?
|
I have this superclass:
import wx
class Plugin(wx.Panel):
def __init__(self, parent, *args, **kwargs):
wx.Panel.__init__(self, parent, *args, **kwargs)
self.colorOver = ((89,89,89))
self.colorLeave = ((110,110,110))
self.SetBackgroundColour(self.colorLeave)
self.SetForegroundColour(self.colorLeave)
self.name = "plugin"
wx.StaticText(self, -1, self.getName(), style=wx.ALIGN_LEFT)
self.Bind(wx.EVT_ENTER_WINDOW, self.onMouseOver)
self.Bind(wx.EVT_LEAVE_WINDOW, self.onMouseLeave)
def onMouseOver(self, event):
self.SetBackgroundColour(self.colorOver)
self.Refresh()
def onMouseLeave(self, event):
self.SetBackgroundColour(self.colorLeave)
self.Refresh()
def OnClose(self, event):
self.Close()
app.Destroy()
def getName(self):
return self.name
and this subclass:
import plugin
import wx
class noisePlugin(plugin.Plugin):
self.name = "noise"
and it gives me this error compiling the subclass:
Traceback (most recent call last):
File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 4, in <module>
class noisePlugin(plugin.Plugin):
File "C:\Users\André Ferreira\Desktop\Tese\Código Python\SoundLog\Plugins\noisePlugin.py", line 5, in noisePlugin
self.name = "noise"
NameError: name 'self' is not defined
What can I do to fix this error?
I want getName() method to return the name of the instanciated class!
Thanks in advance :)
|
[
"Make the subclass\nclass noisePlugin(plugin.Plugin):\n def __init__(self, *a, **k):\n plugin.Plugin.__init__(self, *a, **k)\n self.name = \"noise\"\n\nWhenever you want to use self.something you have to be within a method, not at class level outside of methods!\n",
"What makes you think this works?\nclass noisePlugin(plugin.Plugin):\n self.name = \"noise\"\n\nWhy didn't you copy the \nclass Plugin(wx.Panel):\n def __init__(self, parent, *args, **kwargs):\n\nThat comes before self.name=?\n",
"For the pattern you seem to be trying for (where the name is associated more with the class than with the instance), this is often a better idiom to follow:\nclass A(object):\n name = 'parent'\n\n def __init__(self, ...):\n ... etc\n\nclass B(A):\n name = 'child'\n\n def __init__(self, ...):\n A.__init__(self, ...)\n ... etc\n\nEven though the name attribute is stored on the class rather than the instance, you can access it using self.name in all the instances. Generally if you find yourself assigning a static (unchanging) attribute that is the same in all instances of a given class you should just use a static class attribute like this.\nOn a slightly different topic, were you aware that all wxPython widgets already have a name attribute, which can be assigned using the name keyword argument at initialization time, and accessed using either GetName() or (in recent versions of wxPython) the property Name? If you don't assign it, it will default to some fairly generic class-specific value (like \"text\" or \"textctrl\" for wx.TextCtrl). Depending on what you're trying to do, maybe you can just use it instead of your own name and getName(). wxPython itself does not make any use of this value, as it's intended for you the programmer to use as you see fit.\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002302360_python_wxpython.txt
|
Q:
Manipulating dates in the datastore
I've recently been playing around with Google's AppEngine and I seem to have gotten stuck. I'm trying to create a query that selects posts that are before a certain date (in this case, the date is now - 1 day). I've tried a few different methods in order to accomplish this, but none have worked. One of which involved converting all the dates to UNIX time and running a query like this:
db.GqlQuery("SELECT __key__ FROM Post WHERE date-84600 < %s LIMIT 10, ORDER BY date DESC" % time.time())
But after trying that, I got a syntax error which told me GQL didn't have support for operations such as subtracting in the queries.
Does anyone have any idea as to how I could accomplish this?
Thanks in advance
A:
What happens if you build your query using methods?
query = Post.all()
query.filter('date < ', datetime.datetime - 84600)
results = query.fetch(limit=10)
A:
You need to move the math outside of the query:
db.GqlQuery("SELECT __key__ FROM Post WHERE date < :1 LIMIT 10, ORDER BY date DESC", (time.time() - 84600))
|
Manipulating dates in the datastore
|
I've recently been playing around with Google's AppEngine and I seem to have gotten stuck. I'm trying to create a query that selects posts that are before a certain date (in this case, the date is now - 1 day). I've tried a few different methods in order to accomplish this, but none have worked. One of which involved converting all the dates to UNIX time and running a query like this:
db.GqlQuery("SELECT __key__ FROM Post WHERE date-84600 < %s LIMIT 10, ORDER BY date DESC" % time.time())
But after trying that, I got a syntax error which told me GQL didn't have support for operations such as subtracting in the queries.
Does anyone have any idea as to how I could accomplish this?
Thanks in advance
|
[
"What happens if you build your query using methods?\nquery = Post.all()\nquery.filter('date < ', datetime.datetime - 84600)\nresults = query.fetch(limit=10)\n\n",
"You need to move the math outside of the query:\ndb.GqlQuery(\"SELECT __key__ FROM Post WHERE date < :1 LIMIT 10, ORDER BY date DESC\", (time.time() - 84600))\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"database",
"google_app_engine",
"python"
] |
stackoverflow_0002300759_database_google_app_engine_python.txt
|
Q:
What's the way to keep the dictionary parameter order in Python?
def createNode(doc_, **param_):
cache = {'p':'property','l':'label','td':'totalDelay','rd':'routeDelay','ld':'logicDelay'}
for index in param_:
newIndex = cache[index]
value = param_[index]
print newIndex, '=', value
doc = 10
createNode(doc, p='path', l='ifft4k_radix4_noUnolling_core.vi', td='3.0', ld='1.0', rd='2.0')
Running this code on Python 2.6 gives me the following result.
routeDelay = 2.0
property = path
totalDelay = 3.0
logicDelay = 1.0
label = ifft4k_radix4_noUnolling_core.vi
I need to keep the order of the parameters, I mean, property comes first, then label until I get routeDelay last.
Q : What's the way to keep the dictionary parameter order in Python?
A:
I need to keep the order of the
parameter, I mean, property comes
first, then label until I get
reouteDelay last.
Then you're simply doing things in the wrong order -- no need for ordered dictionaries! Try, instead, a tuple of pairs for cache, as follows:
def createNode(doc_, **param_):
cache = ( ('p', 'property'), , ('l', 'label'), ('td', 'totalDelay'),
('rd', 'routeDelay'), ('ld', 'logicDelay') )
for index, newIndex in cache:
if index not in param_:
continue
value = param_[index]
print newIndex, '=', value
This has exactly the same semantics as your version of createNode, plus the desired property of maintaining the order you wish, and performance is at least as good. By focusing on "keeping the dictionary ordered" you're focusing on the wrong problem (as is the case, alas, for most cases where people reach for "ordered dictionaries"!-).
A:
A regular dictionary won't do, you'll have to use an ordered dictionary instead. Check out these links:
PEP 372: Adding an ordered dictionary to collections
Using an ordered dict as object dictionary in python -- an SO question to prove that people are using PEP 372's odict :-)
Nicola Larosa & Michael Foord's odict module
Try the search term "python ordered dictionary" if you want to Google around for more. I remember seeing a number of ordered dict related questions here, on SO, so if the above links are inadequate for some reason, perhaps you can find something better in some other question.
Update: Mark's suggestion to use a list of tuples may be perfectly good, actually, but named tuples may be more convenient: a relevant fragment in the docs. Also, if you're planning to do some serialisation / deserialisation on your data and would like to do it really fast, check out Google's protocol buffers (Python tooling available).
A:
Dictionaries don't preserve the order of the keys. You could use a list of tuples instead of a dictionary.
|
What's the way to keep the dictionary parameter order in Python?
|
def createNode(doc_, **param_):
cache = {'p':'property','l':'label','td':'totalDelay','rd':'routeDelay','ld':'logicDelay'}
for index in param_:
newIndex = cache[index]
value = param_[index]
print newIndex, '=', value
doc = 10
createNode(doc, p='path', l='ifft4k_radix4_noUnolling_core.vi', td='3.0', ld='1.0', rd='2.0')
Running this code on Python 2.6 gives me the following result.
routeDelay = 2.0
property = path
totalDelay = 3.0
logicDelay = 1.0
label = ifft4k_radix4_noUnolling_core.vi
I need to keep the order of the parameters, I mean, property comes first, then label until I get routeDelay last.
Q : What's the way to keep the dictionary parameter order in Python?
|
[
"\nI need to keep the order of the\n parameter, I mean, property comes\n first, then label until I get\n reouteDelay last.\n\nThen you're simply doing things in the wrong order -- no need for ordered dictionaries! Try, instead, a tuple of pairs for cache, as follows:\ndef createNode(doc_, **param_):\n cache = ( ('p', 'property'), , ('l', 'label'), ('td', 'totalDelay'),\n ('rd', 'routeDelay'), ('ld', 'logicDelay') )\n for index, newIndex in cache:\n if index not in param_:\n continue\n value = param_[index]\n print newIndex, '=', value\n\nThis has exactly the same semantics as your version of createNode, plus the desired property of maintaining the order you wish, and performance is at least as good. By focusing on \"keeping the dictionary ordered\" you're focusing on the wrong problem (as is the case, alas, for most cases where people reach for \"ordered dictionaries\"!-).\n",
"A regular dictionary won't do, you'll have to use an ordered dictionary instead. Check out these links:\n\nPEP 372: Adding an ordered dictionary to collections\nUsing an ordered dict as object dictionary in python -- an SO question to prove that people are using PEP 372's odict :-)\nNicola Larosa & Michael Foord's odict module\n\nTry the search term \"python ordered dictionary\" if you want to Google around for more. I remember seeing a number of ordered dict related questions here, on SO, so if the above links are inadequate for some reason, perhaps you can find something better in some other question.\nUpdate: Mark's suggestion to use a list of tuples may be perfectly good, actually, but named tuples may be more convenient: a relevant fragment in the docs. Also, if you're planning to do some serialisation / deserialisation on your data and would like to do it really fast, check out Google's protocol buffers (Python tooling available).\n",
"Dictionaries don't preserve the order of the keys. You could use a list of tuples instead of a dictionary.\n"
] |
[
7,
6,
3
] |
[] |
[] |
[
"parameter_passing",
"python"
] |
stackoverflow_0002302663_parameter_passing_python.txt
|
Q:
Pass error on socket
I am writing a general Client-Server socket program where the client sends commands to the Server, which executes it and sends the result to the Client.
However if there is an error while executing a command, I want to be able to inform the Client of an error. I know I could send the String "ERROR" or maybe something like -1 etc, but these could also be part of the command output. Is there any better way of sending an error or an exception over a socket.
My Server is in Java and Client is in Python
A:
Typically when doing client-server communication you need to establish some kind of protocol. One very simple protocol is to send the String "COMMAND" before you send any commands and the String "ERROR" before you send any errors. This doubles the number of Strings you have to send but gives more flexibility.
There are also a number of more sophisticated protocols already developed. Rather than sending Strings you could construct a Request object which you then serialize and send to the client. The client can then reconstruct the Request object and perform the request whether it's performing an error or running a command.
A:
You're already (necessarily) establishing some format or protocol whereby strings are being sent back and forth -- either you're somehow terminating each string, or sending its length first, or the like. (TCP is intrinsically just a stream so without such a protocol there would be no way the recipient could possibly know when the command or output is finished!-)
So, whatever approach you're using to delimiting strings, just make it so the results sent back from server to client are two strings each and every time: one being the error description (empty if no error), the other being the commands's results (empty if no results). That's going to be trivial both to send and receive/parse, and have minimal overhead (sending an empty string should be as simple as sending just a terminator or a length of 0).
|
Pass error on socket
|
I am writing a general Client-Server socket program where the client sends commands to the Server, which executes it and sends the result to the Client.
However if there is an error while executing a command, I want to be able to inform the Client of an error. I know I could send the String "ERROR" or maybe something like -1 etc, but these could also be part of the command output. Is there any better way of sending an error or an exception over a socket.
My Server is in Java and Client is in Python
|
[
"Typically when doing client-server communication you need to establish some kind of protocol. One very simple protocol is to send the String \"COMMAND\" before you send any commands and the String \"ERROR\" before you send any errors. This doubles the number of Strings you have to send but gives more flexibility.\nThere are also a number of more sophisticated protocols already developed. Rather than sending Strings you could construct a Request object which you then serialize and send to the client. The client can then reconstruct the Request object and perform the request whether it's performing an error or running a command.\n",
"You're already (necessarily) establishing some format or protocol whereby strings are being sent back and forth -- either you're somehow terminating each string, or sending its length first, or the like. (TCP is intrinsically just a stream so without such a protocol there would be no way the recipient could possibly know when the command or output is finished!-)\nSo, whatever approach you're using to delimiting strings, just make it so the results sent back from server to client are two strings each and every time: one being the error description (empty if no error), the other being the commands's results (empty if no results). That's going to be trivial both to send and receive/parse, and have minimal overhead (sending an empty string should be as simple as sending just a terminator or a length of 0).\n"
] |
[
0,
0
] |
[] |
[] |
[
"java",
"python",
"sockets"
] |
stackoverflow_0002302761_java_python_sockets.txt
|
Q:
How to test whether a variable has been initialized before using it?
So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use if __name__ == '__main__').
Also, there is a method that is to be called for when a client imports the application for use within another application. This method will also instantiate this variable.
What I want to do is test whether the variable has already been instantiated before defining it (so I don't have to go through the creation of the object twice). My intuition told me to use if SOME_VARIABLE is not None: #instantiate here but this yields the error
local variable 'SOME_VARIABLE'
referenced before assignment
What gives?
A:
It's an error to access a variable before it is initialized. An uninitialized variable's value isn't None; accessing it just raises an exception.
You can catch the exception if you like:
>>> try:
... foo = x
... except NameError:
... x = 5
... foo = 1
In a class, you can provide a default value of None and check for that to see if it has changed on a particular instance (assuming that None isn't a valid value for that particular variable):
class Foo(object):
bar = None
def foo(self):
if self.bar is None:
self.bar = 5
return self.bar
A:
You can try if 'varname' in locals() (you probably also have to check globals(), and maybe some other places), or just read from the variable and catch the NameError exception which will be thrown when it doesn't exist.
But if you just want the else-case of if __name__ == '__main__', why not just do:
if __name__ == '__main__'
myvar = 'as_main'
else:
myvar = 'as_import'
|
How to test whether a variable has been initialized before using it?
|
So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use if __name__ == '__main__').
Also, there is a method that is to be called for when a client imports the application for use within another application. This method will also instantiate this variable.
What I want to do is test whether the variable has already been instantiated before defining it (so I don't have to go through the creation of the object twice). My intuition told me to use if SOME_VARIABLE is not None: #instantiate here but this yields the error
local variable 'SOME_VARIABLE'
referenced before assignment
What gives?
|
[
"It's an error to access a variable before it is initialized. An uninitialized variable's value isn't None; accessing it just raises an exception.\nYou can catch the exception if you like:\n>>> try:\n... foo = x\n... except NameError:\n... x = 5\n... foo = 1\n\nIn a class, you can provide a default value of None and check for that to see if it has changed on a particular instance (assuming that None isn't a valid value for that particular variable):\nclass Foo(object):\n bar = None\n def foo(self):\n if self.bar is None:\n self.bar = 5\n return self.bar\n\n",
"You can try if 'varname' in locals() (you probably also have to check globals(), and maybe some other places), or just read from the variable and catch the NameError exception which will be thrown when it doesn't exist.\nBut if you just want the else-case of if __name__ == '__main__', why not just do:\nif __name__ == '__main__'\n myvar = 'as_main'\nelse:\n myvar = 'as_import'\n\n"
] |
[
18,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002303005_python.txt
|
Q:
how to use array in django
I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using IntegerField but on save it is giving error
int() argument must be a string or a number, not 'list
How can I add this field to my model? I am using this field in my views.py so I need to add it in my model. Any suggestions?
A:
You may be interested in using a CommaSeparatedIntegerField.
If you've got a list of integers like this:
my_ints = [1,2,3,4,5]
and a model like this:
class MyModel(models.Model):
values = CommaSeparatedIntegerField(max_length = 200)
then you can save my_ints into a MyModel like this:
m = MyModel(values = ','.join(my_ints))
m.save()
A:
I would look into database normalization. In particular, your database is not even in 1st normal form, the first and probably most significant of the normal forms which states that normalized data should not contain any repeating groups. As a result, the Django object-relational-mapper will have considerable difficulty modeling your data.
By supporting only single, non-repeating types, Django in a sense enforces 1st normal form in data. You could try to write your own SQL to manage this particular field or perhaps find some code on the internet, but perhaps better would be to refactor this field into a many-to-one relationship in its own model. You can find Django documentation on this here.
A:
Clueless' answer is probably the best you can get, but in case you still want to store array of numbers in single field, you can do this - either by manually e.g. pickling it and then storing to TextField, or by writing custom model field that do something like this for you automatically.
Here's the doc: http://docs.djangoproject.com/en/1.1/howto/custom-model-fields/
A:
I got it working by saying textfield in my model.Since i am only using that field for reading it doesnot effect me
|
how to use array in django
|
I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using IntegerField but on save it is giving error
int() argument must be a string or a number, not 'list
How can I add this field to my model? I am using this field in my views.py so I need to add it in my model. Any suggestions?
|
[
"You may be interested in using a CommaSeparatedIntegerField.\nIf you've got a list of integers like this:\nmy_ints = [1,2,3,4,5]\n\nand a model like this:\nclass MyModel(models.Model):\n values = CommaSeparatedIntegerField(max_length = 200)\n\nthen you can save my_ints into a MyModel like this:\nm = MyModel(values = ','.join(my_ints))\nm.save()\n\n",
"I would look into database normalization. In particular, your database is not even in 1st normal form, the first and probably most significant of the normal forms which states that normalized data should not contain any repeating groups. As a result, the Django object-relational-mapper will have considerable difficulty modeling your data.\nBy supporting only single, non-repeating types, Django in a sense enforces 1st normal form in data. You could try to write your own SQL to manage this particular field or perhaps find some code on the internet, but perhaps better would be to refactor this field into a many-to-one relationship in its own model. You can find Django documentation on this here.\n",
"Clueless' answer is probably the best you can get, but in case you still want to store array of numbers in single field, you can do this - either by manually e.g. pickling it and then storing to TextField, or by writing custom model field that do something like this for you automatically. \nHere's the doc: http://docs.djangoproject.com/en/1.1/howto/custom-model-fields/\n",
"I got it working by saying textfield in my model.Since i am only using that field for reading it doesnot effect me\n"
] |
[
7,
1,
1,
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002197975_django_django_models_python.txt
|
Q:
Dump django debug output to a file?
I noticed in the django documentation that when DEBUG is False it will mail your configured ADMINS the full exception information.
Is there an easy way to dump the full exception information this to a file?
A:
No, but you can find or write middleware to catch it.
|
Dump django debug output to a file?
|
I noticed in the django documentation that when DEBUG is False it will mail your configured ADMINS the full exception information.
Is there an easy way to dump the full exception information this to a file?
|
[
"No, but you can find or write middleware to catch it.\n"
] |
[
1
] |
[] |
[] |
[
"debugging",
"django",
"python"
] |
stackoverflow_0002302926_debugging_django_python.txt
|
Q:
Python class methods
In Python, which is the best way (style wise) to allow public access to an object's variables?
There are lots of options I've seen from different languages, I was wondering which of these (if any) is the preferred Python method? These are the options I'm currently torn between:
Allow direct access to object variables (e.g. print(object.variable)), ignore data hiding
Allow access to object variables by a wrapper function:
class X:
variable_a = 0
variable_b = 0
...
def get_variable_a(self):
return self.variable_a
If this is the recommended way, how do you name the methods? (get_variablename(), or just variablename etc?)
What does everyone recommend for this?
thanks!
Lucy
A:
Don't bother using accessors until they're necessary; converting a simple attribute to a property is quick and easy, and doesn't need modification of client code.
When I write a property, I use _get_FOO() and _set_FOO() for the accessors, and _FOO for the attribute itself.
A:
There are no "private" variables in Python. Check section 9.6 of this document http://docs.python.org/tutorial/classes.html
There is a convention though, that the users of the class should treat variables with names, starting with underscore to be not touched directly. Still, there is no mechanism which may prevent this.
Same with the mangled names (starting with 2 underscores).
A:
Just allow direct access to any variables that you wish to expose as the public API. If you need to change the behavior you can always turn it into a property later on.
Notice that this is orthogonal to information hiding. obj.get_some_implementation_detail() is no better than obj.some_implementation_detail.
|
Python class methods
|
In Python, which is the best way (style wise) to allow public access to an object's variables?
There are lots of options I've seen from different languages, I was wondering which of these (if any) is the preferred Python method? These are the options I'm currently torn between:
Allow direct access to object variables (e.g. print(object.variable)), ignore data hiding
Allow access to object variables by a wrapper function:
class X:
variable_a = 0
variable_b = 0
...
def get_variable_a(self):
return self.variable_a
If this is the recommended way, how do you name the methods? (get_variablename(), or just variablename etc?)
What does everyone recommend for this?
thanks!
Lucy
|
[
"Don't bother using accessors until they're necessary; converting a simple attribute to a property is quick and easy, and doesn't need modification of client code.\nWhen I write a property, I use _get_FOO() and _set_FOO() for the accessors, and _FOO for the attribute itself.\n",
"There are no \"private\" variables in Python. Check section 9.6 of this document http://docs.python.org/tutorial/classes.html\nThere is a convention though, that the users of the class should treat variables with names, starting with underscore to be not touched directly. Still, there is no mechanism which may prevent this.\nSame with the mangled names (starting with 2 underscores).\n",
"Just allow direct access to any variables that you wish to expose as the public API. If you need to change the behavior you can always turn it into a property later on.\nNotice that this is orthogonal to information hiding. obj.get_some_implementation_detail() is no better than obj.some_implementation_detail.\n"
] |
[
4,
3,
2
] |
[
"You can use\nGetters and setters (Java like)\nclass SomeClass(object):\n ...\n\n def get_x(self):\n return self._x\n def set_x(self, x):\n self._x = x\n\nc = SomeClass()\nprint c.get_x()\nc.set_x(10)\n\nProperties (C# like)\nclass SomeClass(object):\n ...\n\n def get_x(self):\n return self._x\n def set_x(self, x):\n self._x = x\n x = property(get_x, set_x)\n\nc = SomeClass()\nprint c.x\nc.x = 10\n\nI think it is merely a matter of style. Choose the one you like better. Same applies to the naming convention, choose one convention and stick to it.\nIn any case, data hiding can be done with pseudo-private variables (beginning with two underscores). They cannot be accessed directly, as opposed to the example variables (_x not starting with two underscores).\n"
] |
[
-1
] |
[
"class",
"python"
] |
stackoverflow_0002303414_class_python.txt
|
Q:
How to install python module as a command line application under windows?
I need to install a python module in the site packages that also will be used as a command line application. Suppose I have a module like:
app.py
def main():
print 'Dummy message'
if __name__ == '__main__':
main()
setup.py
import distutils
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if __name__ == '__main__':
setup(name = 'dummy',
version = '1.0',
packages = ['dummy'],
)
Creating the dist by:
setup.py sdist
Install:
setup.py install
And now I would like to use it as a command line application by opening the command window and typing just: dummy
Is it possible to create such application under windows without to carry out registering system pat variables and so on ...
A:
You can use the options in setup.py to declare command line scripts. Please refer to this article. On Windows, the script will be created in "C:\Python26\Scripts" (if you didn't change the path) - lots of tools store their scripts there (e.g. "easy_install", "hg", ...).
A:
Put the following in dummy.cmd:
python.exe -m dummy
Or is it dummy.app...
Oh well, it's one of those.
|
How to install python module as a command line application under windows?
|
I need to install a python module in the site packages that also will be used as a command line application. Suppose I have a module like:
app.py
def main():
print 'Dummy message'
if __name__ == '__main__':
main()
setup.py
import distutils
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if __name__ == '__main__':
setup(name = 'dummy',
version = '1.0',
packages = ['dummy'],
)
Creating the dist by:
setup.py sdist
Install:
setup.py install
And now I would like to use it as a command line application by opening the command window and typing just: dummy
Is it possible to create such application under windows without to carry out registering system pat variables and so on ...
|
[
"You can use the options in setup.py to declare command line scripts. Please refer to this article. On Windows, the script will be created in \"C:\\Python26\\Scripts\" (if you didn't change the path) - lots of tools store their scripts there (e.g. \"easy_install\", \"hg\", ...).\n",
"Put the following in dummy.cmd:\npython.exe -m dummy\n\nOr is it dummy.app...\nOh well, it's one of those.\n"
] |
[
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002303434_python.txt
|
Q:
GAE Chat Data Persistance in Memcache
I'm writing a chat feature (like the Faceboook.com one) for a Google App Engine site. I need a way to keep track of what users have new messages. I'm currently trying to use Memcache:
class Message():
def __init__(self, from_user_key, message_text)
self.from_user_key = from_user_key
self.message_text = message_text
class NewMessages():
def __init__(self):
self.messages = []
def add_message(self, message):
self.messages.append(message)
def get_messages(self):
return self.messages
def messages_sent(self):
self.messages = [] #Clear all messages
def ChatUserManager():
def load(user_key):
manager = memcache.get("chat_user_%s" % user_key)
if manager is not None:
return manager
else:
manager = ChatUserManager(user_key)
memcache.set("chat_user_%s" % user_key, manager)
return manager
def save(self):
memcache.set("chat_user_%s" % user_key, self)
def __init__(self, user_key):
self.online = True
self.new_messages = NewMessages()
self.new_data = False
self.user_key = user_key
def recieve_message(self, message):
self.new_data = True
self.new_messages.add_message(Message(from_user_key, message_text))
def send_message(self, message):
to_manager = ChatUserManager.load(message.from_user_key)
to_manager.recieve_message(message)
def client_receive_success(self):
self.new_data = False
self.new_messages.messages_sent()
This chat is user to user, like Facebook or an IM session, not group chat.
Each user will poll a url with ajax to get new messages addressed to them every x seconds. The chat manager will be loaded on that page (ChatUserManager.load(user_key)) and new messages will be checked for. When they are sent the manager will be told that the messages have been sent (manager.client_receive_success()), and then saved back to memcache (manager.save()).
When a user sends a message in the javascript client, it will send an ajax request to a url. The url will load the client's UserChatManager and call .send_message(Message(to_user_key, message_string))).
I'm concerned about the practicality of this model. If everything is in memcache how will it be synchronized across different pages?
Is there a better way to do this?
I do admit that I'm not a python pro yet so the code might not be very pythonic, are there any best practices I'm missing?
A:
The problem isn't so much about how to share data between "pages" but how will the usability of the service will be impacted by using memcache.
There are no guarantees associated with data persistence in memcache: one moment its there, the other it might not.
|
GAE Chat Data Persistance in Memcache
|
I'm writing a chat feature (like the Faceboook.com one) for a Google App Engine site. I need a way to keep track of what users have new messages. I'm currently trying to use Memcache:
class Message():
def __init__(self, from_user_key, message_text)
self.from_user_key = from_user_key
self.message_text = message_text
class NewMessages():
def __init__(self):
self.messages = []
def add_message(self, message):
self.messages.append(message)
def get_messages(self):
return self.messages
def messages_sent(self):
self.messages = [] #Clear all messages
def ChatUserManager():
def load(user_key):
manager = memcache.get("chat_user_%s" % user_key)
if manager is not None:
return manager
else:
manager = ChatUserManager(user_key)
memcache.set("chat_user_%s" % user_key, manager)
return manager
def save(self):
memcache.set("chat_user_%s" % user_key, self)
def __init__(self, user_key):
self.online = True
self.new_messages = NewMessages()
self.new_data = False
self.user_key = user_key
def recieve_message(self, message):
self.new_data = True
self.new_messages.add_message(Message(from_user_key, message_text))
def send_message(self, message):
to_manager = ChatUserManager.load(message.from_user_key)
to_manager.recieve_message(message)
def client_receive_success(self):
self.new_data = False
self.new_messages.messages_sent()
This chat is user to user, like Facebook or an IM session, not group chat.
Each user will poll a url with ajax to get new messages addressed to them every x seconds. The chat manager will be loaded on that page (ChatUserManager.load(user_key)) and new messages will be checked for. When they are sent the manager will be told that the messages have been sent (manager.client_receive_success()), and then saved back to memcache (manager.save()).
When a user sends a message in the javascript client, it will send an ajax request to a url. The url will load the client's UserChatManager and call .send_message(Message(to_user_key, message_string))).
I'm concerned about the practicality of this model. If everything is in memcache how will it be synchronized across different pages?
Is there a better way to do this?
I do admit that I'm not a python pro yet so the code might not be very pythonic, are there any best practices I'm missing?
|
[
"The problem isn't so much about how to share data between \"pages\" but how will the usability of the service will be impacted by using memcache.\nThere are no guarantees associated with data persistence in memcache: one moment its there, the other it might not.\n"
] |
[
3
] |
[] |
[] |
[
"chat",
"google_app_engine",
"python"
] |
stackoverflow_0002303751_chat_google_app_engine_python.txt
|
Q:
Is there any purpose for a python application use C other than performance?
If Python was so fast as C, the latter would be present in python apps/libraries?
Example: if Python was fast as C would PIL be written completely in Python?
A:
To access "legacy" C libraries and OS facilities.
A:
While you can of course use ctypes to access existing C code, you might not necessarily want to, in sufficiently complex cases: when you're coding to an interface designed for (and implemented in) C, not doing compilation can mean that small errors on the caller's side, that would simply refuse to compile properly in C, can result in crashes of the whole application.
So, using C code (rather than ctypes) for the purpose of reusing good existing C code can make a lot of sense (Cython is fine too, of course, since it does generate C code that, in case of caller-side errors, should fail to compile;-).
Recoding everything from scratch, rather than reusing good, existing, solid and finely tuned code, doesn't make much sense either way, of course -- there are so many interesting new problems to conquer, that spending your time just mimicking an existing, just-fine solution to an old and already-conquered problem is likely not going to be the best, most productive, and most satisfactory way to spend your time;-).
A:
It makes sense to use C modules in Python for:
Performance
Libraries that won't be ported to Python (because of performance reasons, for example) or that use OS-specific functions
Scripting. For example, many games use Python, Lua and other languages as scripting languages. Therefore they expose C/C++ functions to Python.
As to your example: Yes, but Python is inherently slower than C. If both were equally fast, it would make sense to use Python because C code is often more prone to attacks (buffer overflows and stuff).
A:
To access hardware.
|
Is there any purpose for a python application use C other than performance?
|
If Python was so fast as C, the latter would be present in python apps/libraries?
Example: if Python was fast as C would PIL be written completely in Python?
|
[
"To access \"legacy\" C libraries and OS facilities.\n",
"While you can of course use ctypes to access existing C code, you might not necessarily want to, in sufficiently complex cases: when you're coding to an interface designed for (and implemented in) C, not doing compilation can mean that small errors on the caller's side, that would simply refuse to compile properly in C, can result in crashes of the whole application.\nSo, using C code (rather than ctypes) for the purpose of reusing good existing C code can make a lot of sense (Cython is fine too, of course, since it does generate C code that, in case of caller-side errors, should fail to compile;-).\nRecoding everything from scratch, rather than reusing good, existing, solid and finely tuned code, doesn't make much sense either way, of course -- there are so many interesting new problems to conquer, that spending your time just mimicking an existing, just-fine solution to an old and already-conquered problem is likely not going to be the best, most productive, and most satisfactory way to spend your time;-).\n",
"It makes sense to use C modules in Python for:\n\nPerformance\nLibraries that won't be ported to Python (because of performance reasons, for example) or that use OS-specific functions\nScripting. For example, many games use Python, Lua and other languages as scripting languages. Therefore they expose C/C++ functions to Python.\n\nAs to your example: Yes, but Python is inherently slower than C. If both were equally fast, it would make sense to use Python because C code is often more prone to attacks (buffer overflows and stuff).\n",
"To access hardware.\n"
] |
[
7,
5,
2,
0
] |
[] |
[] |
[
"bytecode",
"c",
"performance",
"python"
] |
stackoverflow_0002303683_bytecode_c_performance_python.txt
|
Q:
What is the easiest way to implement a Comet serverside backend?
PHP as an Apache module or otherwise, would start one thread per pending request so it doesn't scale well.
Are Java and Python my only other options?
As a complete newbie to Python, is Twisted easy to use?
A:
Twisted is very powerful but not easy to use, especially for a newbie.
tornado is another async server in Python, less general than Twisted (you would not use it for a network client for example) but simpler to use to implement servers, including Comet ones.
A:
Investigate node.js. It's an evented server-side framework using JavaScript. It will not block communication with your browsers, since it's event-driven.
A:
My experience, been absolutely newbie with Twisted is that you can implement Comet easily with It. I've used Athena, which is included in Nevow. Nevow is built on top of Twisted. It's third pary.
Give it a try.
Here is an example.
|
What is the easiest way to implement a Comet serverside backend?
|
PHP as an Apache module or otherwise, would start one thread per pending request so it doesn't scale well.
Are Java and Python my only other options?
As a complete newbie to Python, is Twisted easy to use?
|
[
"Twisted is very powerful but not easy to use, especially for a newbie.\ntornado is another async server in Python, less general than Twisted (you would not use it for a network client for example) but simpler to use to implement servers, including Comet ones.\n",
"Investigate node.js. It's an evented server-side framework using JavaScript. It will not block communication with your browsers, since it's event-driven.\n",
"My experience, been absolutely newbie with Twisted is that you can implement Comet easily with It. I've used Athena, which is included in Nevow. Nevow is built on top of Twisted. It's third pary.\nGive it a try.\nHere is an example.\n"
] |
[
2,
1,
1
] |
[] |
[] |
[
"comet",
"http",
"php",
"push",
"python"
] |
stackoverflow_0002302145_comet_http_php_push_python.txt
|
Q:
Get zip code based on IP Address with Python
Is it possible to find the zip code based on a users IP address using python / django (not geodjango)? I assume I would have to use a web service, but I would really like to just be able to query a database if possible.
I am using geopy right now, so it would be cool if I could integrate that somehow.
A:
http://www.ip2location.com/python.aspx
import IP2Location;
IP2LocObj = IP2Location.IP2Location();
IP2LocObj.open("data/IP-COUNTRY-SAMPLE.BIN");
rec = IP2LocObj.get_all("19.5.10.1");
print rec.zipcode
I don't have any experience with this package but it looks like it will do what you want.
EDIT: Actually it looks like this is just searching through a data file that they sell -- so probably not that useful if you are looking for something free.
A:
You can't collect a real zip code from an IP address as these are assigned by ISP's when you route threw their connection.
|
Get zip code based on IP Address with Python
|
Is it possible to find the zip code based on a users IP address using python / django (not geodjango)? I assume I would have to use a web service, but I would really like to just be able to query a database if possible.
I am using geopy right now, so it would be cool if I could integrate that somehow.
|
[
"http://www.ip2location.com/python.aspx\nimport IP2Location;\n\nIP2LocObj = IP2Location.IP2Location();\nIP2LocObj.open(\"data/IP-COUNTRY-SAMPLE.BIN\");\nrec = IP2LocObj.get_all(\"19.5.10.1\");\n\nprint rec.zipcode\n\nI don't have any experience with this package but it looks like it will do what you want.\nEDIT: Actually it looks like this is just searching through a data file that they sell -- so probably not that useful if you are looking for something free.\n",
"You can't collect a real zip code from an IP address as these are assigned by ISP's when you route threw their connection.\n"
] |
[
1,
-2
] |
[] |
[] |
[
"django",
"geolocation",
"python"
] |
stackoverflow_0002303966_django_geolocation_python.txt
|
Q:
django having multiple one many to many relations that references same model
i have a model that is having multiple many to many relation to another model it is as follows:
class Match(models.Model):
"""Model docstring"""
Match_Id = models.AutoField(primary_key=True)
Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,)
Team_two = models.ManyToManyField('Team',related_name='Team two',symmetrical=False,)
stadium = models.CharField(max_length=255, blank=True)
Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
Rafree = models.CharField(max_length=255, blank=True)
Judge = models.CharField(max_length=255, blank=True)
winner = models.ForeignKey('Team', related_name='winner',to_field='Team_Name')
updated = models.DateTimeField('update date', auto_now=True )
created = models.DateTimeField('creation date', auto_now_add=True )
what is the best way to implement model like this ?. all though django does not throw any errors when passing the model sql once syncdb is excuted it throws up errors saying there is no unique constraint matching given keys
A:
Are you sure Team_one and Team_two should be ManyToMany fields? Surely, a match only has a single team on each side - in which case these should both be ForeignKeys.
A:
Using spaces in related_name attribute makes me uneasy, but I think the real problem is connected to the use of to_field attribute on the winner field. As far as I know you can set database relations only to unique fields. It doesn't really make sense to relate to another object using a field that may not be unique.
I'm not sure what do you want to achieve by connecting through this particular field. You usually connect models using primary key fields. This still allows you to access any other field on the related object.
|
django having multiple one many to many relations that references same model
|
i have a model that is having multiple many to many relation to another model it is as follows:
class Match(models.Model):
"""Model docstring"""
Match_Id = models.AutoField(primary_key=True)
Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,)
Team_two = models.ManyToManyField('Team',related_name='Team two',symmetrical=False,)
stadium = models.CharField(max_length=255, blank=True)
Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
Rafree = models.CharField(max_length=255, blank=True)
Judge = models.CharField(max_length=255, blank=True)
winner = models.ForeignKey('Team', related_name='winner',to_field='Team_Name')
updated = models.DateTimeField('update date', auto_now=True )
created = models.DateTimeField('creation date', auto_now_add=True )
what is the best way to implement model like this ?. all though django does not throw any errors when passing the model sql once syncdb is excuted it throws up errors saying there is no unique constraint matching given keys
|
[
"Are you sure Team_one and Team_two should be ManyToMany fields? Surely, a match only has a single team on each side - in which case these should both be ForeignKeys.\n",
"Using spaces in related_name attribute makes me uneasy, but I think the real problem is connected to the use of to_field attribute on the winner field. As far as I know you can set database relations only to unique fields. It doesn't really make sense to relate to another object using a field that may not be unique. \nI'm not sure what do you want to achieve by connecting through this particular field. You usually connect models using primary key fields. This still allows you to access any other field on the related object.\n"
] |
[
1,
1
] |
[] |
[] |
[
"database",
"django",
"django_models",
"python"
] |
stackoverflow_0002303778_database_django_django_models_python.txt
|
Q:
Print out the output of os.popen() without buffering in python
Let's say that I have a process that prints out some data something like this ruby code.
1.upto(10) {
|i|
puts i
puts "\n"
sleep 0.6
}
I want to have a python code that spawns this process, and read data from it to print it out.
import os
import sys
cmd = "ruby /Users/smcho/Desktop/testit.rb";
pingaling = os.popen(cmd,"r")
while 1:
line = pingaling.readline()
if not line: break
print line,
sys.stdout.flush()
pingaling.close()
The problem of this code is that it doesn't print the number one by one. It seems like that python prints out all the buffered data at the last point.
Is there a way to print out the output of spawned process without buffering?
A:
The data is being buffered by ruby. Use something like
$stdout.flush
to make it flush. I'm not sure if that's the correct ruby command to do that.
Obligatory:
Use subprocess module. os.popen has been replaced by it.
import subprocess
import sys
cmd = ["ruby", "/Users/smcho/Desktop/testit.rb"]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
print line,
sys.stdout.flush()
p.wait()
|
Print out the output of os.popen() without buffering in python
|
Let's say that I have a process that prints out some data something like this ruby code.
1.upto(10) {
|i|
puts i
puts "\n"
sleep 0.6
}
I want to have a python code that spawns this process, and read data from it to print it out.
import os
import sys
cmd = "ruby /Users/smcho/Desktop/testit.rb";
pingaling = os.popen(cmd,"r")
while 1:
line = pingaling.readline()
if not line: break
print line,
sys.stdout.flush()
pingaling.close()
The problem of this code is that it doesn't print the number one by one. It seems like that python prints out all the buffered data at the last point.
Is there a way to print out the output of spawned process without buffering?
|
[
"The data is being buffered by ruby. Use something like\n$stdout.flush\n\nto make it flush. I'm not sure if that's the correct ruby command to do that.\n\nObligatory:\nUse subprocess module. os.popen has been replaced by it.\nimport subprocess\nimport sys\n\ncmd = [\"ruby\", \"/Users/smcho/Desktop/testit.rb\"]\np = subprocess.Popen(cmd, stdout=subprocess.PIPE)\nfor line in iter(p.stdout.readline, ''):\n print line, \n sys.stdout.flush() \np.wait()\n\n"
] |
[
5
] |
[] |
[] |
[
"flush",
"popen",
"python",
"ruby"
] |
stackoverflow_0002304072_flush_popen_python_ruby.txt
|
Q:
_ElementInterface instance has no attribute 'tostring'
The code below generates this error. I can't figure out why. If ElementTree has parse, why doesn't it have tostring? http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree
from xml.etree.ElementTree import ElementTree
...
tree = ElementTree()
node = ElementTree()
node = tree.parse(open("my_xml.xml"))
text = node.tostring()
A:
tostring is a method of the xml.etree.ElementTree module, not the confusingly similarly-named xml.etree.ElementTree.ElementTree class.
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import tostring
tree = ElementTree()
node = tree.parse(open("my_xml.xml"))
text = tostring(node)
A:
tostring() is actually a function of the ElementTree module not a method of the ElementTree wrapper class.
>>> import xml.etree.ElementTree as ET
>>> x = ET.fromstring('<xml><one>one</one></xml>')
>>> x
<Element xml at 7f749572f710>
>>> ET.tostring(x)
'<xml><one>one</one></xml>'
|
_ElementInterface instance has no attribute 'tostring'
|
The code below generates this error. I can't figure out why. If ElementTree has parse, why doesn't it have tostring? http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree
from xml.etree.ElementTree import ElementTree
...
tree = ElementTree()
node = ElementTree()
node = tree.parse(open("my_xml.xml"))
text = node.tostring()
|
[
"tostring is a method of the xml.etree.ElementTree module, not the confusingly similarly-named xml.etree.ElementTree.ElementTree class.\nfrom xml.etree.ElementTree import ElementTree\nfrom xml.etree.ElementTree import tostring\n\ntree = ElementTree()\nnode = tree.parse(open(\"my_xml.xml\"))\ntext = tostring(node)\n\n",
"tostring() is actually a function of the ElementTree module not a method of the ElementTree wrapper class.\n>>> import xml.etree.ElementTree as ET\n>>> x = ET.fromstring('<xml><one>one</one></xml>')\n>>> x \n<Element xml at 7f749572f710>\n>>> ET.tostring(x)\n'<xml><one>one</one></xml>'\n\n"
] |
[
8,
3
] |
[
"The docs you've linked to do not support the existence of a ElementTree.tostring() method.\nAlso, your call to tree.parse() rebinds node.\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0002304082_python.txt
|
Q:
django database many2many relationship errors
hi i am using the following models to build a database
from django.db import models
from django.contrib import admin
class Team(models.Model):
"""Model docstring"""
slug = models.SlugField(max_length=200)
Team_ID = models.AutoField(primary_key=True)
Team_Name = models.CharField(max_length=100,)
College = models.CharField(max_length=100,)
College = models.CharField(max_length=1,)
Win = models.IntegerField()
Loss = models.IntegerField()
Draw = models.IntegerField()
class Match(models.Model):
Match_Id = models.AutoField(primary_key=True)
Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,)
Team_two = models.ManyToManyField('Team',related_name='Team two',symmetrical=False,)
stadium = models.CharField(max_length=255, blank=True)
Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
Rafree = models.CharField(max_length=255, blank=True)
Judge = models.CharField(max_length=255, blank=True)
winner = models.ForeignKey('Team', related_name='winner',to_field='Team_Name')
updated = models.DateTimeField('update date', auto_now=True )
created = models.DateTimeField('creation date', auto_now_add=True )
when i run the manage.py sqlall the model validate fine and gives me the sql output as follows
BEGIN;
CREATE TABLE "cupmanager_player" (
"slug" varchar(200) NOT NULL,
"Player_Id" serial NOT NULL PRIMARY KEY,
"Player_Name" varchar(100) NOT NULL,
"Nick" varchar(100) NOT NULL,
"Jersy_Number" integer NOT NULL,
"Team_id_id" integer NOT NULL,
"Poistion" varchar(1) NOT NULL,
"Red_card" integer NOT NULL,
"Yellow_card" integer NOT NULL,
"Points" integer NOT NULL
)
;
CREATE TABLE "cupmanager_team" (
"slug" varchar(200) NOT NULL,
"Team_ID" serial NOT NULL PRIMARY KEY,
"Team_Name" varchar(100) NOT NULL,
"College" varchar(1) NOT NULL,
"Win" integer NOT NULL,
"Loss" integer NOT NULL,
"Draw" integer NOT NULL
)
;
ALTER TABLE "cupmanager_player" ADD CONSTRAINT "Team_id_id_refs_Team_ID_1a532b57" FOREIGN KEY ("Team_id_id") REFERENCES "cupmanager_team" ("Team_ID") DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE "cupmanager_match" (
"Match_Id" serial NOT NULL PRIMARY KEY,
"stadium" varchar(255) NOT NULL,
"Start_time" timestamp with time zone,
"Rafree" varchar(255) NOT NULL,
"Judge" varchar(255) NOT NULL,
"winner_id" varchar(100) NOT NULL REFERENCES "cupmanager_team" ("Team_Name") DEFERRABLE INITIALLY DEFERRED,
"updated" timestamp with time zone NOT NULL,
"created" timestamp with time zone NOT NULL
)
;
CREATE TABLE "cupmanager_goal" (
"Goal_ID" serial NOT NULL PRIMARY KEY,
"Match_ID_id" integer NOT NULL REFERENCES "cupmanager_match" ("Match_Id") DEFERRABLE INITIALLY DEFERRED,
"Team_ID_id" varchar(100) NOT NULL REFERENCES "cupmanager_team" ("Team_Name") DEFERRABLE INITIALLY DEFERRED,
"Player_ID_id" varchar(100) NOT NULL REFERENCES "cupmanager_player" ("Player_Name") DEFERRABLE INITIALLY DEFERRED,
"name" varchar(100) NOT NULL,
"updated" timestamp with time zone NOT NULL,
"created" timestamp with time zone NOT NULL
)
;
CREATE TABLE "cupmanager_match_Team_one" (
"id" serial NOT NULL PRIMARY KEY,
"match_id" integer NOT NULL REFERENCES "cupmanager_match" ("Match_Id") DEFERRABLE INITIALLY DEFERRED,
"team_id" integer NOT NULL REFERENCES "cupmanager_team" ("Team_ID") DEFERRABLE INITIALLY DEFERRED,
UNIQUE ("match_id", "team_id")
)
;
CREATE TABLE "cupmanager_match_Team_two" (
"id" serial NOT NULL PRIMARY KEY,
"match_id" integer NOT NULL REFERENCES "cupmanager_match" ("Match_Id") DEFERRABLE INITIALLY DEFERRED,
"team_id" integer NOT NULL REFERENCES "cupmanager_team" ("Team_ID") DEFERRABLE INITIALLY DEFERRED,
UNIQUE ("match_id", "team_id")
)
;
CREATE INDEX "cupmanager_player_slug" ON "cupmanager_player" ("slug");
CREATE INDEX "cupmanager_player_Team_id_id" ON "cupmanager_player" ("Team_id_id");
CREATE INDEX "cupmanager_team_slug" ON "cupmanager_team" ("slug");
CREATE INDEX "cupmanager_match_winner_id" ON "cupmanager_match" ("winner_id");
CREATE INDEX "cupmanager_goal_Match_ID_id" ON "cupmanager_goal" ("Match_ID_id");
CREATE INDEX "cupmanager_goal_Team_ID_id" ON "cupmanager_goal" ("Team_ID_id");
CREATE INDEX "cupmanager_goal_Player_ID_id" ON "cupmanager_goal" ("Player_ID_id");
COMMIT;
but when i now run the manage.py syncdb command i get the following error
psycopg2.ProgrammingError: there is no unique constraint matching given keys for referenced table "cupmanager_team"
any idea what is going on here ? i am using postgresql as the db backend and Postgresql_psycopg2 as the db back end
A:
Mmh do you really have to use your own primary key fields? If you don't specify a primary key field, than Django automatically creates a field called id. I don't see a a benefit from naming the fields e.g. match_id, especially as you want to access this field later, it will look like match.match_id.
So maybe it works without your custom primary key fields.
Also not that the option symmetrical is only taken into account if the field is referencing self, i.e. the own table, which you are not doing here.
|
django database many2many relationship errors
|
hi i am using the following models to build a database
from django.db import models
from django.contrib import admin
class Team(models.Model):
"""Model docstring"""
slug = models.SlugField(max_length=200)
Team_ID = models.AutoField(primary_key=True)
Team_Name = models.CharField(max_length=100,)
College = models.CharField(max_length=100,)
College = models.CharField(max_length=1,)
Win = models.IntegerField()
Loss = models.IntegerField()
Draw = models.IntegerField()
class Match(models.Model):
Match_Id = models.AutoField(primary_key=True)
Team_one = models.ManyToManyField('Team',related_name='Team one',symmetrical=False,)
Team_two = models.ManyToManyField('Team',related_name='Team two',symmetrical=False,)
stadium = models.CharField(max_length=255, blank=True)
Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True)
Rafree = models.CharField(max_length=255, blank=True)
Judge = models.CharField(max_length=255, blank=True)
winner = models.ForeignKey('Team', related_name='winner',to_field='Team_Name')
updated = models.DateTimeField('update date', auto_now=True )
created = models.DateTimeField('creation date', auto_now_add=True )
when i run the manage.py sqlall the model validate fine and gives me the sql output as follows
BEGIN;
CREATE TABLE "cupmanager_player" (
"slug" varchar(200) NOT NULL,
"Player_Id" serial NOT NULL PRIMARY KEY,
"Player_Name" varchar(100) NOT NULL,
"Nick" varchar(100) NOT NULL,
"Jersy_Number" integer NOT NULL,
"Team_id_id" integer NOT NULL,
"Poistion" varchar(1) NOT NULL,
"Red_card" integer NOT NULL,
"Yellow_card" integer NOT NULL,
"Points" integer NOT NULL
)
;
CREATE TABLE "cupmanager_team" (
"slug" varchar(200) NOT NULL,
"Team_ID" serial NOT NULL PRIMARY KEY,
"Team_Name" varchar(100) NOT NULL,
"College" varchar(1) NOT NULL,
"Win" integer NOT NULL,
"Loss" integer NOT NULL,
"Draw" integer NOT NULL
)
;
ALTER TABLE "cupmanager_player" ADD CONSTRAINT "Team_id_id_refs_Team_ID_1a532b57" FOREIGN KEY ("Team_id_id") REFERENCES "cupmanager_team" ("Team_ID") DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE "cupmanager_match" (
"Match_Id" serial NOT NULL PRIMARY KEY,
"stadium" varchar(255) NOT NULL,
"Start_time" timestamp with time zone,
"Rafree" varchar(255) NOT NULL,
"Judge" varchar(255) NOT NULL,
"winner_id" varchar(100) NOT NULL REFERENCES "cupmanager_team" ("Team_Name") DEFERRABLE INITIALLY DEFERRED,
"updated" timestamp with time zone NOT NULL,
"created" timestamp with time zone NOT NULL
)
;
CREATE TABLE "cupmanager_goal" (
"Goal_ID" serial NOT NULL PRIMARY KEY,
"Match_ID_id" integer NOT NULL REFERENCES "cupmanager_match" ("Match_Id") DEFERRABLE INITIALLY DEFERRED,
"Team_ID_id" varchar(100) NOT NULL REFERENCES "cupmanager_team" ("Team_Name") DEFERRABLE INITIALLY DEFERRED,
"Player_ID_id" varchar(100) NOT NULL REFERENCES "cupmanager_player" ("Player_Name") DEFERRABLE INITIALLY DEFERRED,
"name" varchar(100) NOT NULL,
"updated" timestamp with time zone NOT NULL,
"created" timestamp with time zone NOT NULL
)
;
CREATE TABLE "cupmanager_match_Team_one" (
"id" serial NOT NULL PRIMARY KEY,
"match_id" integer NOT NULL REFERENCES "cupmanager_match" ("Match_Id") DEFERRABLE INITIALLY DEFERRED,
"team_id" integer NOT NULL REFERENCES "cupmanager_team" ("Team_ID") DEFERRABLE INITIALLY DEFERRED,
UNIQUE ("match_id", "team_id")
)
;
CREATE TABLE "cupmanager_match_Team_two" (
"id" serial NOT NULL PRIMARY KEY,
"match_id" integer NOT NULL REFERENCES "cupmanager_match" ("Match_Id") DEFERRABLE INITIALLY DEFERRED,
"team_id" integer NOT NULL REFERENCES "cupmanager_team" ("Team_ID") DEFERRABLE INITIALLY DEFERRED,
UNIQUE ("match_id", "team_id")
)
;
CREATE INDEX "cupmanager_player_slug" ON "cupmanager_player" ("slug");
CREATE INDEX "cupmanager_player_Team_id_id" ON "cupmanager_player" ("Team_id_id");
CREATE INDEX "cupmanager_team_slug" ON "cupmanager_team" ("slug");
CREATE INDEX "cupmanager_match_winner_id" ON "cupmanager_match" ("winner_id");
CREATE INDEX "cupmanager_goal_Match_ID_id" ON "cupmanager_goal" ("Match_ID_id");
CREATE INDEX "cupmanager_goal_Team_ID_id" ON "cupmanager_goal" ("Team_ID_id");
CREATE INDEX "cupmanager_goal_Player_ID_id" ON "cupmanager_goal" ("Player_ID_id");
COMMIT;
but when i now run the manage.py syncdb command i get the following error
psycopg2.ProgrammingError: there is no unique constraint matching given keys for referenced table "cupmanager_team"
any idea what is going on here ? i am using postgresql as the db backend and Postgresql_psycopg2 as the db back end
|
[
"Mmh do you really have to use your own primary key fields? If you don't specify a primary key field, than Django automatically creates a field called id. I don't see a a benefit from naming the fields e.g. match_id, especially as you want to access this field later, it will look like match.match_id.\nSo maybe it works without your custom primary key fields.\nAlso not that the option symmetrical is only taken into account if the field is referencing self, i.e. the own table, which you are not doing here.\n"
] |
[
1
] |
[] |
[] |
[
"database",
"django",
"django_models",
"postgresql",
"python"
] |
stackoverflow_0002303498_database_django_django_models_postgresql_python.txt
|
Q:
Automate conversion of Sybase .ADT files to SQL
I am working with some data I obtained that is read with a program using an embedded Advantage Database Server. The program was not written by me and does not have all of the functionality that I need. I would like to convert this data to a different format so that I can work with it more freely, such as MySQL.
I know that Sybase provides some tools for converting a single local database into SQL, which is very nice. This would work fine, except that the authors of this program create a new folder containing a new database for every new document that a users is working with. So there could be 100s of separate database folders each with 100s of .ADT files in them.
I am looking for a way to automate the process of converting these .ADT files and their schema to basically anything else. I've had more luck with almost all the other formats I've had to work with in the past, this one has been most troublesome. I don't need indexes, views, or any of that. I only need to export the tables to another format so that I can process some of the data.
So the solution I'm looking for here is just a way to automate the conversion of a single Advantage Database Server local database to SQL. So I have a folder of .ADT files that represent the database.
I included Ruby and Python in the tags because using one of these scripting languages would be ideal, but any solution would be great.
The route I'm on right now is trying to work with the ODBC drivers, but I'm having trouble and hoped that there was an easier solution.
Thanks!
Chase Gray
A:
Advantage has a dbi (Perl) driver you could use to access the tables in their existing ADT format. Also has JDBC and OLE DB drivers. See all of them at http://devzone.advantagedatabase.com/dz/content.aspx?key=20&Release=13
Note that link is to the version 9.1 drivers. You will want to grab a driver that is equal to or older than the Advantage server that is running (unless the client is using the Advantage Local Server, in which case it won't matter).
A:
After some asking and searching it seems that there isn't something like what I was looking for.
I spent a little while earlier today putting something together based on the Ruby DBF gem. I'm not finished, but it works like I want it to. I'll have to finish up the tests and add the exporting of SQL, etc. but hopefully somebody else finds this question and can retrieve information from a .ADT file without having to install anything.
Here is the link to the project. It'll be in progress for the rest of the night probably. It's pretty minimal right now, but over time I'll probably add to it.
http://github.com/chasemgray/Ruby-ADT
http://chase.ratchetsoftware.com/2010/02/reading-advantage-database-server-files-adt-in-ruby/
Now getting data out should be as simple as this.
require 'adt'
table = ADT::Table.new("test.adt")
table.each do |record|
puts record.name
puts record.email
end
Thanks for your help,
Chase Gray
|
Automate conversion of Sybase .ADT files to SQL
|
I am working with some data I obtained that is read with a program using an embedded Advantage Database Server. The program was not written by me and does not have all of the functionality that I need. I would like to convert this data to a different format so that I can work with it more freely, such as MySQL.
I know that Sybase provides some tools for converting a single local database into SQL, which is very nice. This would work fine, except that the authors of this program create a new folder containing a new database for every new document that a users is working with. So there could be 100s of separate database folders each with 100s of .ADT files in them.
I am looking for a way to automate the process of converting these .ADT files and their schema to basically anything else. I've had more luck with almost all the other formats I've had to work with in the past, this one has been most troublesome. I don't need indexes, views, or any of that. I only need to export the tables to another format so that I can process some of the data.
So the solution I'm looking for here is just a way to automate the conversion of a single Advantage Database Server local database to SQL. So I have a folder of .ADT files that represent the database.
I included Ruby and Python in the tags because using one of these scripting languages would be ideal, but any solution would be great.
The route I'm on right now is trying to work with the ODBC drivers, but I'm having trouble and hoped that there was an easier solution.
Thanks!
Chase Gray
|
[
"Advantage has a dbi (Perl) driver you could use to access the tables in their existing ADT format. Also has JDBC and OLE DB drivers. See all of them at http://devzone.advantagedatabase.com/dz/content.aspx?key=20&Release=13\nNote that link is to the version 9.1 drivers. You will want to grab a driver that is equal to or older than the Advantage server that is running (unless the client is using the Advantage Local Server, in which case it won't matter).\n",
"After some asking and searching it seems that there isn't something like what I was looking for. \nI spent a little while earlier today putting something together based on the Ruby DBF gem. I'm not finished, but it works like I want it to. I'll have to finish up the tests and add the exporting of SQL, etc. but hopefully somebody else finds this question and can retrieve information from a .ADT file without having to install anything.\nHere is the link to the project. It'll be in progress for the rest of the night probably. It's pretty minimal right now, but over time I'll probably add to it.\nhttp://github.com/chasemgray/Ruby-ADT\nhttp://chase.ratchetsoftware.com/2010/02/reading-advantage-database-server-files-adt-in-ruby/\nNow getting data out should be as simple as this.\nrequire 'adt'\n\ntable = ADT::Table.new(\"test.adt\")\n\ntable.each do |record|\n puts record.name\n puts record.email\nend\n\nThanks for your help,\nChase Gray\n"
] |
[
2,
2
] |
[] |
[] |
[
"advantage_database_server",
"python",
"ruby",
"sybase"
] |
stackoverflow_0002289519_advantage_database_server_python_ruby_sybase.txt
|
Q:
Numeric data collection from an mp3 in python
Anyone know how I can plot numeric data from an mp3 in real time?
For example the script plays a mp3 and as its playing prints 3 sets of numeric data.
A:
You could use the Veusz python package that supports realtime plotting of data.
|
Numeric data collection from an mp3 in python
|
Anyone know how I can plot numeric data from an mp3 in real time?
For example the script plays a mp3 and as its playing prints 3 sets of numeric data.
|
[
"You could use the Veusz python package that supports realtime plotting of data.\n"
] |
[
0
] |
[] |
[] |
[
"graphical_programming",
"mp3",
"numeric",
"python"
] |
stackoverflow_0002303958_graphical_programming_mp3_numeric_python.txt
|
Q:
pycurl request exist in header function?
in C do return -1 when i want to cancel the download in either the header or the write function. In pycurl i get this error
pycurl.error: invalid return value for write callback -1 17
I dont know what the 17 means but what am i not doing correctly?
A:
from pycurl.c:
else if (PyInt_Check(result)) {
long obj_size = PyInt_AsLong(result);
if (obj_size < 0 || obj_size > total_size) {
PyErr_Format(ErrorObject, "invalid return value for write callback %ld %ld", (long)obj_size, (long)total_size);
goto verbose_error;
}
this would mean 17 is the total_size - is this possible ? and -1 (result) is what your callback is returning.
A:
import pycurl
import StringIO
c = pycurl.Curl()
s = StringIO.StringIO()
c.setopt(pycurl.URL, url)
c.setopt(pycurl.HEADER, True)
c.setopt(pycurl.NOBODY, True)
c.setopt(pycurl.WRITEFUNCTION, s.write)
c.perform()
print(s.getvalue())
|
pycurl request exist in header function?
|
in C do return -1 when i want to cancel the download in either the header or the write function. In pycurl i get this error
pycurl.error: invalid return value for write callback -1 17
I dont know what the 17 means but what am i not doing correctly?
|
[
"from pycurl.c: \nelse if (PyInt_Check(result)) {\n long obj_size = PyInt_AsLong(result);\n if (obj_size < 0 || obj_size > total_size) {\n PyErr_Format(ErrorObject, \"invalid return value for write callback %ld %ld\", (long)obj_size, (long)total_size);\n goto verbose_error;\n }\n\nthis would mean 17 is the total_size - is this possible ? and -1 (result) is what your callback is returning.\n",
"import pycurl\nimport StringIO\n\nc = pycurl.Curl()\ns = StringIO.StringIO()\nc.setopt(pycurl.URL, url)\nc.setopt(pycurl.HEADER, True)\nc.setopt(pycurl.NOBODY, True)\nc.setopt(pycurl.WRITEFUNCTION, s.write)\nc.perform()\n\nprint(s.getvalue())\n\n"
] |
[
3,
1
] |
[] |
[] |
[
"libcurl",
"pycurl",
"python"
] |
stackoverflow_0000525405_libcurl_pycurl_python.txt
|
Q:
TinyMCE popup windows not working in Django development server
TinyMCE is working just fine, all except for the popup windows. They come up blank, and after a little bit of Google searching, apparently it has something to do with cross domain errors with Firefox and Django. I tried using document.domain, but I have a feeling that it doesn't work when you're using the Django development server (http://127.0.0.1:8000).
A:
There's nothing wrong with 127.0.0.1 as a domain. The problem is that it's different to your media domain localhost, although they both point to the same thing.
TinyMCE doesn't like different domains for the media, which is why having a relative MEDIA_URL would work. Using the URL http://localhost:8000/ to access your server would also work, because the domain would be the same as the MEDIA_URL, so too would setting your MEDIA_URL to 127.0.0.1:8000/m/ and accessing it with http://127.0.0.1:8000/.
A:
Instead of using 127.0.0.1:8000, if I use localhost:8000, everything seems to work perfectly. I'm not sure why. Maybe it's because localhost:8000 is a domain and 127.0.0.1:800 is not.
|
TinyMCE popup windows not working in Django development server
|
TinyMCE is working just fine, all except for the popup windows. They come up blank, and after a little bit of Google searching, apparently it has something to do with cross domain errors with Firefox and Django. I tried using document.domain, but I have a feeling that it doesn't work when you're using the Django development server (http://127.0.0.1:8000).
|
[
"There's nothing wrong with 127.0.0.1 as a domain. The problem is that it's different to your media domain localhost, although they both point to the same thing.\nTinyMCE doesn't like different domains for the media, which is why having a relative MEDIA_URL would work. Using the URL http://localhost:8000/ to access your server would also work, because the domain would be the same as the MEDIA_URL, so too would setting your MEDIA_URL to 127.0.0.1:8000/m/ and accessing it with http://127.0.0.1:8000/.\n",
"Instead of using 127.0.0.1:8000, if I use localhost:8000, everything seems to work perfectly. I'm not sure why. Maybe it's because localhost:8000 is a domain and 127.0.0.1:800 is not.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_tinymce",
"python",
"tinymce"
] |
stackoverflow_0002260061_django_django_tinymce_python_tinymce.txt
|
Q:
app-engine-patch is dead. Now what is the best way to use Django on Google App Engine?
The app-engine-patch authors have officially marked this wonderful project as dead on their website. Over the last year a lot of people have asked what the best way to run Django on Google App Engine was, and time after time people have pointed to app-engine-patch being the way to go. Now that this project is dead, I would love to revisit this discussion and see what you all would recommend.
The old app-engine-patch website refers to a different project called djangoappengine that they are working on. It focuses on using Native Django on App Engine but by doing so appears to limit your ability to use all of App Engine's features (such as its built in User model). What do you all think about this as a replacement solution?
Does the Google App Engine Helper For Django project now look more inviting now that app-engine-patch has died?
Or is app-engine-patch still so great that you would recommend still using it despite it being dead?
I currently have a project in its middle stages relying on app-engine-patch and have loved using it so far, but am scared to continue using a project that is dead. I would really appreciate any comments you have about what you think the best long term solution is now. Thanks!
A:
App engine patch is probably a safer bet for a given moment. Though not actively supported at the moment, it's still great, as it's been tested more thoroughly. If you're ready to take some risks - go and give the new djangoappengine+django-nonrel (native django support for non relational databases, primarily google datastore yest) option a try. That is the option we'll all use in a little while, so probably it's worth to try it out and not to look back. For instance, app engine patch only supports ~300 entities in the admin (i.e. doesn't take advantage of the 1.3.1 functionality), while with the djangoappengine+django-nonrel that is not an issues anymore. www.allbuttonspressed.com, a site of the guys behind app-engine-patch, is all built this new way, you can grab the source code of the site's skeleton @ http://bitbucket.org/wkornewald/allbuttonspressed/.
good luck!
A:
It looks like you can just import it using use_library...
http://code.google.com/appengine/docs/python/tools/libraries.html
|
app-engine-patch is dead. Now what is the best way to use Django on Google App Engine?
|
The app-engine-patch authors have officially marked this wonderful project as dead on their website. Over the last year a lot of people have asked what the best way to run Django on Google App Engine was, and time after time people have pointed to app-engine-patch being the way to go. Now that this project is dead, I would love to revisit this discussion and see what you all would recommend.
The old app-engine-patch website refers to a different project called djangoappengine that they are working on. It focuses on using Native Django on App Engine but by doing so appears to limit your ability to use all of App Engine's features (such as its built in User model). What do you all think about this as a replacement solution?
Does the Google App Engine Helper For Django project now look more inviting now that app-engine-patch has died?
Or is app-engine-patch still so great that you would recommend still using it despite it being dead?
I currently have a project in its middle stages relying on app-engine-patch and have loved using it so far, but am scared to continue using a project that is dead. I would really appreciate any comments you have about what you think the best long term solution is now. Thanks!
|
[
"App engine patch is probably a safer bet for a given moment. Though not actively supported at the moment, it's still great, as it's been tested more thoroughly. If you're ready to take some risks - go and give the new djangoappengine+django-nonrel (native django support for non relational databases, primarily google datastore yest) option a try. That is the option we'll all use in a little while, so probably it's worth to try it out and not to look back. For instance, app engine patch only supports ~300 entities in the admin (i.e. doesn't take advantage of the 1.3.1 functionality), while with the djangoappengine+django-nonrel that is not an issues anymore. www.allbuttonspressed.com, a site of the guys behind app-engine-patch, is all built this new way, you can grab the source code of the site's skeleton @ http://bitbucket.org/wkornewald/allbuttonspressed/. \ngood luck!\n",
"It looks like you can just import it using use_library...\nhttp://code.google.com/appengine/docs/python/tools/libraries.html\n"
] |
[
4,
0
] |
[] |
[] |
[
"app_engine_patch",
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002283414_app_engine_patch_django_google_app_engine_python.txt
|
Q:
How to use Twitter API to check if a user/password is valid?
I have a user and a password and I'd like to use Twitter API (I'm using python-twitter) to check if those are valid data.
A:
urllib2 will raise HTTPError if the credentials are wrong, and the message will be 'HTTP Error 401: Unauthorized'. You could use a temporary instance of the API to make an authorized request (GetFriends(), for example) in a try/except block to determine if the credentials are valid.
import twitter, urllib2
checkCreds = twitter.Api(username, pass)
try:
checkCreds.GetFriends()
except urllib2.HTTPError, status:
if status.find('401') != -1:
print 'Invalid username/password'
Twitter will intentionally allow requests with missing or incorrect credentials for publicly-accessible areas such as GetPublicTimeline() or GetUserTimeline().
A:
If you grab the 0.7 version of python-twitter, a VerifyCredentials method has been added. If the returned value is None then the username/password combo was incorrect.
I liked using api.GetUser(username) first to check if they provided a valid username and then using api.VerifyCredentials() to check the password -- this way I could informed the user which part of their login was incorrect.
As others have mentioned, Twitter is pushing for OAuth logins only and are expected to deprecate the existing username/passwd login method.
|
How to use Twitter API to check if a user/password is valid?
|
I have a user and a password and I'd like to use Twitter API (I'm using python-twitter) to check if those are valid data.
|
[
"urllib2 will raise HTTPError if the credentials are wrong, and the message will be 'HTTP Error 401: Unauthorized'. You could use a temporary instance of the API to make an authorized request (GetFriends(), for example) in a try/except block to determine if the credentials are valid.\nimport twitter, urllib2\ncheckCreds = twitter.Api(username, pass)\ntry:\n checkCreds.GetFriends()\nexcept urllib2.HTTPError, status:\n if status.find('401') != -1:\n print 'Invalid username/password'\n\nTwitter will intentionally allow requests with missing or incorrect credentials for publicly-accessible areas such as GetPublicTimeline() or GetUserTimeline().\n",
"If you grab the 0.7 version of python-twitter, a VerifyCredentials method has been added. If the returned value is None then the username/password combo was incorrect.\nI liked using api.GetUser(username) first to check if they provided a valid username and then using api.VerifyCredentials() to check the password -- this way I could informed the user which part of their login was incorrect.\nAs others have mentioned, Twitter is pushing for OAuth logins only and are expected to deprecate the existing username/passwd login method.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"twitter"
] |
stackoverflow_0002304712_python_twitter.txt
|
Q:
Is there a way of checking for membership from the values of a dictionary? Once confirmed, can we do other things?
I understand that it's quite easy to check if a key is available in a dictionary, but what about certain values?
So, what I have here is a dictionary of lists where the key references a set of, for consistency's sake, strings. It would look a bit like this:
menu = {'breakfast':['soft-boiled eggs', 'hash brown', 'Earl Grey'],
'lunch':['pasta', 'soup'],
'dinner':['chips', 'beef stew', 'veggies']}
Now what I'd like to do is check if, say, 'chips' is in my menu and if so, I'd like to replace it with 'crusty bread'. I know I can try using 'chips' in menu['lunch'] or the same for breakfast, but what if I don't know when it's being served?
Extension
While this is harder to explain let's say we've a class called Food defined such:
class Food(object):
def __init__(self, meal):
self.meal = meal
self.ingredients = collections.defaultdict(set)
def __str__(self):
return "%s" %(self.meal)
Here, meal will refer to either breakfast, lunch or dinner. And we have ingredients which is a dictionary of sets. 'potatoes' is an ingredient and when keyed we'll have the relevant dishes show up: hash browns, chips. As such, when I call print meal, menu[meal].ingredients for my function, I get the following result (this is only for breakfast since that's all I've put in):
breakfast defaultdict(<type 'set'>, {'potatoes': set(['chips', 'hash brown']), 'eggs': set(['omelette', 'hard-boiled', 'soft-boiled']), 'tea': set(['Assam', 'Earl Grey', 'English'])})
So this is basically what's available for breakfast for specific 'ingredients'.
Now, let's assume the worst has happened and I've run out of potatoes! What I'd like to do now is replace 'potatoes' with 'bread' under which I'll have the values/types 'roll', 'crusty', 'brown'. How would one go about doing that?
And to top things off, towards lunch-time, we run out of 'Assam' tea. Similar to the question before the Extension, how would I remove that (after checking to see if it existed in the first place)?
A:
Membership in menu is easy:
[k for k, v in menu.iteritems() if 'chips' in v]
Membership with defaultdict works exactly the same way since containment checking doesn't mutate it.
A:
One obvious way is to just go thru whole dict and replace the values but IMO it is better to design it so that it is easy to replace ingredients e.g. have a single object(may be singleton class) for each type of ingredient, so you can just replace the types on the fly e.g.
tea.remove('assam')
and it will affect all the places where tea was being referred. similarly you can keep track of the meals where tea was being used, in some kind of registry and update registry if you want to remove tea from all the meals or may be flag tea as deleted, or want to replace potato with bread, do that in registry, which in turn can ask each meal to do that
registry.replace(potato, bread)
A:
It looks like the basic thing you're asking for is how to iterate through a dictionary -- once you have that, it's all basic stuff.
for key,value in mydict.iteritems():
print "%s = %s" %(key, value)
now, to apply it directly to your situation:
for meal, food in menu.iteritems():
if 'potatoes' in food.ingredients:
del food.ingredients['potatoes']
food.ingredients['bread'] = set(['roll', 'crusty', 'brown'])
'del' can be used to remove a key/value pair from a dictionary
|
Is there a way of checking for membership from the values of a dictionary? Once confirmed, can we do other things?
|
I understand that it's quite easy to check if a key is available in a dictionary, but what about certain values?
So, what I have here is a dictionary of lists where the key references a set of, for consistency's sake, strings. It would look a bit like this:
menu = {'breakfast':['soft-boiled eggs', 'hash brown', 'Earl Grey'],
'lunch':['pasta', 'soup'],
'dinner':['chips', 'beef stew', 'veggies']}
Now what I'd like to do is check if, say, 'chips' is in my menu and if so, I'd like to replace it with 'crusty bread'. I know I can try using 'chips' in menu['lunch'] or the same for breakfast, but what if I don't know when it's being served?
Extension
While this is harder to explain let's say we've a class called Food defined such:
class Food(object):
def __init__(self, meal):
self.meal = meal
self.ingredients = collections.defaultdict(set)
def __str__(self):
return "%s" %(self.meal)
Here, meal will refer to either breakfast, lunch or dinner. And we have ingredients which is a dictionary of sets. 'potatoes' is an ingredient and when keyed we'll have the relevant dishes show up: hash browns, chips. As such, when I call print meal, menu[meal].ingredients for my function, I get the following result (this is only for breakfast since that's all I've put in):
breakfast defaultdict(<type 'set'>, {'potatoes': set(['chips', 'hash brown']), 'eggs': set(['omelette', 'hard-boiled', 'soft-boiled']), 'tea': set(['Assam', 'Earl Grey', 'English'])})
So this is basically what's available for breakfast for specific 'ingredients'.
Now, let's assume the worst has happened and I've run out of potatoes! What I'd like to do now is replace 'potatoes' with 'bread' under which I'll have the values/types 'roll', 'crusty', 'brown'. How would one go about doing that?
And to top things off, towards lunch-time, we run out of 'Assam' tea. Similar to the question before the Extension, how would I remove that (after checking to see if it existed in the first place)?
|
[
"Membership in menu is easy:\n[k for k, v in menu.iteritems() if 'chips' in v]\n\nMembership with defaultdict works exactly the same way since containment checking doesn't mutate it.\n",
"One obvious way is to just go thru whole dict and replace the values but IMO it is better to design it so that it is easy to replace ingredients e.g. have a single object(may be singleton class) for each type of ingredient, so you can just replace the types on the fly e.g.\ntea.remove('assam')\n\nand it will affect all the places where tea was being referred. similarly you can keep track of the meals where tea was being used, in some kind of registry and update registry if you want to remove tea from all the meals or may be flag tea as deleted, or want to replace potato with bread, do that in registry, which in turn can ask each meal to do that\nregistry.replace(potato, bread)\n\n",
"It looks like the basic thing you're asking for is how to iterate through a dictionary -- once you have that, it's all basic stuff.\nfor key,value in mydict.iteritems():\n print \"%s = %s\" %(key, value)\n\nnow, to apply it directly to your situation:\nfor meal, food in menu.iteritems():\n if 'potatoes' in food.ingredients:\n del food.ingredients['potatoes']\n food.ingredients['bread'] = set(['roll', 'crusty', 'brown'])\n\n'del' can be used to remove a key/value pair from a dictionary\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0002304749_dictionary_python.txt
|
Q:
Remove and insert lines in a text file
I have a text file looks like:
first line
second line
third line
forth line
fifth line
sixth line
I want to replace the third and forth lines with three new lines. The above contents would become:
first line
second line
new line1
new line2
new line3
fifth line
sixth line
How can I do this using Python?
A:
For python2.6
with open("file1") as infile:
with open("file2","w") as outfile:
for i,line in enumerate(infile):
if i==2:
# 3rd line
outfile.write("new line1\n")
outfile.write("new line2\n")
outfile.write("new line3\n")
elif i==3:
# 4th line
pass
else:
outfile.write(line)
For python3.1
with open("file1") as infile, open("file2","w") as outfile:
for i,line in enumerate(infile):
if i==2:
# 3rd line
outfile.write("new line1\n")
outfile.write("new line2\n")
outfile.write("new line3\n")
elif i==3:
# 4th line
pass
else:
outfile.write(line)
A:
import fileinput
myinsert="""new line1\nnew line2\nnew line3"""
for line in fileinput.input("file",inplace=1):
linenum=fileinput.lineno()
if linenum==1 or linenum>4 :
line=line.rstrip()
if linenum==2:
line=line+myinsert
print line
Or if you file is not too big,
import os
myinsert=["new line3\n","new line2\n","new line1\n"]
data=open("file").readlines()
data[2:4]=""
for i in myinsert:data.insert(2,i)
open("outfile","w").write(''.join(data))
os.rename("outfile","file)
A:
Read the whole file as a list of lines, then replace the lines you want to delete with a new list of lines:
f = open('file.txt')
data = f.readlines()
f.close()
data[2:4] = [
'new line1\n',
'new line2\n',
'new line3\n']
f = open('processed.txt','w')
f.writelines(data)
f.close()
Note that list slicing is zero-based, and [2:4] means "element 2 up to but not including element 4".
A:
Open a second file to write to, read and then write the lines you want to copy over, write the new lines, read the lines you want to skip, then copy the rest.
A:
import os
i = open(inputFilePath, 'r')
o = open(inputFilePath+"New", 'w')
lineNo = 0
for line in input:
lineNo += 1
if lineNo != 3:
o.write(line)
else:
o.write(myNewLines)
i.close()
o.close()
os.remove(inputFilePath)
os.rename(inputFilePath+"New", inputFilePath)
Hope this helps
A:
There are be several ways to achieve that
if you file is small and your lines unique, you can just read whole file and replace the line e.g.
f.read().replace("third line", "new line1\nnew line2\nnew line3")
But if the file is big or lines not unqiue, just read thru file line by line, and output each line but at third line output three different lines
e.g
for i, line in enumerate(f):
if i == 2:
o.write(myThreelines)
else:
o.write(line)
|
Remove and insert lines in a text file
|
I have a text file looks like:
first line
second line
third line
forth line
fifth line
sixth line
I want to replace the third and forth lines with three new lines. The above contents would become:
first line
second line
new line1
new line2
new line3
fifth line
sixth line
How can I do this using Python?
|
[
"For python2.6\nwith open(\"file1\") as infile:\n with open(\"file2\",\"w\") as outfile:\n for i,line in enumerate(infile):\n if i==2:\n # 3rd line\n outfile.write(\"new line1\\n\")\n outfile.write(\"new line2\\n\")\n outfile.write(\"new line3\\n\")\n elif i==3:\n # 4th line\n pass\n else:\n outfile.write(line)\n\nFor python3.1\nwith open(\"file1\") as infile, open(\"file2\",\"w\") as outfile:\n for i,line in enumerate(infile):\n if i==2:\n # 3rd line\n outfile.write(\"new line1\\n\")\n outfile.write(\"new line2\\n\")\n outfile.write(\"new line3\\n\")\n elif i==3:\n # 4th line\n pass\n else:\n outfile.write(line)\n\n",
"import fileinput\nmyinsert=\"\"\"new line1\\nnew line2\\nnew line3\"\"\"\nfor line in fileinput.input(\"file\",inplace=1):\n linenum=fileinput.lineno()\n if linenum==1 or linenum>4 : \n line=line.rstrip()\n if linenum==2:\n line=line+myinsert\n print line\n\nOr if you file is not too big, \nimport os\nmyinsert=[\"new line3\\n\",\"new line2\\n\",\"new line1\\n\"]\ndata=open(\"file\").readlines()\ndata[2:4]=\"\"\nfor i in myinsert:data.insert(2,i)\nopen(\"outfile\",\"w\").write(''.join(data))\nos.rename(\"outfile\",\"file)\n\n",
"Read the whole file as a list of lines, then replace the lines you want to delete with a new list of lines:\nf = open('file.txt')\ndata = f.readlines()\nf.close()\ndata[2:4] = [\n 'new line1\\n',\n 'new line2\\n',\n 'new line3\\n']\nf = open('processed.txt','w')\nf.writelines(data)\nf.close()\n\nNote that list slicing is zero-based, and [2:4] means \"element 2 up to but not including element 4\".\n",
"Open a second file to write to, read and then write the lines you want to copy over, write the new lines, read the lines you want to skip, then copy the rest.\n",
"import os\ni = open(inputFilePath, 'r')\no = open(inputFilePath+\"New\", 'w')\n\nlineNo = 0\nfor line in input:\n lineNo += 1\n if lineNo != 3:\n o.write(line)\n else:\n o.write(myNewLines)\n\ni.close()\no.close()\nos.remove(inputFilePath)\nos.rename(inputFilePath+\"New\", inputFilePath)\n\nHope this helps\n",
"There are be several ways to achieve that\n\nif you file is small and your lines unique, you can just read whole file and replace the line e.g.\nf.read().replace(\"third line\", \"new line1\\nnew line2\\nnew line3\")\nBut if the file is big or lines not unqiue, just read thru file line by line, and output each line but at third line output three different lines\n\ne.g\nfor i, line in enumerate(f):\n if i == 2:\n o.write(myThreelines)\n else:\n o.write(line)\n\n"
] |
[
7,
4,
3,
2,
1,
0
] |
[] |
[] |
[
"file_io",
"python"
] |
stackoverflow_0002305115_file_io_python.txt
|
Q:
python 2.6.4 doesn't support mod_python?
am looking for a way to run django by just using my xampp, and i bumped into this tutorial online
http://jyotirmaya.blogspot.com/2008/11/xampp-python-django.html
according to the author, mod_python 3.3.1 is not supported by python 2.6, but the blog post was created more then a year ago i think. is this thing still true until now? or its ok if I will use 2.6 and combine it with mod python 3.3.1 ?
A:
mod_python must be compiled against the specific version of Python that the handler will be run in. At the time there was probably no Windows installer for mod_python built against 2.6.4, hence the hysteria.
In all fairness, you should probably be using mod_wsgi to run Django apps instead.
|
python 2.6.4 doesn't support mod_python?
|
am looking for a way to run django by just using my xampp, and i bumped into this tutorial online
http://jyotirmaya.blogspot.com/2008/11/xampp-python-django.html
according to the author, mod_python 3.3.1 is not supported by python 2.6, but the blog post was created more then a year ago i think. is this thing still true until now? or its ok if I will use 2.6 and combine it with mod python 3.3.1 ?
|
[
"mod_python must be compiled against the specific version of Python that the handler will be run in. At the time there was probably no Windows installer for mod_python built against 2.6.4, hence the hysteria.\nIn all fairness, you should probably be using mod_wsgi to run Django apps instead.\n"
] |
[
6
] |
[] |
[] |
[
"django",
"mod_python",
"python"
] |
stackoverflow_0002305210_django_mod_python_python.txt
|
Q:
How can I limit an SQL query to be nondestructive?
I'm planning on building a Django log-viewing app with powerful filters. I'd like to enable the user to finely filter the results with some custom (possibly DB-specific) SELECT queries.
However, I dislike giving the user write access to the database. Is there a way to make sure a query doesn't change anything in the database? Like a 'dry run' flag? Or is there a way to filter SELECT queries so that they can't be harmful in any way?
I thought about running the queries as a separate MySQL user but I'd rather avoid the hassle. I also thought about using Google App Engine's GQL 'language', but if there is a cleaner solution, I'd certainly like to hear it :)
Thanks.
A:
Connect with a user that has only been granted SELECT permissions. Situations like this is why permissions exist in the first place.
A:
Create and use non-modifiable views.
|
How can I limit an SQL query to be nondestructive?
|
I'm planning on building a Django log-viewing app with powerful filters. I'd like to enable the user to finely filter the results with some custom (possibly DB-specific) SELECT queries.
However, I dislike giving the user write access to the database. Is there a way to make sure a query doesn't change anything in the database? Like a 'dry run' flag? Or is there a way to filter SELECT queries so that they can't be harmful in any way?
I thought about running the queries as a separate MySQL user but I'd rather avoid the hassle. I also thought about using Google App Engine's GQL 'language', but if there is a cleaner solution, I'd certainly like to hear it :)
Thanks.
|
[
"Connect with a user that has only been granted SELECT permissions. Situations like this is why permissions exist in the first place.\n",
"Create and use non-modifiable views.\n"
] |
[
14,
1
] |
[] |
[] |
[
"django",
"python",
"security",
"sql",
"sql_injection"
] |
stackoverflow_0002305353_django_python_security_sql_sql_injection.txt
|
Q:
Installing bitarray in Python 2.6 on Windows
I would like to install bitarray in Windows running python 2.6.
I have mingw32 installed, and I have C:\Python26\Lib\distutils\distutils.cfg set to:
[build]
compiler = mingw32
If I type, in a cmd.exe window:
C:\Documents and Settings\john\My Documents\bitarray-0.3.5>python setup.py install
I get:
[normal python messages skipped]
C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c bitarray/_bitarray.c -o build\temp.win32-2.6\Release\bitarray\_bitarray.o
bitarray/_bitarray.c:2197: error: initializer element is not constant
bitarray/_bitarray.c:2197: error: (near initialization for `BitarrayIter_Type.tp_getattro')
bitarray/_bitarray.c:2206: error: initializer element is not constant
bitarray/_bitarray.c:2206: error: (near initialization for `BitarrayIter_Type.tp_iter')
bitarray/_bitarray.c:2232: error: initializer element is not constant
bitarray/_bitarray.c:2232: error: (near initialization for `Bitarraytype.tp_getattro')
bitarray/_bitarray.c:2253: error: initializer element is not constant
bitarray/_bitarray.c:2253: error: (near initialization for `Bitarraytype.tp_alloc')
bitarray/_bitarray.c:2255: error: initializer element is not constant
bitarray/_bitarray.c:2255: error: (near initialization for `Bitarraytype.tp_free')
error: command 'gcc' failed with exit status 1
Can anyone help?
A:
MingW cannot compile the bitarray sources, I tried with version 3.4.5 and get the same errors.
However, it compiles fine with the Microsoft compiler.
For your convenience I've build msi and exe installers for Python 2.6:
http://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.msi
http://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.exe
Please point the bitarray author to them so that he can upload them to pypi.
A:
I needed to build bitarray for myself (I needed bit shift), so I couldn't use your pre-built binaries. The problem lies in mingw not working properly with __declspec(dllimport). Python already solves this problem for cygwin builds by using auto-import instead of declspec. However, this is not enabled for mingw builds. So you either need to modify the PyAPI_FUNC macro in pyport.h or add
#define __CYGWIN__
to the bitarray sources.
|
Installing bitarray in Python 2.6 on Windows
|
I would like to install bitarray in Windows running python 2.6.
I have mingw32 installed, and I have C:\Python26\Lib\distutils\distutils.cfg set to:
[build]
compiler = mingw32
If I type, in a cmd.exe window:
C:\Documents and Settings\john\My Documents\bitarray-0.3.5>python setup.py install
I get:
[normal python messages skipped]
C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python26\include -IC:\Python26\PC -c bitarray/_bitarray.c -o build\temp.win32-2.6\Release\bitarray\_bitarray.o
bitarray/_bitarray.c:2197: error: initializer element is not constant
bitarray/_bitarray.c:2197: error: (near initialization for `BitarrayIter_Type.tp_getattro')
bitarray/_bitarray.c:2206: error: initializer element is not constant
bitarray/_bitarray.c:2206: error: (near initialization for `BitarrayIter_Type.tp_iter')
bitarray/_bitarray.c:2232: error: initializer element is not constant
bitarray/_bitarray.c:2232: error: (near initialization for `Bitarraytype.tp_getattro')
bitarray/_bitarray.c:2253: error: initializer element is not constant
bitarray/_bitarray.c:2253: error: (near initialization for `Bitarraytype.tp_alloc')
bitarray/_bitarray.c:2255: error: initializer element is not constant
bitarray/_bitarray.c:2255: error: (near initialization for `Bitarraytype.tp_free')
error: command 'gcc' failed with exit status 1
Can anyone help?
|
[
"MingW cannot compile the bitarray sources, I tried with version 3.4.5 and get the same errors.\nHowever, it compiles fine with the Microsoft compiler.\nFor your convenience I've build msi and exe installers for Python 2.6:\nhttp://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.msi\nhttp://starship.python.net/crew/theller/bitarray-0.3.5.win32-py2.6.exe\nPlease point the bitarray author to them so that he can upload them to pypi.\n",
"I needed to build bitarray for myself (I needed bit shift), so I couldn't use your pre-built binaries. The problem lies in mingw not working properly with __declspec(dllimport). Python already solves this problem for cygwin builds by using auto-import instead of declspec. However, this is not enabled for mingw builds. So you either need to modify the PyAPI_FUNC macro in pyport.h or add\n#define __CYGWIN__\n\nto the bitarray sources.\n"
] |
[
3,
0
] |
[] |
[] |
[
"bitarray",
"c",
"mingw",
"python"
] |
stackoverflow_0000780127_bitarray_c_mingw_python.txt
|
Q:
Sampling keys due to their values
I have a dictionary in python with key->value as str->int. If I have to chose a key based on it's own value, then as the value gets larger the key has a lower possibility of being chosen.
For example, if key1=2 and key2->1, then the attitude of key1 should be 2:1.
How can I do this?
A:
If the values are too large for gnibler's approach:
Build a list of tuples (key, index), where index is the sum of all values that come before key in the list (this would be the index of the first occurrence of key gnibler's list c. Also calculate the sum of all values (n).
Now, generate a random number xbetween 0 and n - 1. Find the last entry in the list with index < x. Since the list is sorted by index, you can use binary search to do that efficiently.
Update: KennyTM's code is an implementation of this, except that he uses a brute-force linear search instead of binary search; this will be inefficient if the number of keys are large.
A:
It the values are not too large, you can do it this way
>>> from random import choice
>>> d={"key1":2,"key2":1}
>>> c=[]
>>> for k,v in d.items():
... c+=[k]*v
...
>>> choice(c)
'key1'
>>> sum(1 for x in range(100) if choice(c)=="key1")
63
>>> sum(1 for x in range(100) if choice(c)=="key2")
36
A:
1. Construct a CDF-like list like this:
def build_cdf(distrib):
cdf = []
val = 0
for key, freq in distrib.items():
val += freq
cdf.append((val, key))
return (val, cdf)
This function returns a tuple, the 1st value is the sum of probabilities, and 2nd value is the CDF.
2. Construct the sampler like this:
import random
def sample_from_cdf(val_and_cdf):
(val, cdf) = val_and_cdf;
rand = random.uniform(0, val)
# use bisect.bisect_left to reduce search time from O(n) to O(log n).
return [key for index, key in cdf if index > rand][0]
Usage:
x = build_cdf({"a":0.2, "b":0.3, "c":0.5});
y = [sample_from_cdf(x) for i in range(0,100000)];
print (len([t for t in y if t == "a"])) # 19864
print (len([t for t in y if t == "b"])) # 29760
print (len([t for t in y if t == "c"])) # 50376
You may want to make this into a class.
A:
A quick and simple version of the algorithm from oefe's and KennyTM's answers:
def select_weighted(d):
offset = random.randint(0, sum(d.itervalues())-1)
for k, v in d.iteritems():
if offset < v:
return k
offset -= v
|
Sampling keys due to their values
|
I have a dictionary in python with key->value as str->int. If I have to chose a key based on it's own value, then as the value gets larger the key has a lower possibility of being chosen.
For example, if key1=2 and key2->1, then the attitude of key1 should be 2:1.
How can I do this?
|
[
"If the values are too large for gnibler's approach:\nBuild a list of tuples (key, index), where index is the sum of all values that come before key in the list (this would be the index of the first occurrence of key gnibler's list c. Also calculate the sum of all values (n).\nNow, generate a random number xbetween 0 and n - 1. Find the last entry in the list with index < x. Since the list is sorted by index, you can use binary search to do that efficiently.\nUpdate: KennyTM's code is an implementation of this, except that he uses a brute-force linear search instead of binary search; this will be inefficient if the number of keys are large.\n",
"It the values are not too large, you can do it this way\n>>> from random import choice\n>>> d={\"key1\":2,\"key2\":1}\n>>> c=[]\n>>> for k,v in d.items():\n... c+=[k]*v\n... \n>>> choice(c)\n'key1'\n>>> sum(1 for x in range(100) if choice(c)==\"key1\")\n63\n>>> sum(1 for x in range(100) if choice(c)==\"key2\")\n36\n\n",
"1. Construct a CDF-like list like this:\ndef build_cdf(distrib):\n cdf = []\n val = 0\n for key, freq in distrib.items():\n val += freq\n cdf.append((val, key))\n return (val, cdf)\n\nThis function returns a tuple, the 1st value is the sum of probabilities, and 2nd value is the CDF. \n2. Construct the sampler like this:\nimport random\ndef sample_from_cdf(val_and_cdf):\n (val, cdf) = val_and_cdf;\n rand = random.uniform(0, val)\n # use bisect.bisect_left to reduce search time from O(n) to O(log n).\n return [key for index, key in cdf if index > rand][0]\n\nUsage:\nx = build_cdf({\"a\":0.2, \"b\":0.3, \"c\":0.5});\ny = [sample_from_cdf(x) for i in range(0,100000)];\nprint (len([t for t in y if t == \"a\"])) # 19864\nprint (len([t for t in y if t == \"b\"])) # 29760\nprint (len([t for t in y if t == \"c\"])) # 50376\n\nYou may want to make this into a class.\n",
"A quick and simple version of the algorithm from oefe's and KennyTM's answers:\ndef select_weighted(d):\n offset = random.randint(0, sum(d.itervalues())-1)\n for k, v in d.iteritems():\n if offset < v:\n return k\n offset -= v\n\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"dictionary",
"python",
"sampling"
] |
stackoverflow_0002305501_dictionary_python_sampling.txt
|
Q:
How to output huge dependency relationships diagram of Plone with Graphviz?
I wrote a tool for find dependency relationships behind a Python project. It is Gluttony. I run it on Plone, the result is impressive. I output the diagram with Networkx, and it looks like this:
(source: googlecode.com)
(Gee! It looks like World of Goo!)
A mess! I didn't handle layout with Networkx. That's why it is a mess. The tool can output Graphviz format file. I tried to render the diagram with dot command. I use command like this:
dot -Kdot -Tpng -oplone plone.dot
I got a huge image after long running, but the result seems wrong. I can't see anything on the result image. It looks like a white paper, nothing on it. What's wrong? Is the diagram too big to render? What should I do for rendering such a huge complex diagram?
I can get correct result from other small diagram, like this one:
(source: googlecode.com)
Even a much bigger diagram can be rendered correctly, let's see the diagram of TurboGears2
I think it should be fun to see the dependency relationship of such monster project like Plone. Also it is useful for researching. Unfortunately, I can't output diagram correctly. Cold someone help me out? Thanks.
Here is the Graphviz format file of Plone:
plone.dot
A:
The command dot plone.dot -Tsvg > plone.svg renders this scalable vecor graphic:
alt text http://dl.dropbox.com/u/138632/plone.svg
I can open the .svg file fine in Inkscape and zoom in till 100%.
A:
If you can produce an image: Graphviz tends to create huge files. Zoom in.
For me graphviz regularly crashes on your file. It seems to max out on 32 kPixels per side and your file would be larger, resulting in an integer overflow.
Try splitting the file up into multiple sub-graphs (Additional points for using graph algorithms for finding good separation points).
Update:
I threw up a quick script to split dot files. It's not perfect, but it works reasonable.
|
How to output huge dependency relationships diagram of Plone with Graphviz?
|
I wrote a tool for find dependency relationships behind a Python project. It is Gluttony. I run it on Plone, the result is impressive. I output the diagram with Networkx, and it looks like this:
(source: googlecode.com)
(Gee! It looks like World of Goo!)
A mess! I didn't handle layout with Networkx. That's why it is a mess. The tool can output Graphviz format file. I tried to render the diagram with dot command. I use command like this:
dot -Kdot -Tpng -oplone plone.dot
I got a huge image after long running, but the result seems wrong. I can't see anything on the result image. It looks like a white paper, nothing on it. What's wrong? Is the diagram too big to render? What should I do for rendering such a huge complex diagram?
I can get correct result from other small diagram, like this one:
(source: googlecode.com)
Even a much bigger diagram can be rendered correctly, let's see the diagram of TurboGears2
I think it should be fun to see the dependency relationship of such monster project like Plone. Also it is useful for researching. Unfortunately, I can't output diagram correctly. Cold someone help me out? Thanks.
Here is the Graphviz format file of Plone:
plone.dot
|
[
"The command dot plone.dot -Tsvg > plone.svg renders this scalable vecor graphic:\nalt text http://dl.dropbox.com/u/138632/plone.svg \nI can open the .svg file fine in Inkscape and zoom in till 100%.\n",
"If you can produce an image: Graphviz tends to create huge files. Zoom in.\nFor me graphviz regularly crashes on your file. It seems to max out on 32 kPixels per side and your file would be larger, resulting in an integer overflow.\nTry splitting the file up into multiple sub-graphs (Additional points for using graph algorithms for finding good separation points).\nUpdate:\nI threw up a quick script to split dot files. It's not perfect, but it works reasonable.\n"
] |
[
2,
1
] |
[] |
[] |
[
"diagram",
"graphviz",
"plone",
"python"
] |
stackoverflow_0002303079_diagram_graphviz_plone_python.txt
|
Q:
UnicodeDecodeError problem with mechanize
I receive the following string from one website via mechanize:
'We\x92ve'
I know that \x92 stands for ’ character. I'm trying to convert that string to Unicode:
>> unicode('We\x92ve','utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 2: unexpected code byte
What am I doing wrong?
Edit: The reason I tried 'utf-8' was this:
>> response = browser.response()
>> response.info()['content-type']
'text/html; charset=utf-8'
Now I see I can't always trust content-type header.
A:
\x92 stands for ’ alright, but it does so in the Windows-1252 encoding, not in UTF-8:
>>> print unicode('We\x92ve','1252')
We’ve
If you don't know what encoding your source data is in, you can detect it using chardet (extremely easy to use).
|
UnicodeDecodeError problem with mechanize
|
I receive the following string from one website via mechanize:
'We\x92ve'
I know that \x92 stands for ’ character. I'm trying to convert that string to Unicode:
>> unicode('We\x92ve','utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 2: unexpected code byte
What am I doing wrong?
Edit: The reason I tried 'utf-8' was this:
>> response = browser.response()
>> response.info()['content-type']
'text/html; charset=utf-8'
Now I see I can't always trust content-type header.
|
[
"\\x92 stands for ’ alright, but it does so in the Windows-1252 encoding, not in UTF-8:\n>>> print unicode('We\\x92ve','1252')\nWe’ve\n\nIf you don't know what encoding your source data is in, you can detect it using chardet (extremely easy to use).\n"
] |
[
4
] |
[] |
[] |
[
"mechanize",
"python",
"unicode"
] |
stackoverflow_0002305997_mechanize_python_unicode.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.