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:
Python code simplification? One line, add all in list
I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion.
Question: What is the sum of the digits of the number 21000?
My answer:
>>> i=0
>>> for item in [int(n) for n in str(2**1000)];i+=item
A:
sum(int(n) for n in str(2**1000))
A:
Not a one-liner, but a cleaner-looking generator solution, also avoiding the int->string->int conversion:
def asDigits(n):
while n:
n,d = divmod(n,10)
yield d
print sum(asDigits(2**1000))
Gives 1366.
Interestingly, the sum of the digits in 2**10000 is 13561, whose digits add up to the same value as 1366.
Of course, if expressed in binary, the sum of the digits in 2**1000 is 1. (I even did it in my head!)
A:
Single int to str conversion to get length:
int(sum(map(lambda x:2**1000/x % 10, (10**x for x in xrange(len(str(2**1000)))))))
| Python code simplification? One line, add all in list | I'm making my way through project Euler and I'm trying to write the most concise code I can. I know it's possible, so how could I simplify the following code. Preferably, I would want it to be one line and not use the int->string->int conversion.
Question: What is the sum of the digits of the number 21000?
My answer:
>>> i=0
>>> for item in [int(n) for n in str(2**1000)];i+=item
| [
"sum(int(n) for n in str(2**1000))\n\n",
"Not a one-liner, but a cleaner-looking generator solution, also avoiding the int->string->int conversion:\ndef asDigits(n):\n while n:\n n,d = divmod(n,10)\n yield d\n\nprint sum(asDigits(2**1000))\n\nGives 1366.\nInterestingly, the sum of the digits in 2... | [
16,
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003145379_python.txt |
Q:
Which is faster to learn: Django (Python) or Ruby on Rails (Ruby)?
I have done the front-end of my design, but I have no experience in web programming. Would like to pick up a language asap so that I can deploy the product. Which is faster to pick up between the two? I know there is always debate in which is better. I think either one serves well for me, but I want to know which one is easier to learn, so that I can get my site up asap. Oh, I need Ajax too. Thanks.
Update: I am proficient in HTML, CSS, Joomla, Wordpress. Just no web programming experience whatsoever. I have setup several sites up.
A:
There is no good answer to this without more background on you, and even then it is going to be nothing more than a guess.
Either language can be learned depending on your own experiences. Both have similar abilities with a natural language type syntax. The two frameworks you list are similar as well.
The real way to decide this is to read through the language tutorial of each one and see which feels better for yourself.
If you are looking to actually deploy a solid product however, it would be a far better option to find yourself a good programmer or company to build it for you. They will be more aware of the limitations, features and best practices of their own chosen framework and toolchain.
A:
I agree that there is no real good answer to this, however the philosophy of the frameworks is slightly different - which lines up with the philosophies of python and ruby.
In Ruby/Rails, convention is considered better than configuration.
Rails does a whole load of things for you without telling you what it's doing. Objects have a method called method_missing which will allow you to run methods that have no real "definition". For instance, when I use the new_user_path method in Rails, there's no actual method called new_user_path anywhere. It's being created based on a route to something else. If you ever need to find where something is happening in Rails, it can be a nightmare. That said, it doing a lot of things for you is extremely handy.
In Python/Django, quoting from the "The Zen of Python, by Tim Peters" (you can see it by typing import this into a python console)
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
It's namely the "explicit is always better than implicit" and the "flat is better than nested" items where python and ruby differ wildly. Ruby blocks are a fundamental structure in Rails that create extremely deeply nested constructs.
That said, I have not used the Django framework thoroughly, so it's possible it doesn't conform to the same conventions as python.
It comes down to a matter of preference, really, but understand what you're getting into is always good.
A:
I start playing with both and choose Python/Django as it was easier for me.
| Which is faster to learn: Django (Python) or Ruby on Rails (Ruby)? | I have done the front-end of my design, but I have no experience in web programming. Would like to pick up a language asap so that I can deploy the product. Which is faster to pick up between the two? I know there is always debate in which is better. I think either one serves well for me, but I want to know which one is easier to learn, so that I can get my site up asap. Oh, I need Ajax too. Thanks.
Update: I am proficient in HTML, CSS, Joomla, Wordpress. Just no web programming experience whatsoever. I have setup several sites up.
| [
"There is no good answer to this without more background on you, and even then it is going to be nothing more than a guess.\nEither language can be learned depending on your own experiences. Both have similar abilities with a natural language type syntax. The two frameworks you list are similar as well.\nThe real w... | [
7,
5,
2
] | [] | [] | [
"django",
"python",
"ruby",
"ruby_on_rails"
] | stackoverflow_0003145879_django_python_ruby_ruby_on_rails.txt |
Q:
Reisze wx.Dialog horizontally only
Is there a way to allow a custom wx.Dialog to be resized in the horizontal direction only? I've tried using GetSize() and then setting the min and max height of the window using SetSizeHints(), but for some reason it always allows the window to be resized just a little, and it looks rather tacky. The only other alternative I have come up with is to hard-code the min and max height, but I don't think that would be such a good idea...
Relevant code:
class SomeDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, title="blah blah",
style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
size = self.GetSize()
self.SetSizeHints(minW=size.GetWidth(), minH=size.GetHeight(),
maxH=size.GetHeight())
os: Windows 7
python version: 2.5.4
wxPython version: 2.8.10
A:
If you don't want the height to change, why would it be a bad idea to set min and max height to the same value (the one you want to force)? You can of course get the system estimate of the "best value" with GetBetSize or related methods. Though I find the fact that setting the size hints doesn't have the same effect (as I think it should) peculiar... what platform are you using wxpython on, and what version of Python, wxpython, and the platform/OS itself...?
| Reisze wx.Dialog horizontally only | Is there a way to allow a custom wx.Dialog to be resized in the horizontal direction only? I've tried using GetSize() and then setting the min and max height of the window using SetSizeHints(), but for some reason it always allows the window to be resized just a little, and it looks rather tacky. The only other alternative I have come up with is to hard-code the min and max height, but I don't think that would be such a good idea...
Relevant code:
class SomeDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, title="blah blah",
style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
size = self.GetSize()
self.SetSizeHints(minW=size.GetWidth(), minH=size.GetHeight(),
maxH=size.GetHeight())
os: Windows 7
python version: 2.5.4
wxPython version: 2.8.10
| [
"If you don't want the height to change, why would it be a bad idea to set min and max height to the same value (the one you want to force)? You can of course get the system estimate of the \"best value\" with GetBetSize or related methods. Though I find the fact that setting the size hints doesn't have the same ... | [
2
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0003145978_python_wxpython.txt |
Q:
IPython with own scope?
I encountered a problem with the scope variables have when IPython is invoked at the end of a python script.
All functions I call in the script itself can modify variables, which will subsequently be used by other functions.
If I call the same functions in ipython, the scripted ones can access the changed variables but variables which existed when ipython was called don't change.
Thus my question: How do I propagate the global variables into ipython?
(I could do something like A=globals()['A'] of course but thats ugly)
A:
You could create a class with a static method (decorator: @staticmethod) that returns a singleton instance of that class. That object can contain any number of members that function as globals.
class Globals:
__master = None
somevar = 1
othervar = 2
@staticmethod
def get_master():
if Globals.__master is None:
Globals.__master = Globals()
return Globals.__master
g1 = Globals.get_master()
g2 = Globals.get_master()
g1.somevar += 1
print g1.somevar
print g2.somevar
Prints:
2
2
| IPython with own scope? | I encountered a problem with the scope variables have when IPython is invoked at the end of a python script.
All functions I call in the script itself can modify variables, which will subsequently be used by other functions.
If I call the same functions in ipython, the scripted ones can access the changed variables but variables which existed when ipython was called don't change.
Thus my question: How do I propagate the global variables into ipython?
(I could do something like A=globals()['A'] of course but thats ugly)
| [
"You could create a class with a static method (decorator: @staticmethod) that returns a singleton instance of that class. That object can contain any number of members that function as globals.\nclass Globals:\n __master = None\n somevar = 1\n othervar = 2\n\n @staticmethod\n def get_master():\n ... | [
0
] | [] | [] | [
"ipython",
"namespaces",
"python",
"scope"
] | stackoverflow_0003142721_ipython_namespaces_python_scope.txt |
Q:
Possible to return instantiator in Python?
class Parent():
def __init__(self):
self.child = Child()
class Child():
def __init__(self):
# get Parent instance
self.parent = self.Instantiator()
I know this isn't proper encapsulation but for interest's sake...
Given a "Parent" class that instantiates a "Child" object, is it possible from within Child to return the Parent object that instantiated it? And if no, I'm curious, do any languages support this?
A:
To answer the question, no, there's no way1 the child instance knows about any classes which contain references to it. The common2 way to handle this is:
class Parent(object):
def __init__(self):
self.child = Child()
self.child._parent = self
1 Of course, this isn't strictly true. As another commentor noted, you can extract the stack frame from the executing code within the __init__ method, and examine the f_locals dictionary for the self variable for the frame before the currently executing one. But this is complicated, and prone to error. Highly unrecommended.
2 A slightly better way to handle this (depending on the specific needs of the program) might be to require the parent to pass itself to the child, like so:
class Parent(object):
def __init__(self):
self.child = Child(self)
class Child(object):
def __init__(self, parent):
self._parent = parent
A:
Here's a reasonably-simple metaclass solution to the problem:
import functools
class MetaTrackinits(type):
being_inited = []
def __new__(cls, n, b, d):
clob = type.__new__(cls, n, b, d)
theinit = getattr(clob, '__init__')
@functools.wraps(theinit)
def __init__(self, *a, **k):
MetaTrackinits.being_inited.append(self)
try: theinit(self, *a, **k)
finally: MetaTrackinits.being_inited.pop()
setattr(clob, '__init__', __init__)
def Instantiator(self, where=-2):
return MetaTrackinits.being_inited[where]
setattr(clob, 'Instantiator', Instantiator)
return clob
__metaclass__ = MetaTrackinits
class Parent():
def __init__(self):
self.child = Child()
class Child():
def __init__(self):
self.parent = self.Instantiator()
p = Parent()
print p
print p.child.parent
a typical output, depending on the platform, will be something like
<__main__.Parent object at 0xd0750>
<__main__.Parent object at 0xd0750>
You could obtain a similar effect (in 2.6 and later) with a class decorator, but then all classes needing the functionality (both parent and children ones) would have to be explicitly decorated -- here, they just need to have the same metaclass, which may be less intrusive thanks to the "module-global __metaclass__ setting" idiom (and the fact that metaclasses, differently from class-decorations, also get inherited).
In fact, this is simple enough that I would consider allowing it in production code, if the need for that magical "instantiator" method had a proven business basis (I would never allow, in production code, a hack based on walking the stack frames!-). (BTW, the "allowing" part comes from the best-practice of mandatory code reviews: code changes don't get into the trunk of the codebase without consensus from reviewers -- this how typical open source projects work, and also how we always operate at my employer).
A:
Here's an example based off of some of Chris B.'s suggestions to show how absolutely terrible it would be to inspect the stack:
import sys
class Child(object):
def __init__(self):
# To get the parent:
# 1. Get our current stack frame
# 2. Go back one level to our caller (the Parent() constructor).
# 3. Grab it's locals dictionary
# 4. Fetch the self instance.
# 5. Assign it to our parent property.
self.parent = sys._getframe().f_back.f_locals['self']
class Parent(object):
def __init__(self):
self.child = Child()
if __name__ == '__main__':
p = Parent()
assert(id(p) == id(p.child.parent))
Sure that'll work, but just never try to refactor it into a seperate method, or create a base class from it.
A:
you could* try to use the traceback module, just to prove a point.
**Don't try this at home, kids*
A:
This can be done in python with metaclasses.
| Possible to return instantiator in Python? | class Parent():
def __init__(self):
self.child = Child()
class Child():
def __init__(self):
# get Parent instance
self.parent = self.Instantiator()
I know this isn't proper encapsulation but for interest's sake...
Given a "Parent" class that instantiates a "Child" object, is it possible from within Child to return the Parent object that instantiated it? And if no, I'm curious, do any languages support this?
| [
"To answer the question, no, there's no way1 the child instance knows about any classes which contain references to it. The common2 way to handle this is:\nclass Parent(object):\n def __init__(self):\n self.child = Child()\n self.child._parent = self\n\n1 Of course, this isn't strictly true. As a... | [
7,
2,
1,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003145652_oop_python.txt |
Q:
How are closures implemented?
"Learning Python, 4th Ed." mentions that:
the enclosing scope variable is looked up when the nested functions
are later called..
However, I thought that when a function exits, all of its local references disappear.
def makeActions():
acts = []
for i in range(5): # Tries to remember each i
acts.append(lambda x: i ** x) # All remember same last i!
return acts
makeActions()[n] is the same for every n because the variable i is somehow looked up at call time. How does Python look up this variable? Shouldn't it not exist at all because makeActions has already exited? Why doesn't Python do what the code intuitively suggests, and define each function by replacing i with its current value within the for loop as the loop is running?
A:
I think it's pretty obvious what happens when you think of i as a name not some sort of value. Your lambda function does something like "take x: look up the value of i, calculate i**x" ... so when you actually run the function, it looks up i just then so i is 4.
You can also use the current number, but you have to make Python bind it to another name:
def makeActions():
def make_lambda( j ):
return lambda x: j * x # the j here is still a name, but now it wont change anymore
acts = []
for i in range(5):
# now you're pushing the current i as a value to another scope and
# bind it there, under a new name
acts.append(make_lambda(i))
return acts
It might seem confusing, because you often get taught that a variable and it's value are the same thing -- which is true, but only in languages that actually use variables. Python has no variables, but names instead.
About your comment, actually i can illustrate the point a bit better:
i = 5
myList = [i, i, i]
i = 6
print(myList) # myList is still [5, 5, 5].
You said you changed i to 6, that is not what actually happend: i=6 means "i have a value, 6 and i want to name it i". The fact that you already used i as a name matters nothing to Python, it will just reassign the name, not change it's value (that only works with variables).
You could say that in myList = [i, i, i], whatever value i currently points to (the number 5) gets three new names: mylist[0], mylist[1], mylist[2]. That's the same thing that happens when you call a function: The arguments are given new names. But that is probably going against any intuition about lists ...
This can explain the behavior in the example: You assign mylist[0]=5, mylist[1]=5, mylist[2]=5 - no wonder they don't change when you reassign the i. If i was something muteable, for example a list, then changing i would reflect on all entries in myList too, because you just have different names for the same value!
The simple fact that you can use mylist[0] on the left hand of a = proves that it is indeed a name. I like to call = the assign name operator: It takes a name on the left, and a expression on the right, then evaluates the expression (call function, look up the values behind names) until it has a value and finally gives the name to the value. It does not change anything.
For Marks comment about compiling functions:
Well, references (and pointers) only make sense when we have some sort of addressable memory. The values are stored somewhere in memory and references lead you that place. Using a reference means going to that place in memory and doing something with it. The problem is that none of these concepts are used by Python!
The Python VM has no concept of memory - values float somewhere in space and names are little tags connected to them (by a little red string). Names and values exist in separate worlds!
This makes a big difference when you compile a function. If you have references, you know the memory location of the object you refer to. Then you can simply replace then reference with this location.
Names on the other hand have no location, so what you have to do (during runtime) is follow that little red string and use whatever is on the other end. That is the way Python compiles functions: Where
ever there is a name in the code, it adds a instruction that will figure out what that name stands for.
So basically Python does fully compile functions, but names are compiled as lookups in the nesting namespaces, not as some sort of reference to memory.
When you use a name, the Python compiler will try to figure out where to which namespace it belongs to. This results in a instruction to load that name from the namespace it found.
Which brings you back to your original problem: In lambda x:x**i, the i is compiled as a lookup in the makeActions namespace (because i was used there). Python has no idea, nor does it care about the value behind it (it does not even have to be a valid name). One that code runs the i gets looked up in it's original namespace and gives the more or less expected value.
A:
What happens when you create a closure:
The closure is constructed with a pointer to the frame (or roughly, block) that it was created in: in this case, the for block.
The closure actually assumes shared ownership of that frame, by incrementing the frame's ref count and stashing the pointer to that frame in the closure. That frame, in turn, keeps around references to the frames it was enclosed in, for variables that were captured further up the stack.
The value of i in that frame keeps changing as long as the for loop is running – each assignment to i updates the binding of i in that frame.
Once the for loop exits, the frame is popped off the stack, but it isn't thrown away as it might usually be! Instead, it's kept around because the closure's reference to the frame is still active. At this point, though, the value of i is no longer updated.
When the closure is invoked, it picks up whatever value of i is in the parent frame at the time of invocation. Since in the for loop you create closures, but don't actually invoke them, the value of i upon invocation will be the last value it had after all the looping was done.
Future calls to makeActions will create different frames. You won't reuse the for loop's previous frame, or update that previous frame's i value, in that case.
In short: frames are garbage-collected just like other Python objects, and in this case, an extra reference is kept around to the frame corresponding to the for block so it doesn't get destroyed when the for loop goes out of scope.
To get the effect you want, you need to have a new frame created for each value of i you want to capture, and each lambda needs to be created with a reference to that new frame. You won't get that from the for block itself, but you could get that from a call to a helper function which will establish the new frame. See THC4k's answer for one possible solution along these lines.
A:
The local references persist because they're contained in the local scope, which the closure keeps a reference to.
A:
I thought that when a function exits, all of its local references disappear.
Except for those locals which are closed over in a closure. Those do not disappear, even when the function to which they are local has returned.
A:
Intuitively one might think i would be captured in its current state but that is not the case. Think of each layer as a dictionary of name value pairs.
Level 1:
acts
i
Level 2:
x
Every time you create a closure for the inner lambda you are capturing a reference to level one. I can only assume that the run-time will perform a look-up of the variable i, starting in level 2 and making its way to level 1. Since you are not executing these functions immediately they will all use the final value of i.
Experts?
| How are closures implemented? | "Learning Python, 4th Ed." mentions that:
the enclosing scope variable is looked up when the nested functions
are later called..
However, I thought that when a function exits, all of its local references disappear.
def makeActions():
acts = []
for i in range(5): # Tries to remember each i
acts.append(lambda x: i ** x) # All remember same last i!
return acts
makeActions()[n] is the same for every n because the variable i is somehow looked up at call time. How does Python look up this variable? Shouldn't it not exist at all because makeActions has already exited? Why doesn't Python do what the code intuitively suggests, and define each function by replacing i with its current value within the for loop as the loop is running?
| [
"I think it's pretty obvious what happens when you think of i as a name not some sort of value. Your lambda function does something like \"take x: look up the value of i, calculate i**x\" ... so when you actually run the function, it looks up i just then so i is 4.\nYou can also use the current number, but you have... | [
10,
8,
1,
1,
0
] | [] | [] | [
"closures",
"python"
] | stackoverflow_0003145893_closures_python.txt |
Q:
concat multiple block in jinja2?
I use jinja2 for my template engine in python.
i would like to join content of multiple block and would like to render it at the end of the template, just before tag. { they are various JavaScript snippets throughout the code in multiple template which i would like to move to the end of the file, how do i do it ? }
edit :
I would like to move all my inline javascript that are created in child jinja templates. I would like to move them to bottom of the page. so I have created a block in the parent template at the end of the page and using it in child template to write javascript. but , there may be multiple child, and so multiple javascript block, and as multiple block does not supported in jinja2 , what is the other solution do i have ? -------- one alternate i think is to create javascript itself in such a way that it does not need to be inline.
A:
I assume that by multiple children, you mean that there are templates inheriting from templates inheriting from templates ... inheriting from the base template. If that's the case, you need to define the same javascript block in each template and call super() in all of the children, in addition to adding more JavaScript. Calling super() prints the output of the parent's javascript block, and so on up the chain of inheritance. Along the way, each block may add code of its own.
So you could have something like this in each template:
{% block javascript %}
{{ super() }}
function foo(x, y) {
return x + y;
}
{% endblock %}
| concat multiple block in jinja2? | I use jinja2 for my template engine in python.
i would like to join content of multiple block and would like to render it at the end of the template, just before tag. { they are various JavaScript snippets throughout the code in multiple template which i would like to move to the end of the file, how do i do it ? }
edit :
I would like to move all my inline javascript that are created in child jinja templates. I would like to move them to bottom of the page. so I have created a block in the parent template at the end of the page and using it in child template to write javascript. but , there may be multiple child, and so multiple javascript block, and as multiple block does not supported in jinja2 , what is the other solution do i have ? -------- one alternate i think is to create javascript itself in such a way that it does not need to be inline.
| [
"I assume that by multiple children, you mean that there are templates inheriting from templates inheriting from templates ... inheriting from the base template. If that's the case, you need to define the same javascript block in each template and call super() in all of the children, in addition to adding more Jav... | [
22
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0003127502_jinja2_python_templates.txt |
Q:
Automagically expanding a Python list with formatted output
Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.
For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "IN" clause.
import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
Any help would be appreciated!
A:
try:
",".join( map(str, record_ids) )
",".join( list_of_strings ) joins a list of string by separating them with commas
if you have a list of numbers, map( str, list ) will convert it to a list of strings
A:
I do stuff like this (to ensure I'm using bindings):
sqlStmt=("UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)"
% ', '.join(['?' for n in record_ids]))
mysql_cursor.execute(sqlStmt, record_ids)
mysql.commit()
This works for all dynamic lists you want to bind without leaving you susceptible to SQL injection attacks.
A:
Further to the given answers, note that you may want to special case the empty list case as "where rec_id in ()" is not valid SQL, so you'll get an error.
Also be very careful of building SQL manually like this, rather than just using automatically escaped parameters. For a list of integers, it'll work, but if you're dealing with strings received from user input, you open up a huge SQL injection vulnerability by doing this.
A:
Slightly different alternative to Dustin's answer:
sqlStmt=("UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in (%s)"
% ', '.join(['?'] * len(record_ids)))
| Automagically expanding a Python list with formatted output | Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.
For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "IN" clause.
import MySQLdb
record_ids = [ 23, 43, 71, 102, 121, 241 ]
mysql = MySQLdb.connect(user="username", passwd="secret", db="apps")
mysql_cursor = mysql.cursor()
sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )"
mysql_cursor.execute( sqlStmt, record_ids )
mysql.commit()
Any help would be appreciated!
| [
"try:\n\",\".join( map(str, record_ids) )\n\n\",\".join( list_of_strings ) joins a list of string by separating them with commas\nif you have a list of numbers, map( str, list ) will convert it to a list of strings\n",
"I do stuff like this (to ensure I'm using bindings):\nsqlStmt=(\"UPDATE apps.sometable SET las... | [
17,
3,
2,
0
] | [
"Alternitavely, using replace:\nsqlStmt=\"UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in \" +\n record_ids.__str__().replace('[','(').replace(']',')')\n\n"
] | [
-1
] | [
"list",
"mysql",
"python"
] | stackoverflow_0000315672_list_mysql_python.txt |
Q:
How to sort a list of inter-linked tuples?
lst = [(u'course', u'session'), (u'instructor', u'session'), (u'session', u'trainee'), (u'person', u'trainee'), (u'person', u'instructor'), (u'course', u'instructor')]
I've above list of tuple, I need to sort it with following logic....
each tuple's 2nd element is dependent on 1st element, e.g. (course, session) -> session is dependent on course and so on..
I want a sorted list based on priority of their dependency, less or independent object will come first so output should be like below,
lst = [course, person, instructor, session, trainee]
A:
You're looking for what's called a topological sort. The wikipedia page shows the classic Kahn and depth-first-search algorithms for it; Python examples are here (a bit dated, but should still run fine), on pypi (stable and reusable -- you can also read the code online here) and here (Tarjan's algorithm, that kind-of also deals with cycles in the dependencies specified), just to name a few.
A:
Conceptually, what you need to do is create a directed acyclic graph with edges determined by the contents of your list, and then do a topological sort on the graph. The algorithm to do this doesn't exist in Python's standard library (at least, not that I can think of off the top of my head), but you can find plenty of third-party implementations online, such as http://www.bitformation.com/art/python_toposort.html
The function at that website takes a list of all the strings, items, and another list of the pairs between strings, partial_order. Your lst should be passed as the second argument. To generate the first argument, you can use itertools.chain.from_iterable(lst), so the overall function call would be
import itertools
lst = ...
ordering = topological_sort(itertools.chain.from_iterable(lst), lst)
Or you could modify the function from the website to only take one argument, and to create the nodes in the graph directly from the values in your lst.
EDIT: Using the topsort module Alex Martelli linked to, you could just pass lst directly.
| How to sort a list of inter-linked tuples? | lst = [(u'course', u'session'), (u'instructor', u'session'), (u'session', u'trainee'), (u'person', u'trainee'), (u'person', u'instructor'), (u'course', u'instructor')]
I've above list of tuple, I need to sort it with following logic....
each tuple's 2nd element is dependent on 1st element, e.g. (course, session) -> session is dependent on course and so on..
I want a sorted list based on priority of their dependency, less or independent object will come first so output should be like below,
lst = [course, person, instructor, session, trainee]
| [
"You're looking for what's called a topological sort. The wikipedia page shows the classic Kahn and depth-first-search algorithms for it; Python examples are here (a bit dated, but should still run fine), on pypi (stable and reusable -- you can also read the code online here) and here (Tarjan's algorithm, that kin... | [
5,
4
] | [] | [] | [
"list",
"python",
"sorting",
"topological_sort",
"tuples"
] | stackoverflow_0003146700_list_python_sorting_topological_sort_tuples.txt |
Q:
Django - managing multiple pages with multiple fields
I am using Django for developing a website and I want to allow my staff to be able to add/edit/delete pages with multiple text fields. I am planning to use Django's admin framework for this as the staff is a non-technical one.But I have no clue on how to go about doing this so that people can login and edit the contents on these pages whenever they want.
Also, my site will be receiving around 1500 hits per day. I don't want to embed these pages in static templates (so that I can allow my staff to edit it). Will loading this data at runtime slow down my site. I am using a Servint VPS server.
Thanks
niting
A:
Follow the Django tutorial, replacing the concept of Polls with Pages, and Choices with Content blocks and you'll be most of the way there (Django's built in Admin will allow you to edit these models).
For a more advanced CMS based on Django take a look at either Django CMS or FeinCMS.
| Django - managing multiple pages with multiple fields | I am using Django for developing a website and I want to allow my staff to be able to add/edit/delete pages with multiple text fields. I am planning to use Django's admin framework for this as the staff is a non-technical one.But I have no clue on how to go about doing this so that people can login and edit the contents on these pages whenever they want.
Also, my site will be receiving around 1500 hits per day. I don't want to embed these pages in static templates (so that I can allow my staff to edit it). Will loading this data at runtime slow down my site. I am using a Servint VPS server.
Thanks
niting
| [
"Follow the Django tutorial, replacing the concept of Polls with Pages, and Choices with Content blocks and you'll be most of the way there (Django's built in Admin will allow you to edit these models).\nFor a more advanced CMS based on Django take a look at either Django CMS or FeinCMS.\n"
] | [
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003146904_django_django_admin_python.txt |
Q:
Convert array to string
I have a reeeealy huge string, which looks like ['elem1','elem2',(...)] and contains about 100,000(!) elements.
What is the best method to change it back to a list?
A:
eval("['elem1','elem2']") gives you back list ['elem1','elem2']
If you had string looking like this ["elem1","elem2",(...)] you might use json.read() (in python 2.5 or earlier) or json.loads() (in python 2.6) from json module to load it safely.
A:
One possible solution is:
input = "['elem1', 'elem2' ] "
result_as_list = [ e.strip()[1:-1] for e in input.strip()[1:-1].split(",") ]
This builds the complete result list in memory. You may switch to generator expression
result_as_iterator = ( e.strip()[1:-1] for e in input.strip()[1:-1].split(",") )
if memory consumption is a concern.
A:
If you don't want to use eval, this may work:
big_string = """['oeu','oeu','nth','nthoueoeu']"""
print big_string[1:-2].split("'")[1::2]
| Convert array to string | I have a reeeealy huge string, which looks like ['elem1','elem2',(...)] and contains about 100,000(!) elements.
What is the best method to change it back to a list?
| [
"eval(\"['elem1','elem2']\") gives you back list ['elem1','elem2']\nIf you had string looking like this [\"elem1\",\"elem2\",(...)] you might use json.read() (in python 2.5 or earlier) or json.loads() (in python 2.6) from json module to load it safely.\n",
"One possible solution is:\ninput = \"['elem1', 'elem2' ]... | [
3,
1,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003147570_list_python.txt |
Q:
How do you set a background image in a frame with pygtk?
I mean like a frame with some widgets which overlap the background (the image), basically how do you partially overlap/clobber an Image?
Like a background in a Firefox theme, for instance.
A:
I think that this is a FAQ.
| How do you set a background image in a frame with pygtk? | I mean like a frame with some widgets which overlap the background (the image), basically how do you partially overlap/clobber an Image?
Like a background in a Firefox theme, for instance.
| [
"I think that this is a FAQ.\n"
] | [
2
] | [] | [] | [
"pygtk",
"python",
"user_interface"
] | stackoverflow_0003147020_pygtk_python_user_interface.txt |
Q:
Command not defined in Python - Real basics, but confused!
I have written this short script (which I've stripped away some minor detail for size) and I'm getting a very simple error, yet, I don't understand why! I'm very new to Python, so maybe someone can explain the issue and why it's not working?
The error seems to fall when I wish to print the full custom serial write string back to the console, it doesn't seem to recognise the Args I sent to the function.
Perhaps I have misunderstood something very simple. Should be simple for anyone even with the tiniest of Python understanding
Cheers
The Code:
#! /usr/bin/env python
# IMPORTS APPEAR HERE ***
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity='N',
stopbits=1,
bytesize=8
)
# Sets motor number
motor_no = "2"
# Lets create our main GUI class
class ArialApp(object):
# Default init stuff
def __init__(self):
# Create a builder object and create the objects from the .glade file
self.builder = gtk.Builder()
self.builder.add_from_file("../res/main.glade")
self.builder.connect_signals(self)
# Open the serial connection to the encoder and keep it open
ser.open()
# Custom function for sending commands down the serial. Needed to wrap defaults
# arround the custom 'serial.write' command.
self.send_command('A')
# Code removed for space.....
# Custom method for sending commands down serial with default ammendments
def send_command(self, nanotech):
# Send the command with the #, then motor number which should be global, then the command
# sent the the method followed by a return
ser.write("#" + motor_no + nanotech + '\r\n')
# Print to the console the full command sent down the pipe
# [[[ ERROR GOES HERE ]]]
print "#" + motor_no + nanotech + '\r\n'
# Just to show its in here...
if __name__ == "__main__":
app = ArialApp()
gtk.main()
The error:
File "main.py", line 62, in ArialApp
print "#" + motor_no + commands + '\r\n'
NameError: name 'commands' is not defined
Finally, just to shed some context on the situation:
I am writing a small GUI app in Glade and Python / PyGTK to control a stepper motor over serial using the PySerial module. However, I would like to package up my own "write" function so I can append default values to the 'send' down the cable. For example, the motor number and always appending returns on the end of the instructions. Other things like reading back the response straight away in the same function would be useful to gauge responses too, so, wrapping it up into a custom function seemed like the sensible thing to do.
Any advice or help on the above would be appreciated.
Thank-you kindly.
Andy
UPDATE: I have addresses the original issue of not including "self" and I've managed to get Stack to accept the tabs I normally use so its cleaner to look at. Also wanted to note the only code I removed was simple variable setting. However, the issue persists!
A:
It could be because you're missing the self argument:
def send_command(self, commands):
A:
you've got an indentation error in def send_command(commands):
and your first parameter should be "self" :
class ArialApp(object):
<snap>
def send_command(self, commands):
ser.write("#" + motor_no + commands + '\r\n')
A:
Firstly, you should use more than a single space for indentation. White space is significant in Python, and it's very hard to see that you've got it right if you're only using one space. Four is the usually accepted amount.
The main issue with your send_command method is that you've forgotten that the first argument to any method in Python is (by convention) self. So the signature should be:
def send_command(self, commands):
However, the code you have shown would not give the error you state: it would instead give this:
TypeError: send_command() takes exactly 1 argument (2 given)
In addition, in your method it's not commands which is not defined, but motor_no. This is why it's always important to show the actual code you're running, cut down enough to actually reproduce the error.
| Command not defined in Python - Real basics, but confused! | I have written this short script (which I've stripped away some minor detail for size) and I'm getting a very simple error, yet, I don't understand why! I'm very new to Python, so maybe someone can explain the issue and why it's not working?
The error seems to fall when I wish to print the full custom serial write string back to the console, it doesn't seem to recognise the Args I sent to the function.
Perhaps I have misunderstood something very simple. Should be simple for anyone even with the tiniest of Python understanding
Cheers
The Code:
#! /usr/bin/env python
# IMPORTS APPEAR HERE ***
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity='N',
stopbits=1,
bytesize=8
)
# Sets motor number
motor_no = "2"
# Lets create our main GUI class
class ArialApp(object):
# Default init stuff
def __init__(self):
# Create a builder object and create the objects from the .glade file
self.builder = gtk.Builder()
self.builder.add_from_file("../res/main.glade")
self.builder.connect_signals(self)
# Open the serial connection to the encoder and keep it open
ser.open()
# Custom function for sending commands down the serial. Needed to wrap defaults
# arround the custom 'serial.write' command.
self.send_command('A')
# Code removed for space.....
# Custom method for sending commands down serial with default ammendments
def send_command(self, nanotech):
# Send the command with the #, then motor number which should be global, then the command
# sent the the method followed by a return
ser.write("#" + motor_no + nanotech + '\r\n')
# Print to the console the full command sent down the pipe
# [[[ ERROR GOES HERE ]]]
print "#" + motor_no + nanotech + '\r\n'
# Just to show its in here...
if __name__ == "__main__":
app = ArialApp()
gtk.main()
The error:
File "main.py", line 62, in ArialApp
print "#" + motor_no + commands + '\r\n'
NameError: name 'commands' is not defined
Finally, just to shed some context on the situation:
I am writing a small GUI app in Glade and Python / PyGTK to control a stepper motor over serial using the PySerial module. However, I would like to package up my own "write" function so I can append default values to the 'send' down the cable. For example, the motor number and always appending returns on the end of the instructions. Other things like reading back the response straight away in the same function would be useful to gauge responses too, so, wrapping it up into a custom function seemed like the sensible thing to do.
Any advice or help on the above would be appreciated.
Thank-you kindly.
Andy
UPDATE: I have addresses the original issue of not including "self" and I've managed to get Stack to accept the tabs I normally use so its cleaner to look at. Also wanted to note the only code I removed was simple variable setting. However, the issue persists!
| [
"It could be because you're missing the self argument:\n def send_command(self, commands):\n\n",
"you've got an indentation error in def send_command(commands):\nand your first parameter should be \"self\" :\nclass ArialApp(object):\n\n<snap>\n\n def send_command(self, commands):\n ser.write(\"#\" + m... | [
2,
1,
1
] | [] | [] | [
"eclipse",
"glade",
"pydev",
"pygtk",
"python"
] | stackoverflow_0003147786_eclipse_glade_pydev_pygtk_python.txt |
Q:
PyArg_ParseTuple causing segmentation fault
I'm trying to call a c function from my extension and have narrowed the problem down to this test case.
#import "Python.h"
...
// Called from python with test_method(0, 0, 'TEST')
static PyObject*
test_method(PyObject *args)
{
int ok, x, y, size;
const char *s;
// this causes Segmentation fault
//ok = PyArg_ParseTuple(args, "iis#", &x, &y, &s, &size);
// also segfaults
//if(ok) PyErr_SetString(PyExc_SystemError, 'Exception');
// this does not cause segfault but fills the variables with garbage
ok = PyArg_ParseTuple(&args, "iis#", &x, &y, &s, &size);
// Example: >test_method 0, 37567920, (garbage)
printf(">test_method %d, %d, %s\n", x, y, s);
/* Success */
Py_RETURN_NONE;
}
static PyMethodDef testMethods[] =
{
{"test_method", test_method, METH_VARARGS,
"test_method"},
...
{NULL, NULL, 0, NULL}
};
Any ideas what I might be doing wrong. (Python version 2.6.4).
A:
Hmmm. I think the signature of your method should be this:
static PyObject* test_method(PyObject* self, PyObject* args)
If you are invoking your test_method as a bound method (i.e. a method of some object instance), self will be the object itself. If test_method is a module function, self is the pointer passed to Py_InitModule4() when you initialized the module (or NULL if you used Py_InitModule()). The thing is that Python makes no distinctions between bound instance methods and ordinary functions at the code level, that's why you have to pass self even if you are implementing a plain function.
See this page for more details.
| PyArg_ParseTuple causing segmentation fault | I'm trying to call a c function from my extension and have narrowed the problem down to this test case.
#import "Python.h"
...
// Called from python with test_method(0, 0, 'TEST')
static PyObject*
test_method(PyObject *args)
{
int ok, x, y, size;
const char *s;
// this causes Segmentation fault
//ok = PyArg_ParseTuple(args, "iis#", &x, &y, &s, &size);
// also segfaults
//if(ok) PyErr_SetString(PyExc_SystemError, 'Exception');
// this does not cause segfault but fills the variables with garbage
ok = PyArg_ParseTuple(&args, "iis#", &x, &y, &s, &size);
// Example: >test_method 0, 37567920, (garbage)
printf(">test_method %d, %d, %s\n", x, y, s);
/* Success */
Py_RETURN_NONE;
}
static PyMethodDef testMethods[] =
{
{"test_method", test_method, METH_VARARGS,
"test_method"},
...
{NULL, NULL, 0, NULL}
};
Any ideas what I might be doing wrong. (Python version 2.6.4).
| [
"Hmmm. I think the signature of your method should be this:\nstatic PyObject* test_method(PyObject* self, PyObject* args)\n\nIf you are invoking your test_method as a bound method (i.e. a method of some object instance), self will be the object itself. If test_method is a module function, self is the pointer passed... | [
1
] | [] | [] | [
"argument_passing",
"c",
"python",
"python_c_extension"
] | stackoverflow_0003147869_argument_passing_c_python_python_c_extension.txt |
Q:
How to convert comma-separated key value pairs into a dictionary using lambda functions
I'm having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions?
fname:John,lname:doe,mname:dunno,city:Florida
Thanks
A:
There is not really a need for a lambda here.
s = "fname:John,lname:doe,mname:dunno,city:Florida"
sd = dict(u.split(":") for u in s.split(","))
A:
You don't need lambda functions to do this:
>>> s = "fname:John,lname:doe,mname:dunno,city:Florida"
>>> dict(item.split(":") for item in s.split(","))
{'lname': 'doe', 'mname': 'dunno', 'fname': 'John', 'city': 'Florida'}
But you can if you really want to:
>>> dict(map(lambda x: x.split(":"), s.split(",")))
{'lname': 'doe', 'mname': 'dunno', 'fname': 'John', 'city': 'Florida'}
A:
If you really want you can even do this with two lambdas, but never try this at work! Just for fun:
s = "name:John,lname:doe,mname:dunno,city:Florida"
d = reduce(lambda d, kv: d.__setitem__(kv[0], kv[1]) or d,
map(lambda s: s.split(':'), s.split(',')),
{})
| How to convert comma-separated key value pairs into a dictionary using lambda functions | I'm having a little problem figuring out lamba functions. Could someone show me how to split the following string into a dictionary using lambda functions?
fname:John,lname:doe,mname:dunno,city:Florida
Thanks
| [
"There is not really a need for a lambda here.\ns = \"fname:John,lname:doe,mname:dunno,city:Florida\"\nsd = dict(u.split(\":\") for u in s.split(\",\"))\n\n",
"You don't need lambda functions to do this:\n>>> s = \"fname:John,lname:doe,mname:dunno,city:Florida\"\n>>> dict(item.split(\":\") for item in s.split(\",... | [
17,
2,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0003147554_lambda_python.txt |
Q:
Configuration inheritance mechanism
I have the following structure:
config
|-- groups
|-- rootgroup
|-- group1 (includes rootgroup)
|-- group2 (includes group1)
|-- group3 (includes rootgroup)
|-- users
|-- Fred (includes group3 and group2)
So inheritance tree for Fred will look like:
_Fred_
v v
group2 group3
v v
group1 v
v /
rootgroup
I need an algorithm to print the linear config read order beginning at the bottom left of the tree (for given example it would be rootgroup - group1 - group2 - group3; group1 overwrites rootgroup, group2 overwrites group1, etc...) and find recursive links (for example if rootgroup includes group 2), moreover it must find the recursion loop (... -> group2 -> group1 -> rootgroup -> group2 -> ...).
Preferable language is python, but any will do.
Thanks.
A:
Well after reading about directed acyclic graphs (DAG) I came up with following solution:
def getNodeDepsTree(self, node, back_path=None):
"""Return whole dependency tree for given node"""
# List of current node dependencies
node_deps = []
if not back_path:
back_path = []
# Push current node into return path list
back_path.append(node)
# Get current node dependencies list
deps = getNodeDeps(node)
for dep in deps:
# If dependency persist in list of visited nodes - it's a recursion
if dep in back_path:
pos = back_path.index(dep)
self.log.error("Recursive link detected. '" + node
+ "', contains a recursive link to '" + dep
+ "'. Removing dependency. Recursive loop is:\n\t"
+ '\n\t'.join(back_path[pos:]))
continue
# Recursively call self for child nodes
node_deps.extend(self.getNodeDepsTree(dep, back_path))
# Finally add current node as dependency
node_deps.append(node)
# Remove current node from list of visited nodes and return
back_path.pop()
return node_deps
| Configuration inheritance mechanism | I have the following structure:
config
|-- groups
|-- rootgroup
|-- group1 (includes rootgroup)
|-- group2 (includes group1)
|-- group3 (includes rootgroup)
|-- users
|-- Fred (includes group3 and group2)
So inheritance tree for Fred will look like:
_Fred_
v v
group2 group3
v v
group1 v
v /
rootgroup
I need an algorithm to print the linear config read order beginning at the bottom left of the tree (for given example it would be rootgroup - group1 - group2 - group3; group1 overwrites rootgroup, group2 overwrites group1, etc...) and find recursive links (for example if rootgroup includes group 2), moreover it must find the recursion loop (... -> group2 -> group1 -> rootgroup -> group2 -> ...).
Preferable language is python, but any will do.
Thanks.
| [
"Well after reading about directed acyclic graphs (DAG) I came up with following solution:\ndef getNodeDepsTree(self, node, back_path=None):\n \"\"\"Return whole dependency tree for given node\"\"\"\n # List of current node dependencies\n node_deps = []\n\n if not back_path:\n back_path = []\n\n ... | [
0
] | [] | [] | [
"inheritance",
"python",
"recursion"
] | stackoverflow_0003139915_inheritance_python_recursion.txt |
Q:
approaching django model fields through a field name mapping
Django newbie here,
I have several types of models, in each of them the fields have different names (e.g. first_name, forename, prenom) and I want each of the models to contain a mapping so that I can easily approach each of the fields using one conventional name (e.g. first_name for all of the field names). what's a good way of doing this?
A:
I think the best way would be to use conventional names in your models and provide only one obvious way to access it. If you don't wan't to change the database columns too, you can use the db_column option. Example:
class Person(models.Model):
first_name = models.CharField(max_length=255, db_column='prenom')
class Customer(models.Model):
first_name = models.CharField(max_length=255, db_column='forename')
class Worker(models.Model):
first_name = models.CharField(max_length=255) # column is also called "first_name"
If you need to provide different ways to access the members (which I would try to avoid!) you can still add properties to each model.
A:
You could define a @property on each of your models, like this:
class Personage(models.Model):
prenom = models.CharField(max_length=255)
@property
def first_name(self):
return self.prenom
then you can just reference your new property like this:
personage = Personage.objects.all()[0]
personage.first_name
A:
You could make your models all inherit a new model that has a property function defined to get/set the right variable.
class BaseNameClass(models.Model)
def getfname(self):
if hasattr(self, 'first_name'): return self.first_name
if hasattr(self, 'prenom'): return self.prenom
if hasattr(self, 'forename'): return self.forename
def setfname(self, x):
if hasattr(self, 'first_name'): self.first_name = x
if hasattr(self, 'prenom'): self.prenom = x
if hasattr(self, 'forename'): self.forename = x
firstname = property(getfname, setfname)
And then change your models to all inherit from that. It will be slightly slower but we're talking nano and milliseconds.
If you had an descendant object called person, you'd access the name simply by:
print person.firstname
person.firstname = "oli"
print person.firstname
| approaching django model fields through a field name mapping | Django newbie here,
I have several types of models, in each of them the fields have different names (e.g. first_name, forename, prenom) and I want each of the models to contain a mapping so that I can easily approach each of the fields using one conventional name (e.g. first_name for all of the field names). what's a good way of doing this?
| [
"I think the best way would be to use conventional names in your models and provide only one obvious way to access it. If you don't wan't to change the database columns too, you can use the db_column option. Example:\nclass Person(models.Model):\n first_name = models.CharField(max_length=255, db_column='prenom')... | [
4,
2,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003148027_django_django_models_python.txt |
Q:
Is it possible to access the source code of a python script passed to python on standard in?
This is a bit of a random question that is more out of curiosity than any specific need.
Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python code stored in a file? For example, doing something like this at the Bash prompt:
$ echo '
> print "The Code:"
> PrintScript() # What would this function look like?
> for i in range(5):
> print i,
> print "!"
> ' | python
and get an output like this:
The Code:
print "The Code:"
PrintScript() # What would this function look like?
for i in range(5):
print i,
print "!"
0 1 2 3 4 5 !
I suspect that this probably can't be done, but given python's introspection capabilities, I was curious to know whether it extended to this level.
A:
That's the closest I'm getting:
echo 'import __main__,inspect;print inspect.getsource(__main__)' | python
which fails... In any case, the original code is eaten up (read from stdin) by the interpreter at startup. At most you may be able to get to the compiled code, again through the __main__ module.
Update:
The dis module is supposed to give you a disassembly of all functions in a module, but even that one isn't seeing any code:
$ echo -e 'import __main__,dis;print dis.dis(__main__)' | python
None
And even when I throw in a function:
$ echo -e "import __main__,dis;print dis.dis(__main__)\ndef x():\n pass" | python
None
A:
Yes, it is indeed possible to write a program which outputs it's own source. You don't need even introspection for this tasks, you just need to be able to print computed strings (works with every language).
The technique is called Quine and here is a rather short example in Python:
quine = 'quine = %r\r\nprint quine %% quine'
print quine % quine
But quines aren't limited to such simple programs. They can do much more, for example printing their own source backwards and so on... :)
A:
print open(__file__).read(),
This will work on UNIX systems I think, but I'm not sure about Windows. The trailing comma makes sure that the source code is printed exactly, without an extra trailing newline.
Just realized (based on the comments below) that this does not work if your source code comes from sys.stdin, which is exactly what you were asking for. In that case, you might take advantage of some of the ideas outlined on this page about quines (programs printing their own source codes) in Python, but none of the solutions would be a single function that just works. A language-independent discussion is here.
So, in short, no, I don't think this is possible with a single function if your source code comes from the standard input. There might be a possibility to access the interpreted form of your program as a Python code object and translate that back into source form, but the translated form will almost surely not match the original file contents exactly. (For instance, the comments and the shebang line would definitely be stripped away).
A:
closest you can get is using readline to interrogate the command history if available from what i can see e.g. but i suspect this may not contain stuff piped into the session and would only work for interactive sessions anyway
| Is it possible to access the source code of a python script passed to python on standard in? | This is a bit of a random question that is more out of curiosity than any specific need.
Is it possible to write some python code that will print some stuff out, including the source code itself, without having the python code stored in a file? For example, doing something like this at the Bash prompt:
$ echo '
> print "The Code:"
> PrintScript() # What would this function look like?
> for i in range(5):
> print i,
> print "!"
> ' | python
and get an output like this:
The Code:
print "The Code:"
PrintScript() # What would this function look like?
for i in range(5):
print i,
print "!"
0 1 2 3 4 5 !
I suspect that this probably can't be done, but given python's introspection capabilities, I was curious to know whether it extended to this level.
| [
"That's the closest I'm getting:\necho 'import __main__,inspect;print inspect.getsource(__main__)' | python\n\nwhich fails... In any case, the original code is eaten up (read from stdin) by the interpreter at startup. At most you may be able to get to the compiled code, again through the __main__ module.\nUpdate:\... | [
3,
2,
1,
1
] | [] | [] | [
"python",
"quine",
"stdin"
] | stackoverflow_0003147823_python_quine_stdin.txt |
Q:
HTML generation in Python
What's the easiest way to quickly create some simple HTML in Python? All I've found so far are complex templating systems or classes for HTML generation with APIs that seem much heavier than what I need.
I could just do it myself by sticking strings together but I thought there might be a library that could save me a little time.
edit- I decided to take a closer look at the Jinja2 templating system. It looks like it could be useful at some point in the future and doesn't look like it will take as much time to figure out as I thought.
A:
quixote is an old-ish but still fascinating framework -- it basically "embeds HTML in Python" (rather than vice versa, as all popular templating systems do).
One simple example from the overview:
def format_row [html] (head, value):
"<tr valign=top align=left>\n"
" <th align=left>%s</th>\n" % head
" <td>%s</td>\n" % value
"</tr>\n"
In Python proper, the first of those strings would be the docstring, the others would be ignored, and the [html] part would be a syntax error. In Quixote, the [html] marks this function as being "PTL" (Python Template Language) rather than Python proper, the file extension to use for modules with such functions is .ptl, but they can still be imported from Python and those strings are output.
I doubt you want to adopt Quixote in preference to modern Python templating approaches, but it does make for interesting reading, IMHO.
Further along similar lines is nevow (though it's more geared to generating XML, not HTML per se), esp. stan, where the canonical example is...:
>>> from nevow import flat, stan
>>> html = stan.Tag('html')
>>> p = stan.Tag('p')
>>> someStan = html[ p(style='font-family: Verdana;')[ "Hello, ", "world!" ] ]
>>> flat.flatten(someStan)
'<html><p style="font-family: Verdana;">Hello, world!</p></html>'
Kind of "even cooler"... because you don't have to worry about closing tags correctly;-).
In the end, though, for production work templating systems like jinja2 or mako are typically preferred these days -- the main practical reason being the better separation of presentation logic (in the template) from other layers (in Python code proper) than they offer wrt the "embed HTML/XML within Python" approaches, I guess.
A:
Have a look at the Markup module: http://markup.sourceforge.net/
Edit: Here's another module that looks quite similar: http://www.decalage.info/en/python/html
A:
The Python string.Template may do what you want. And it's built-in.
http://docs.python.org/library/string.html#template-strings
I can't understand "APIs that seem much heavier" without further definition or examples.
A:
If you're looking for basic and barebones then the ancient HTMLgen will do. Otherwise, use a template engine.
| HTML generation in Python | What's the easiest way to quickly create some simple HTML in Python? All I've found so far are complex templating systems or classes for HTML generation with APIs that seem much heavier than what I need.
I could just do it myself by sticking strings together but I thought there might be a library that could save me a little time.
edit- I decided to take a closer look at the Jinja2 templating system. It looks like it could be useful at some point in the future and doesn't look like it will take as much time to figure out as I thought.
| [
"quixote is an old-ish but still fascinating framework -- it basically \"embeds HTML in Python\" (rather than vice versa, as all popular templating systems do).\nOne simple example from the overview:\ndef format_row [html] (head, value):\n \"<tr valign=top align=left>\\n\"\n \" <th align=left>%s</th>\\n\" % ... | [
2,
1,
1,
0
] | [] | [] | [
"html_generation",
"python"
] | stackoverflow_0003145935_html_generation_python.txt |
Q:
Inserting records into Sqlite using Python parameter substitution where some fields are blank
I am running this sort of query:
insert into mytable (id, col1, col2)
values (:ID, :COL1, :COL2)
In Python, a dictionary of this form can be used in conjuction with the query above for parameter substitution:
d = { 'ID' : 0, 'COL1' : 'hi', 'COL2' : 'there' }
cursor.execute(sql_insert, d)
But in the real problem, there are lots of columns and lots of rows. Sometimes the data source that populates the dictionary doesn't have an entry. However, if the dictionary is short, Sqlite will complain that an incorrect number of bindings was supplied, rather than giving me a way to add empty strings or NULLs in the columns which are not populated in this case.
I'm being a lazy, or a bit perfectionist. I could write some code to add any missing fields to the dictionary. I'm just looking for an elegant solution that doesn't require triplicating the list of fields.
I tried overloading the dictionary with a modified dictionary that returns an empty string if the field is missing.
A:
I haven't checked that this works, but I think it should:
from collections import defaultdict
d = { 'ID' : 0, 'COL1' : 'hi' }
cursor.execute(sql_insert, defaultdict(str, d))
defaultdict is a specialised dictionary where any missing keys generate a new value instead of throwing a KeyError.
Of course this only works if all the values need the same default such as an empty string or None. If you need different defaults then you'll need a dictionary containing the defaults and you can do:
DEFAULTS = { ... whatever ... }
d = { 'ID' : 0, 'COL1' : 'hi' }
cursor.execute(sql_insert, dict(DEFAULTS).update(d))
Note that you must copy DEFAULTS each time so you can update the copy with the actual values.
A:
To be honest, I'm not entirely sure what you're asking. It seems you're saying that you want to build an insert statement for a table row where you have some but not all of the field values ready.
You could build your query like this (taking advantage of dict.get returning None for missing keys):
>>> columns = ['id','col1','col2','col_missing']
>>> myData = {'id': 0, 'col1': 'hi', 'col2':'there'}
>>> myQuery = 'insert into mytable (%s) values (%s)' % (",".join(columns),",".join(['%s']*len(columns)))
>>> myArgs = [ myData.get(x) for x in columns ]
>>> myQuery
'insert into mytable (id,col1,col2,col_missing) values (%s,%s,%s,%s)'
>>> myArgs
[0, 'hi', 'there', None]
>>> cursor.execute(myQuery,myArgs)
A:
The DEFAULT constraint specifies a default value to use when doing an INSERT. The value may be NULL, a string constant, a number, or a constant expression enclosed in parentheses
quoted from here.
so use CREATE like this:
CREATE mytable {
id INTEGER PRIMARY KEY,
col1 TEXT DEFAULT 'Hello, World!',
col2 TEXT DEFAULT 'The cake in a lie'
}
| Inserting records into Sqlite using Python parameter substitution where some fields are blank | I am running this sort of query:
insert into mytable (id, col1, col2)
values (:ID, :COL1, :COL2)
In Python, a dictionary of this form can be used in conjuction with the query above for parameter substitution:
d = { 'ID' : 0, 'COL1' : 'hi', 'COL2' : 'there' }
cursor.execute(sql_insert, d)
But in the real problem, there are lots of columns and lots of rows. Sometimes the data source that populates the dictionary doesn't have an entry. However, if the dictionary is short, Sqlite will complain that an incorrect number of bindings was supplied, rather than giving me a way to add empty strings or NULLs in the columns which are not populated in this case.
I'm being a lazy, or a bit perfectionist. I could write some code to add any missing fields to the dictionary. I'm just looking for an elegant solution that doesn't require triplicating the list of fields.
I tried overloading the dictionary with a modified dictionary that returns an empty string if the field is missing.
| [
"I haven't checked that this works, but I think it should:\nfrom collections import defaultdict\nd = { 'ID' : 0, 'COL1' : 'hi' }\ncursor.execute(sql_insert, defaultdict(str, d))\n\ndefaultdict is a specialised dictionary where any missing keys generate a new value instead of throwing a KeyError.\nOf course this onl... | [
7,
0,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003148315_python_sqlite.txt |
Q:
How to pickle a empty file?
I want to pickle a file that sometime's is empty. Right now its empty, but my idea is that its going to grow over time.
How do i check if a file is "pickable" since it seems that you can not pickle a empty file?
A:
Simply use a try/except block.
def example():
try:
return pickle.loads("")
except EOFError:
return None
It's easier to ask forgiveness than permission. :)
A:
Pickle is considered unsafe. Try Cerealizer instead. It might incidentally solve your empty file problem.
| How to pickle a empty file? | I want to pickle a file that sometime's is empty. Right now its empty, but my idea is that its going to grow over time.
How do i check if a file is "pickable" since it seems that you can not pickle a empty file?
| [
"Simply use a try/except block.\ndef example():\n try:\n return pickle.loads(\"\")\n except EOFError:\n return None\n\nIt's easier to ask forgiveness than permission. :)\n",
"Pickle is considered unsafe. Try Cerealizer instead. It might incidentally solve your empty file problem.\n"
] | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0003148656_python.txt |
Q:
Are Interfaces just "Syntactic Sugar"?
I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
Do Interfaces were created in another languages because they don't provide multiple inheritance? Or am I missing something more important here?
A:
First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires.
It's a lot like comparing the number 7 and the color green. They're both nouns. Beyond that, you're going to have trouble comparing the two.
Here's the bottom line.
Python does not need interfaces.
Java requires them.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
The two concepts have almost nothing to do with each other.
I can define a large number of classes which share a common interface. In Python, because of "duck typing", I don't have to carefully be sure they all have a common superclass.
An interface is a declaration of "intent" for disjoint class hierarchies. It provides a common specification (that can be checked by the compiler) that is not part of the simple class hierarchy. It allows multiple class hierarchies to implement some common features and be polymorphic with respect to those features.
In Python you can use multiple inheritance with our without interfaces. Multiple inheritance can include interface classes or not include interface classes.
Java doesn't even have multiple inheritance. Instead it uses a completely different technique called "mixins".
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
If you create an interface in Python, it can be a kind of formal contract. A claim that all subclasses will absolutely do what the interface claims.
Of course, a numbskull is perfectly free to lie. They can inherit from an interface and mis-implement everything. Nothing prevents bad behavior from sociopaths.
You create an interface in Java to allow multiple classes of objects to have a common behavior. Since you don't tell the compiler much in Python, the concept doesn't even apply.
Do Interfaces were created in another languages because they don't provide multiple inheritance?
Since the concepts aren't related, it's hard to answer this.
In Java, they do use "mixin" instead of multiple inheritance. The "interface" allows some mixing-in of additional functionality. That's one use for an interface.
Another use of an Interface to separate "is" from "does". The class hierarchy defines what an objects IS. The interface hierarchy defines what a class DOES.
In most cases, IS and DOES are isomorphic, so there's no distinction.
In some cases, what an object IS and what an object DOES are different.
A:
The usefulness of an interface is directly connected to the usefulness of static typing. If you're working in a dynamically-typed language like PHP or Python, interfaces truly don't add significantly to the expressiveness of the language. That is, any program that can be described as using interfaces can be expressed without significant difference without using interfaces.
As a result, Python has a fairly nebulous concept of a "protocol" (an implementation conforming to a certain pattern, like the iteration protocol) which amounts to essentially the same thing, but without the other benefits of compile-time checking its value is limited.
In a statically-typed language, on the other hand, an interface is essential to allow implementation to be decoupled from implementation. In a static language, the types of all expressions must be resolved at compile time, so normally bindings to implementation must be made at that time, limiting run-time flexibility. An interface defines how to access functionality without defining a specific implementation, which allows a static language to prove that expressions are correct without having access to the implementation.
Without interfaces (or an equivalent formulation like C++'s pure virtual functions), the expressiveness of a statically-typed language would be severely hampered. In fact, many implementations exist (Win32 and COM come immediately to mind) to essentially reproduce much of the functionality of interfaces and virtual dispatch in C by storing function pointers in structures (and thus re-implementing C++'s virtual functions and vtable invocation by hand). In this case there is a big difference in expressiveness, since many changes are required in the program to express the same concepts.
Interfaces are just one example of type polymorphism, and a fairly limited one at that. In languages that support parametric polymorphism (aka generics) you can accomplish much more. (For example, C#'s LINQ would not be possible without generic interfaces.) For a much more powerful form of the same kind of thing, look into Haskell's typeclasses.
A:
Even in duck-typed languages like Python, an interface can be a clearer statement of your intent. If you have a number of implementations, and they share a set of methods, an interface can be a good way to document the external behavior of those methods, give the concept a name, and make the concept concrete.
Without the explicit interface, there's an important concept in your system that has no physical representation. This doesn't mean you have to use interfaces, but interfaces provide that concreteness.
A:
In dynamically typed languages, like PHP and Python, interfaces are only of limited use. You can already attempt to call methods on any object whenever, and you get a run-time error if it doesn't exist.
It's in statically typed languages, like Java and .NET, that interfaces become important, because methods and their arguments are checked at compile-time.
Now, for interfaces:
Java has Lists in addition to arrays. As a general rule, arrays are for primitives (the number types mainly), while Lists are for objects.
I can have a List<String>, which is a list of strings. I know I can add strings to it, and get strings back from it.
I don't know which implementation it is. It could be an ArrayList (list backed by an array), a LinkedList (list backed by a doubly linked list), a CopyOnWriteArrayList (thread-safe version of ArrayList), etc...
Thanks to polymorphism and interfaces, I don't need to know which type of List it is to do List operations on it.
A:
Because you want to program against an interface and not a concrete implementation (GoF 1995:18)
A:
Because sometimes you don't want to provide an implementation.
Java Interface
Java class
A:
Yes. As for PHP, interfaces are just a means to overcome the lack of multiple inheritance. There are minor semantic differences useful for IDEs, and fewer conflicts caused by interfaces clearly aid newbie programmers. But as said before, it's not strictly necessary in dynamic languages.
http://c2.com/cgi/wiki?MultipleInheritance
A:
Please read Twisted Framework article about power of Zope Interfaces in python.
A:
It's generally implemented to replace multiple inheritance (C#).
I think some languages/programmers use them as a way of enforcing requirements for object structure as well.
| Are Interfaces just "Syntactic Sugar"? | I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
Do Interfaces were created in another languages because they don't provide multiple inheritance? Or am I missing something more important here?
| [
"First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires. \nIt's a lot like c... | [
13,
12,
5,
4,
3,
1,
1,
1,
0
] | [] | [] | [
"interface",
"oop",
"php",
"python"
] | stackoverflow_0003134531_interface_oop_php_python.txt |
Q:
How do I get the class of a ManyToMany field in django models?
I have some fields in a model that are ManyToMany, I want the ManyToMany class itself, when I only have the field name. Is there any way I can retrieve it?
A:
If model_obj were an instance of the Model class that defines a ManyToManyField named foom2m, then you could do this:
related_model = model_obj.__class_.foom2m.field.rel.to
| How do I get the class of a ManyToMany field in django models? | I have some fields in a model that are ManyToMany, I want the ManyToMany class itself, when I only have the field name. Is there any way I can retrieve it?
| [
"If model_obj were an instance of the Model class that defines a ManyToManyField named foom2m, then you could do this:\nrelated_model = model_obj.__class_.foom2m.field.rel.to\n\n"
] | [
1
] | [] | [] | [
"django_models",
"python"
] | stackoverflow_0003148879_django_models_python.txt |
Q:
How to set up Atana Studio 3 Themes in Pydev
I've installed the Aptana Studio 3 preview and noticed it has support for themes (such as a bespin style or Ruby envy) and I'd love to use the Bespin one in Pydev but so far I've had no luck getting it to work, anyone have a clue as to how to get it to work?
Video showing the themes in action.
A:
Window->Preferences
Aptana->Themes
| How to set up Atana Studio 3 Themes in Pydev | I've installed the Aptana Studio 3 preview and noticed it has support for themes (such as a bespin style or Ruby envy) and I'd love to use the Bespin one in Pydev but so far I've had no luck getting it to work, anyone have a clue as to how to get it to work?
Video showing the themes in action.
| [
"\nWindow->Preferences\nAptana->Themes\n\n"
] | [
1
] | [] | [] | [
"aptana",
"pydev",
"python",
"themes"
] | stackoverflow_0002880193_aptana_pydev_python_themes.txt |
Q:
One-to-one relationships between entities in the Python Google App Engine
Is to possible to create one-to-one relations in the Python version of Google App Engine? I know it is possible in Java.
A:
Sure - just use a ReferenceProperty that references an entity not referenced by anything else.
| One-to-one relationships between entities in the Python Google App Engine | Is to possible to create one-to-one relations in the Python version of Google App Engine? I know it is possible in Java.
| [
"Sure - just use a ReferenceProperty that references an entity not referenced by anything else.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003148719_google_app_engine_python.txt |
Q:
Manipulating the db with SQL Server 2005 - Django
I'm trying to accomplish the following:
Grab the db schema
Grab any constraints*
Alter tables
Add/Drop tables
I'm currently using pyodbc backend for Django.
I would like to perform all these tasks within a view file.
I'm using the following in order to grab fields of tables starting with 'core_':
SELECT table_name,ordinal_position,column_name,data_type,
is_nullable,character_maximum_length FROM
information_schema.COLUMNS WHERE table_name LIKE 'core_%'
ORDER BY ordinal_position
*Fixed thanks to Madhivanan Link
Any ideas to get started?
A:
Try this by using a wildcard %
SELECT table_name,ordinal_position,column_name,data_type,
is_nullable,character_maximum_length FROM
information_schema.COLUMNS WHERE table_name LIKE 'core_%'
ORDER BY ordinal_position
| Manipulating the db with SQL Server 2005 - Django | I'm trying to accomplish the following:
Grab the db schema
Grab any constraints*
Alter tables
Add/Drop tables
I'm currently using pyodbc backend for Django.
I would like to perform all these tasks within a view file.
I'm using the following in order to grab fields of tables starting with 'core_':
SELECT table_name,ordinal_position,column_name,data_type,
is_nullable,character_maximum_length FROM
information_schema.COLUMNS WHERE table_name LIKE 'core_%'
ORDER BY ordinal_position
*Fixed thanks to Madhivanan Link
Any ideas to get started?
| [
"Try this by using a wildcard %\nSELECT table_name,ordinal_position,column_name,data_type, \nis_nullable,character_maximum_length FROM \ninformation_schema.COLUMNS WHERE table_name LIKE 'core_%' \nORDER BY ordinal_position \n\n"
] | [
3
] | [] | [] | [
"django",
"pyodbc",
"python",
"sql",
"sql_server"
] | stackoverflow_0003149396_django_pyodbc_python_sql_sql_server.txt |
Q:
Opening SSL URLs with Python
I'm using mechanize to navigate pages, it works pretty well.
Unfortunately I have a random error come up, by random I mean it occasionally appears.
URLError at /test/
urlopen error [Errno 1] _ssl.c:1325: error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record mac>
I really need help on this one :)
any ideas?
A:
I had a similar error and found that PycURL works way better than urllib.
Django request XML file with SSL IO error
| Opening SSL URLs with Python | I'm using mechanize to navigate pages, it works pretty well.
Unfortunately I have a random error come up, by random I mean it occasionally appears.
URLError at /test/
urlopen error [Errno 1] _ssl.c:1325: error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record mac>
I really need help on this one :)
any ideas?
| [
"I had a similar error and found that PycURL works way better than urllib.\nDjango request XML file with SSL IO error\n"
] | [
1
] | [] | [] | [
"django",
"linux",
"mechanize",
"python",
"ssl"
] | stackoverflow_0002603119_django_linux_mechanize_python_ssl.txt |
Q:
Python Script Hangs, Potentially an Infinite Loop?
Once again working on Project Euler, this time my script just hangs there. I'm pretty sure I'm letting it run for long enough, and my hand-trace (as my father calls it) yields no issues. Where am I going wrong?
I'm only including the relevant portion of the code, for once.
def main():
f, n = 0, 20
while f != 20:
f = 0
for x in range(1,21):
if n % x != 0: break
else: ++f
if f == 20: print n
n += 20
Thanks in advance!
A:
Python doesn't have increment (++). It's interpreted as +(+(a)). + is the unary plus operator, which basically does nothing. Use += 1
A:
Here in your case 'f' value can never reach 20 and hence never exit
1) At 1st break (when n=20 and x =3) it again set f=0.
Similarly for next loop also n get increased 20 but when 'x' is 3 again same f=0
So this will go in infinite loop....
| Python Script Hangs, Potentially an Infinite Loop? | Once again working on Project Euler, this time my script just hangs there. I'm pretty sure I'm letting it run for long enough, and my hand-trace (as my father calls it) yields no issues. Where am I going wrong?
I'm only including the relevant portion of the code, for once.
def main():
f, n = 0, 20
while f != 20:
f = 0
for x in range(1,21):
if n % x != 0: break
else: ++f
if f == 20: print n
n += 20
Thanks in advance!
| [
"Python doesn't have increment (++). It's interpreted as +(+(a)). + is the unary plus operator, which basically does nothing. Use += 1\n",
"Here in your case 'f' value can never reach 20 and hence never exit\n1) At 1st break (when n=20 and x =3) it again set f=0.\nSimilarly for next loop also n get increased ... | [
3,
0
] | [] | [] | [
"infinite_loop",
"python"
] | stackoverflow_0003149496_infinite_loop_python.txt |
Q:
How to recognize current location in python?
My client has two offices in Germany and USA and a python program should recognize the office location. What will be the most elegant way to implement this? It only have to recognize the country. Furthermore it also could happens that there will be no permanent internet connection. The program works on windows but the solution should be os independent.
Any suggestions?
Thanks
A:
AFAIK, there's no elegant solution. You can make educated guesses, but then, take this example: I unplug my laptop in Germany and go to the USA. I plug it in the US office - the regional settings are the same, the time zone didn't change, now what?
Things from which you can make a guess:
regional and language settings (but a German in the USA can be using de_DE)
time zone (but are we in NYC or in Brazil? same TZ offset; in your case, (PDT/EDT) and CET is different enough)
internal IP address (assuming your offices have different internal addressing (e.g. "10.5.20.0/24 - Germany, 192.168.4.0/24 - USA"; what of the VPNs, what about unconnected devices?)
external IP address (if you need accuracy on the scale USA/Europe, this is passable; of course, VPNs mess this up, and question says external connectivity may not be available)
keeping a list of which computer is where (messy and hard to maintain)
keeping a list of which user is where
remembering where this computer was on last program start (and whether it was corrected manually)
By assigning a score to each of these things, and checking for each, you could get a probability score where the computer is. You might get some incorrect guesses though, so make a manual override, too.
The combined score might be quite accurate in the general case; what you need to do is find the edge and corner cases, then find some way to identify those.
| How to recognize current location in python? | My client has two offices in Germany and USA and a python program should recognize the office location. What will be the most elegant way to implement this? It only have to recognize the country. Furthermore it also could happens that there will be no permanent internet connection. The program works on windows but the solution should be os independent.
Any suggestions?
Thanks
| [
"AFAIK, there's no elegant solution. You can make educated guesses, but then, take this example: I unplug my laptop in Germany and go to the USA. I plug it in the US office - the regional settings are the same, the time zone didn't change, now what?\nThings from which you can make a guess:\n\nregional and language ... | [
5
] | [] | [] | [
"geolocation",
"python"
] | stackoverflow_0003149579_geolocation_python.txt |
Q:
How do I get the index of the largest list inside a list of lists using Python?
I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists:
props = [lx,ly,lz,sx,sy,sz,rx,ry,rz]
I printed out the keyframes for each property/track in an arbitrary animation and they are of different lengths:
track Position . X has 24 keys
track Position . Y has 24 keys
track Position . Z has 24 keys
track Scale . X has 1 keys
track Scale . Y has 1 keys
track Scale . Z has 1 keys
track Rotation . H has 23 keys
track Rotation . P has 24 keys
track Rotation . B has 24 keys
Now if I want to use those keys in Blender I need to do something like:
go to the current frame
set the properties for that key frame( can be location,rotation,scale) and insert a keyframe
So far my plan is to:
Loop from 0 to the maximum number of key frames for all the properties
Loop through each property
Check if it has a value stored for the current key, if so, go to the frame in Blender and store the values/insert keyframe
Is this the best way to do this ?
This is the context for the question.
First I need to find the largest list that props stores. I'm new to python and was wondering if there was a magic function that does that for you. Similar to max(), but for list lengths.
At the moment I'm thinking of coding it like this:
# after props are set
lens = []
for p in props: lens.append(len(p))
maxLen = max(lens)
What would be the best way to get that ?
Thanks
A:
max(enumerate(props), key = lambda tup: len(tup[1]))
This gives you a tuple containing (index, list) of the longest list in props.
A:
You can use a generator expression:
maxLen = max(len(p) for p in props)
| How do I get the index of the largest list inside a list of lists using Python? | I am storing animation key frames from Cinema4D(using the awesome py4D) into a lists of lists:
props = [lx,ly,lz,sx,sy,sz,rx,ry,rz]
I printed out the keyframes for each property/track in an arbitrary animation and they are of different lengths:
track Position . X has 24 keys
track Position . Y has 24 keys
track Position . Z has 24 keys
track Scale . X has 1 keys
track Scale . Y has 1 keys
track Scale . Z has 1 keys
track Rotation . H has 23 keys
track Rotation . P has 24 keys
track Rotation . B has 24 keys
Now if I want to use those keys in Blender I need to do something like:
go to the current frame
set the properties for that key frame( can be location,rotation,scale) and insert a keyframe
So far my plan is to:
Loop from 0 to the maximum number of key frames for all the properties
Loop through each property
Check if it has a value stored for the current key, if so, go to the frame in Blender and store the values/insert keyframe
Is this the best way to do this ?
This is the context for the question.
First I need to find the largest list that props stores. I'm new to python and was wondering if there was a magic function that does that for you. Similar to max(), but for list lengths.
At the moment I'm thinking of coding it like this:
# after props are set
lens = []
for p in props: lens.append(len(p))
maxLen = max(lens)
What would be the best way to get that ?
Thanks
| [
"max(enumerate(props), key = lambda tup: len(tup[1]))\n\nThis gives you a tuple containing (index, list) of the longest list in props.\n",
"You can use a generator expression:\nmaxLen = max(len(p) for p in props)\n\n"
] | [
26,
8
] | [] | [] | [
"blender",
"cinema_4d",
"list",
"python"
] | stackoverflow_0003149502_blender_cinema_4d_list_python.txt |
Q:
ctypes outputting unknown value at end of correct values
I have the following DLL ('arrayprint.dll') function that I want to use in Python via ctypes:
__declspec(dllexport) void PrintArray(int* pArray) {
int i;
for(i = 0; i < 5; pArray++, i++) {
printf("%d\n",*pArray);
}
}
My Python script is as follows:
from ctypes import *
fiveintegers = c_int * 5
x = fiveintegers(2,3,5,7,11)
px = pointer(x)
mydll = CDLL('arrayprint.dll')
mydll.PrintArray(px)
The final function call outputs the following:
2
3
5
7
11
2226984
What is the 2226984 and how do I get rid of it? It doesn't look to be the decimal value for the memory address of the DLL, x, or px.
Thanks,
Mike
(Note: I'm not actually using PrintArray for anything; it was just the easiest example I could find that generated the same behavior as the longer function I'm using.)
A:
mydll.PrintArray.restype = None
mydll.PrintArray(px)
By default ctypes assumes the function returns an integral type, which causes undefined behavior (reading a garbage memory location).
| ctypes outputting unknown value at end of correct values | I have the following DLL ('arrayprint.dll') function that I want to use in Python via ctypes:
__declspec(dllexport) void PrintArray(int* pArray) {
int i;
for(i = 0; i < 5; pArray++, i++) {
printf("%d\n",*pArray);
}
}
My Python script is as follows:
from ctypes import *
fiveintegers = c_int * 5
x = fiveintegers(2,3,5,7,11)
px = pointer(x)
mydll = CDLL('arrayprint.dll')
mydll.PrintArray(px)
The final function call outputs the following:
2
3
5
7
11
2226984
What is the 2226984 and how do I get rid of it? It doesn't look to be the decimal value for the memory address of the DLL, x, or px.
Thanks,
Mike
(Note: I'm not actually using PrintArray for anything; it was just the easiest example I could find that generated the same behavior as the longer function I'm using.)
| [
"mydll.PrintArray.restype = None\nmydll.PrintArray(px)\n\nBy default ctypes assumes the function returns an integral type, which causes undefined behavior (reading a garbage memory location).\n"
] | [
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0003149768_ctypes_python.txt |
Q:
How can I avoid circular imports in Python?
I'm having a problem with circular imports. I have three Python test modules: robot_test.py which is my main script, then two auxiliary modules, controller_test.py and servo_test.py. The idea is that I want controller_test.py to define a class for my microcontroller and servo_test.py to define a class for my servos. I then want to instantiate these classes in robot_test.py. Here are my three test modules:
""" robot_test.py """
from pi.nodes.actuators.servo_test import Servo
from pi.nodes.controllers.controller_test import Controller
myController = Controller()
myServo = Servo()
print myController.ID, myServo.ID
""" controller_test.py """
class Controller():
def __init__(self, id="controller"):
self.ID = id
""" servo_test.py """
class Servo():
def __init__(self, id="servo"):
self.ID = id
If I run robot_test.py, I get the expected printout:
controller servo
However, now comes the twist. In reality, the servo_test.py module depends on controller_test.py by way of robot_test.py. This is because my servo definitions require an already-instantiated controller object before they themselves can be instantiated. But I'd like to keep all the initial instantiations in robot_test.py. So I tried modifying my servo_test.py script as follows:
""" servo_test.py """
from pi.nodes.robots.robot_test import myController
class Servo():
def __init__(self, id="servo"):
self.ID = id
print myController.ID
Of course, I could sense that the circularity was going to cause problems and sure enough, when I now try to run robot_test.py I get the error:
ImportError: Cannot import name Servo
which in turn is caused by servo_test.py returning the error:
ImportError: Cannot import name myController
In C# I would define myController and myServo as static objects in robot_test.py and then I could use them in other classes. Is there anyway to do the same in Python? One workaround I have found is to pass the myController object to the Servo class as an argument, but I was hoping to avoid having to do this.
Thanks!
A:
One workaround I have found is to pass
the myController object to the Servo
class as an argument, but I was hoping
to avoid having to do this.
Why ever would you want to avoid it? It's a classic case of a crucial Design Pattern (maybe the most important one that wasn't in the original Gang of Four masterpiece), Dependency Injection.
DI implementation alternatives to having the dependency in the initializer include using a setter method (which completes another crucial non-Gof4 DP, two-phase construction, started in the __init__) -- that avoids another circularity problem not related to imports, when A's instances need a B and B's instances need an A, in each case to complete what's logically the instances "initialization". But when you don't need two-phase construction, initializers are the natural place to inject dependencies.
Beyond the advantages related to breaking circularity, DI facilitates reuse (by generalization: e.g, if and when you need to have multiple controllers and servos rather than just one of each, it allows you to easily control the "pairing up" among them) and testing (it becomes easy to isolate each class for testing purposes by injecting in it a mock of the other, for example).
What's not to like?
A:
servo_test.py doesn't actually need myController, since the access is within a function. Import the module instead, and access myController via that module.
import pi.nodes.robots.robot_test as robot_test
class Servo():
def __init__(self, id="servo"):
self.ID = id
print robot_test.myController.ID
This will work as long as myController exists before Servo is instantiated.
A:
Pass the instantiated controller object as an init argument to the instantiation of the Servo.
""" servo_test.py """
class Servo():
def __init__(self,controller,id="servo"):
self.ID = id
self.ctrl = controller
print self.ctrl.ID
""" robot_test.py """
from pi.nodes.actuators.servo_test import Servo
from pi.nodes.controllers.controller_test import Controller
myController = Controller()
myServo = Servo(myController)
| How can I avoid circular imports in Python? | I'm having a problem with circular imports. I have three Python test modules: robot_test.py which is my main script, then two auxiliary modules, controller_test.py and servo_test.py. The idea is that I want controller_test.py to define a class for my microcontroller and servo_test.py to define a class for my servos. I then want to instantiate these classes in robot_test.py. Here are my three test modules:
""" robot_test.py """
from pi.nodes.actuators.servo_test import Servo
from pi.nodes.controllers.controller_test import Controller
myController = Controller()
myServo = Servo()
print myController.ID, myServo.ID
""" controller_test.py """
class Controller():
def __init__(self, id="controller"):
self.ID = id
""" servo_test.py """
class Servo():
def __init__(self, id="servo"):
self.ID = id
If I run robot_test.py, I get the expected printout:
controller servo
However, now comes the twist. In reality, the servo_test.py module depends on controller_test.py by way of robot_test.py. This is because my servo definitions require an already-instantiated controller object before they themselves can be instantiated. But I'd like to keep all the initial instantiations in robot_test.py. So I tried modifying my servo_test.py script as follows:
""" servo_test.py """
from pi.nodes.robots.robot_test import myController
class Servo():
def __init__(self, id="servo"):
self.ID = id
print myController.ID
Of course, I could sense that the circularity was going to cause problems and sure enough, when I now try to run robot_test.py I get the error:
ImportError: Cannot import name Servo
which in turn is caused by servo_test.py returning the error:
ImportError: Cannot import name myController
In C# I would define myController and myServo as static objects in robot_test.py and then I could use them in other classes. Is there anyway to do the same in Python? One workaround I have found is to pass the myController object to the Servo class as an argument, but I was hoping to avoid having to do this.
Thanks!
| [
"\nOne workaround I have found is to pass\n the myController object to the Servo\n class as an argument, but I was hoping\n to avoid having to do this.\n\nWhy ever would you want to avoid it? It's a classic case of a crucial Design Pattern (maybe the most important one that wasn't in the original Gang of Four m... | [
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003149796_python.txt |
Q:
Python-dependency, windows (CMake)
I have a large, crossplatform, python-dependent project, which is built by CMake.
In linux, python is either preinstalled or easily retrived by shell script. But on windows build, i have to install python manually from .msi before running CMake. Is there any good workaround using cmake scripts?
PS All other external dependencies are downloaded from dedicated FTP server.
A:
Python doesn't really have to be installed to function properly. For my own CMake based projects on Windows, I just use a .zip file containing the entire python tree. All you need to do is extract it to a temporary directory, add it to your path, and set your PYTHONHOME/PYTHONPATH environment variables. Once that's done, you have a fully operational Python interpreter at your disposal. About the only 'gotcha' on Windows is to make sure you remember to copy the Python DLL out of C:\Windows\system32 into the top-level Python directory prior to creating the .zip.
| Python-dependency, windows (CMake) | I have a large, crossplatform, python-dependent project, which is built by CMake.
In linux, python is either preinstalled or easily retrived by shell script. But on windows build, i have to install python manually from .msi before running CMake. Is there any good workaround using cmake scripts?
PS All other external dependencies are downloaded from dedicated FTP server.
| [
"Python doesn't really have to be installed to function properly. For my own CMake based projects on Windows, I just use a .zip file containing the entire python tree. All you need to do is extract it to a temporary directory, add it to your path, and set your PYTHONHOME/PYTHONPATH environment variables. Once that'... | [
2
] | [] | [] | [
"c++",
"cmake",
"installation",
"python"
] | stackoverflow_0003147754_c++_cmake_installation_python.txt |
Q:
web2py: how to enable "request_reset_password" function?
I'm new to web2py but eager to learn it fast.
I try to enable "request_reset_passwor" function but every time I enter this page:
http://127.0.0.1:8000/project/default/user/request_reset_password
I receive message that the function is disabled.
Can you please tell me what should I do and where to get it working?
Thank you in advance.
A:
I think you need to set up your mail server in db.py first...
| web2py: how to enable "request_reset_password" function? | I'm new to web2py but eager to learn it fast.
I try to enable "request_reset_passwor" function but every time I enter this page:
http://127.0.0.1:8000/project/default/user/request_reset_password
I receive message that the function is disabled.
Can you please tell me what should I do and where to get it working?
Thank you in advance.
| [
"I think you need to set up your mail server in db.py first...\n"
] | [
1
] | [] | [] | [
"frameworks",
"python",
"web2py"
] | stackoverflow_0003121586_frameworks_python_web2py.txt |
Q:
How to parse the "" using feedparser?
The rss file is shown as below, i want to get the content in section media:group . I check the document of feedparser, but it seems not mention this. How to do it? Any help is appreciated.
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:ymusic="http://music.yahoo.com/rss/1.0/ymusic/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel>
<title>XYZ InfoX: Special hello </title>
<link>http://www1.XYZInfoX.com/learninghello/home</link>
<description>hello</description>
<language>en</language> <copyright />
<pubDate>Wed, 17 Mar 2010 08:50:06 GMT</pubDate>
<dc:creator />
<dc:date>2010-03-17T08:50:06Z</dc:date>
<dc:language>en</dc:language> <dc:rights />
<image>
<title>Voice of America</title>
<link>http://www1.XYZInfoX.com/learninghello</link>
<url>http://media.XYZInfoX.com/designimages/XYZRSSIcon.gif</url>
</image>
<item>
<title>Who Were the Deadliest Gunmen of the Wild West?</title>
<link>http://www1.XYZInfoX.com/learninghello/home/Deadliest-Gunmen-of-the-Wild-West-87826807.html</link>
<description> The story of two of them: "Killin'" Jim Miller was an outlaw, "Texas" John Slaughter was a lawman | EXPLORATIONS </description>
<pubDate>Wed, 17 Mar 2010 00:38:48 GMT</pubDate>
<guid isPermaLink="false">87826807</guid>
<dc:creator></dc:creator>
<dc:date>2010-03-17T00:38:48Z</dc:date>
<media:group>
<media:content url="http://media.XYZInfoX.com/images/archives_peace_comm_480_16mar_se.jpg" medium="image" isDefault="true" height="300" width="480" />
<media:content url="http://media.XYZInfoX.com/images/archives_peace_comm_230_16mar_se_edited-1.jpg" medium="image" isDefault="false" height="230" width="230" />
<media:content url="http://media.XYZInfoX.com/images/tex_trans_lawmans_230_16mar10_se.jpg" medium="image" isDefault="false" height="230" width="230" />
<media:content url="http://www.XYZInfoX.com/MediaAssets2/learninghello/dalet/se-exp-outlaws-part2-17mar2010.Mp3" type="audio/mpeg" medium="audio" isDefault="false" />
</media:group>
</item>
A:
feedparser 4.1 as available from PyPi has this bug.
the solution for me was to get the latest feedparser.py (4.2 pre) from the repository.
svn checkout http://feedparser.googlecode.com/svn/trunk/ feedparser-readonly
cd feedparser-readonly
python setup.py install
now you can access all mrss items
>>> import feedparser # the new version!
>>> d = feedparser.parse(MY_XML_URL)
>>> for content in d.entries[0].media_content: print content['url']
should do the job for you
A:
You can parse the feed using
feed = feedparser.parse(your_feeds_url)
and then access your xml elements using either python's attribute access or dictionary-like access on feed and its subelements. The former method won't work for an element name like media:content, so use the latter method.
The rest should become clear after studying the examples at http://www.feedparser.org
| How to parse the "" using feedparser? | The rss file is shown as below, i want to get the content in section media:group . I check the document of feedparser, but it seems not mention this. How to do it? Any help is appreciated.
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:ymusic="http://music.yahoo.com/rss/1.0/ymusic/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel>
<title>XYZ InfoX: Special hello </title>
<link>http://www1.XYZInfoX.com/learninghello/home</link>
<description>hello</description>
<language>en</language> <copyright />
<pubDate>Wed, 17 Mar 2010 08:50:06 GMT</pubDate>
<dc:creator />
<dc:date>2010-03-17T08:50:06Z</dc:date>
<dc:language>en</dc:language> <dc:rights />
<image>
<title>Voice of America</title>
<link>http://www1.XYZInfoX.com/learninghello</link>
<url>http://media.XYZInfoX.com/designimages/XYZRSSIcon.gif</url>
</image>
<item>
<title>Who Were the Deadliest Gunmen of the Wild West?</title>
<link>http://www1.XYZInfoX.com/learninghello/home/Deadliest-Gunmen-of-the-Wild-West-87826807.html</link>
<description> The story of two of them: "Killin'" Jim Miller was an outlaw, "Texas" John Slaughter was a lawman | EXPLORATIONS </description>
<pubDate>Wed, 17 Mar 2010 00:38:48 GMT</pubDate>
<guid isPermaLink="false">87826807</guid>
<dc:creator></dc:creator>
<dc:date>2010-03-17T00:38:48Z</dc:date>
<media:group>
<media:content url="http://media.XYZInfoX.com/images/archives_peace_comm_480_16mar_se.jpg" medium="image" isDefault="true" height="300" width="480" />
<media:content url="http://media.XYZInfoX.com/images/archives_peace_comm_230_16mar_se_edited-1.jpg" medium="image" isDefault="false" height="230" width="230" />
<media:content url="http://media.XYZInfoX.com/images/tex_trans_lawmans_230_16mar10_se.jpg" medium="image" isDefault="false" height="230" width="230" />
<media:content url="http://www.XYZInfoX.com/MediaAssets2/learninghello/dalet/se-exp-outlaws-part2-17mar2010.Mp3" type="audio/mpeg" medium="audio" isDefault="false" />
</media:group>
</item>
| [
"feedparser 4.1 as available from PyPi has this bug.\nthe solution for me was to get the latest feedparser.py (4.2 pre) from the repository.\nsvn checkout http://feedparser.googlecode.com/svn/trunk/ feedparser-readonly\ncd feedparser-readonly\npython setup.py install\n\nnow you can access all mrss items\n>>> import... | [
6,
0
] | [] | [] | [
"feedparser",
"python",
"rss"
] | stackoverflow_0002461853_feedparser_python_rss.txt |
Q:
py2exe not making exe?
I am following the tutorial for py2exe from this site http://www.py2exe.org/index.cgi/Tutorial
this is the setup code:
from distutils.core import setup
import py2exe
setup(console=['script.py'])
when I type in cmd:
python setup.py install
I get this:
running install
running build
my script works fine and I even tried it for simple scripts such as
print "hello world"
I was able to use py2exe before without any problems but for some reason it stop working for me. I even tried to reinstall the module but it still won't do anything. Any idea's from those brilliant minds on stack overflow?
A:
To build an exe, the command is:
python setup.py py2exe
| py2exe not making exe? | I am following the tutorial for py2exe from this site http://www.py2exe.org/index.cgi/Tutorial
this is the setup code:
from distutils.core import setup
import py2exe
setup(console=['script.py'])
when I type in cmd:
python setup.py install
I get this:
running install
running build
my script works fine and I even tried it for simple scripts such as
print "hello world"
I was able to use py2exe before without any problems but for some reason it stop working for me. I even tried to reinstall the module but it still won't do anything. Any idea's from those brilliant minds on stack overflow?
| [
"To build an exe, the command is:\npython setup.py py2exe\n\n"
] | [
3
] | [] | [] | [
"py2exe",
"python"
] | stackoverflow_0003150593_py2exe_python.txt |
Q:
Python code refactoring question. Applying functions to multiple elements
I have code that looks something like this:
self.ui.foo.setEnabled(False)
self.ui.bar.setEnabled(False)
self.ui.item.setEnabled(False)
self.ui.item2.setEnabled(False)
self.ui.item3.setEnabled(False)
And I would like to turn it into something like this:
items = [foo,bar,item,item2,item3]
for elm in items:
self.ui.elm.setEnabled(False)
But obviously just having the variables in the list with out the 'self.ui' part is invalid, and I would rather not type out 'self.ui' for every element in the list, because that really isn't to much better. How could I rewrite my first code to make it something like what I'm talking about?
A:
Grab the object to have the function called on it by its attribute name using the built-in getattr function:
items = ['foo', 'bar', 'item', 'item2', 'item3']
for elm in items:
getattr(self.ui, elm).setEnabled(False)
| Python code refactoring question. Applying functions to multiple elements | I have code that looks something like this:
self.ui.foo.setEnabled(False)
self.ui.bar.setEnabled(False)
self.ui.item.setEnabled(False)
self.ui.item2.setEnabled(False)
self.ui.item3.setEnabled(False)
And I would like to turn it into something like this:
items = [foo,bar,item,item2,item3]
for elm in items:
self.ui.elm.setEnabled(False)
But obviously just having the variables in the list with out the 'self.ui' part is invalid, and I would rather not type out 'self.ui' for every element in the list, because that really isn't to much better. How could I rewrite my first code to make it something like what I'm talking about?
| [
"Grab the object to have the function called on it by its attribute name using the built-in getattr function:\nitems = ['foo', 'bar', 'item', 'item2', 'item3']\nfor elm in items:\n getattr(self.ui, elm).setEnabled(False)\n\n"
] | [
4
] | [
"You could try something like:\nitems = [foo,bar,item,item2,item3]\nui = self.ui\nfor elm in items:\n ui.elm.setEnabled(False)\n\n"
] | [
-3
] | [
"list",
"python",
"refactoring"
] | stackoverflow_0003150856_list_python_refactoring.txt |
Q:
Newbie Python question about sys.argv
I'm currently going through a few tutorials to get myself up and running on Python, but I seem to hit the same problem a few times. The tutorial I'm currently following is Aloha.py in Introduction to Simulation by Norm Matloff.
The problem I'm hitting seems to be in the following code:
import random, sys
class node: # one object of this class models one network node
# some class variables
s = int(sys.argv[1]) # number of nodes
The error message when I try and run the programme is:
Traceback (most recent call last):
File "C:\Python26\Aloha.py", line 8, in <module>
class node:
File "C:\Python26\Aloha.py", line 10, in node
s = int(sys.argv[0])
ValueError: invalid literal for int() with base 10: 'C:\\Python26\\Aloha.py'
I've worked out that sys.argv[1] doesn't exist when I try and run the program, so does anyone know where I might be going wrong? Is there some way of starting the program that will set these values or is my system somehow set up incorrectly?
A:
The traceback shows that you actually have this in your code:
s = int(sys.argv[0])
so you are referring to argument 0 - the script name itself - rather than 1.
A:
sys.argv is for collecting the options given to the program on the command-line. So instead of just running the file, you'll want to run python aloha.py 5 (or whatever number you want).
(Otherwise, you could just set the number directly in the code instead of always expecting it on the command-line, as in s = 5 for example.)
A:
Also, to load in command line arguments when you run a program you'd want to run your program like this...
python Aloha.py 75
Where 75 is replaced by the number of nodes. 75 will then become argv[1].
| Newbie Python question about sys.argv | I'm currently going through a few tutorials to get myself up and running on Python, but I seem to hit the same problem a few times. The tutorial I'm currently following is Aloha.py in Introduction to Simulation by Norm Matloff.
The problem I'm hitting seems to be in the following code:
import random, sys
class node: # one object of this class models one network node
# some class variables
s = int(sys.argv[1]) # number of nodes
The error message when I try and run the programme is:
Traceback (most recent call last):
File "C:\Python26\Aloha.py", line 8, in <module>
class node:
File "C:\Python26\Aloha.py", line 10, in node
s = int(sys.argv[0])
ValueError: invalid literal for int() with base 10: 'C:\\Python26\\Aloha.py'
I've worked out that sys.argv[1] doesn't exist when I try and run the program, so does anyone know where I might be going wrong? Is there some way of starting the program that will set these values or is my system somehow set up incorrectly?
| [
"The traceback shows that you actually have this in your code:\ns = int(sys.argv[0])\n\nso you are referring to argument 0 - the script name itself - rather than 1.\n",
"sys.argv is for collecting the options given to the program on the command-line. So instead of just running the file, you'll want to run python ... | [
4,
3,
1
] | [
"try \ns = int(sys.argv[-1])\n\n"
] | [
-1
] | [
"python"
] | stackoverflow_0003151019_python.txt |
Q:
Netbeans + sqlite3 = Fail?
I've decided to give Python a try on Netbeans. The problem so far is when try to run program I know works, i.e. if I ran it through the terminal. For the project I selected the correct Python version (2.6.5). And received the following error:
Traceback (most recent call last): File
"/Users/XXX/NetBeansProjects/NewPythonProject3/src/newpythonproject3.py",
line 4, in
import sqlite3 ImportError: No module named sqlite3
A:
Search for PYTHONPATH. You probably have different settings in your OS and Netbeans.
| Netbeans + sqlite3 = Fail? | I've decided to give Python a try on Netbeans. The problem so far is when try to run program I know works, i.e. if I ran it through the terminal. For the project I selected the correct Python version (2.6.5). And received the following error:
Traceback (most recent call last): File
"/Users/XXX/NetBeansProjects/NewPythonProject3/src/newpythonproject3.py",
line 4, in
import sqlite3 ImportError: No module named sqlite3
| [
"Search for PYTHONPATH. You probably have different settings in your OS and Netbeans.\n"
] | [
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003149370_python_sqlite.txt |
Q:
Python: Are class attributes equivalent to local variables when inside a method?
In python, I know that looking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:
a = 4
def function()
for x in range(10000):
<do something with 'a'>
Is slower than
def function()
a = 4
for x in range(10000):
<do something with 'a'>
So, when I look at a class definition, with an attribute and a method:
class Classy(object):
def __init__(self, attribute1):
self.attribute1 = attribute1
self.attribute2 = 4
def method(self):
for x in range(10000):
<do something with self.attribute1 and self.attribute2>
Is my use of self.attribute more like my first or second function? What about if I sub class Classy, and try to access attribute2 from a method in my sub class?
A:
Locally scoped variables are fast because the interpreter doesn't need to do a dictionary lookup. It knows at compile-time exactly how many local variables there will be and it creates instructions to access them as an array.
Member attributes require a dictionary lookup, so they execute similar to your first example using globally scoped variables.
For speed, you can do something like:
attribute1 = self.attribute1
# do stuff with attribute1
which shadows attribute1 in a local variable, so only a single dictionary lookup is needed. I wouldn't bother unless I'd done some profiling indicating that a method was a bottleneck, though.
| Python: Are class attributes equivalent to local variables when inside a method? | In python, I know that looking up a locally scoped variable is significantly faster than looking up a global scoped variable. So:
a = 4
def function()
for x in range(10000):
<do something with 'a'>
Is slower than
def function()
a = 4
for x in range(10000):
<do something with 'a'>
So, when I look at a class definition, with an attribute and a method:
class Classy(object):
def __init__(self, attribute1):
self.attribute1 = attribute1
self.attribute2 = 4
def method(self):
for x in range(10000):
<do something with self.attribute1 and self.attribute2>
Is my use of self.attribute more like my first or second function? What about if I sub class Classy, and try to access attribute2 from a method in my sub class?
| [
"Locally scoped variables are fast because the interpreter doesn't need to do a dictionary lookup. It knows at compile-time exactly how many local variables there will be and it creates instructions to access them as an array.\nMember attributes require a dictionary lookup, so they execute similar to your first ex... | [
4
] | [] | [] | [
"attributes",
"class",
"methods",
"python"
] | stackoverflow_0003151068_attributes_class_methods_python.txt |
Q:
Retrieving a lot url addresses
Edit: Just for clarification I am using python, and would like to do this within python.
I am in the middle of collecting data for a research project at our university. Basically I need to scrape a lot of information from a website that monitors the European Parliament. Here is an example of how the url of one site looks like:
http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0190&language=EN
The numbers after the reference part of the address refers to:
A7 = Parliament in session (previous parliaments are A6 etc.),
2010 = year,
0190 = number of the file.
What I want to do is to create a variable that has all the urls for different parliaments, so I can loop over this variable and scrape the information from the websites.
P.S: I have tried this:
number = range(1,190,1)
for i in number:
search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-" + str(number[i]) +"&language=EN"
results = search_url
print results
but this gives me the following error:
Traceback (most recent call last):
File "", line 7, in
IndexError: list index out of range
A:
Can you use python and wget ? Loop through the sessions that exist, and create a string to give to wget? Or is that overkill?
A:
If I understand correctly, you just want to be able to loop over the parliments?
i.e. you want A7, A6, A5...?
If that's what you want a simple loop could handle it:
for p in xrange(7,0, -1):
parliment = "A%d" % p
print p
for the other values similar loops would work just as well:
for year in xrange(2010, 2000, -1):
print year
for filenum in xrange(100,200):
fnum = "%.4d" % filenum
print fnum
You could easily nest your loops in the proper order to generate the combination(s) you need. HTH!
Edit:
String formatting is super useful, and here's how you can do it with your example:
# Just create a string with the format specifier in it: %.4d - a [d]ecimal with a
# precision/width of 4 - so instead of 3 you'll get 0003
search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-%.4d&language=EN"
# This creates a Python generator. They're super powerful and fun to use,
# and you can iterate over them, just like a collection.
# 1 is the default step, so no need for it in this case
for number in xrange(1,190):
print search_url % number
String formatting takes a string with a variety of specifiers - you'll recognize them because they have % in them - followed by % and a tuple containing the arguments to the format string.
If you want to add the year and parliment, change the string to this:
search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A%d-%d-%.4d&language=EN"
where the important changes are here:
reference=A%d-%d-%.4d&language=EN
That means you'll need to pass 3 decimals like so:
print search_url % (parliment, year, number)
A:
Sorry I can't give this as a comment, but I don't have a high enough score yet.
Looking at the code you quoted in the comment above, your problem is you are trying to add a string and an integer. While some languages will do on the fly conversion (useful when it works but confusing when it doesn't), you have to explicitly convert it with str().
It should be something like:
"http://firstpartofurl" + str(number[i]) + "restofurl"
or, you can use string formatting (using % etc. as Wayne's answer).
A:
Use selenium. Since it controls uses a real browser, it can handle sites using complex javascript. Many language bindings are available, including python.
| Retrieving a lot url addresses | Edit: Just for clarification I am using python, and would like to do this within python.
I am in the middle of collecting data for a research project at our university. Basically I need to scrape a lot of information from a website that monitors the European Parliament. Here is an example of how the url of one site looks like:
http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-0190&language=EN
The numbers after the reference part of the address refers to:
A7 = Parliament in session (previous parliaments are A6 etc.),
2010 = year,
0190 = number of the file.
What I want to do is to create a variable that has all the urls for different parliaments, so I can loop over this variable and scrape the information from the websites.
P.S: I have tried this:
number = range(1,190,1)
for i in number:
search_url = "http://www.europarl.europa.eu/sides/getDoc.do?type=REPORT&mode=XML&reference=A7-2010-" + str(number[i]) +"&language=EN"
results = search_url
print results
but this gives me the following error:
Traceback (most recent call last):
File "", line 7, in
IndexError: list index out of range
| [
"Can you use python and wget ? Loop through the sessions that exist, and create a string to give to wget? Or is that overkill?\n",
"If I understand correctly, you just want to be able to loop over the parliments?\ni.e. you want A7, A6, A5...? \nIf that's what you want a simple loop could handle it:\nfor p in xr... | [
1,
1,
1,
0
] | [] | [] | [
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0003150621_python_screen_scraping_web_scraping.txt |
Q:
App Engine template values not showing
I'm trying to read a line from a static file and insert it into a template in Google App engine using the Webapp framework. However, the line does not render, not matter what I try. Is there something that I'm overlooking?
main.py:
def get(self):
...
question = randomLine("data/questions.csv")
data = question.split(',')[0]
template_values = {
'data': data,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
index.html:
...
<div id="question">
<p>{{ data }}</p>
</div>
...
A:
Never mind, I solved it. I had renamed main.py, but I didn't update it in app.yaml so even though I had cleared my cache and the datastore, it was still somehow loading what was left. Doh!
| App Engine template values not showing | I'm trying to read a line from a static file and insert it into a template in Google App engine using the Webapp framework. However, the line does not render, not matter what I try. Is there something that I'm overlooking?
main.py:
def get(self):
...
question = randomLine("data/questions.csv")
data = question.split(',')[0]
template_values = {
'data': data,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
index.html:
...
<div id="question">
<p>{{ data }}</p>
</div>
...
| [
"Never mind, I solved it. I had renamed main.py, but I didn't update it in app.yaml so even though I had cleared my cache and the datastore, it was still somehow loading what was left. Doh!\n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python",
"templates"
] | stackoverflow_0003151425_google_app_engine_python_templates.txt |
Q:
library for representing 3D polyhedra
Are there any libraries that provide 3D polyhedra, and support calculating the intersection of two polyhedra?
If it makes a difference, the polyhedra I want to model do not have 'holes' in them.
The focus would be on correctness first and speed a close second!
Ideally this library would:
have existing tidy python bindings
be free-standing or have reasonable and small dependencies
support calculating the outline of the polyhedron when view from any given angle
A:
CGAL offers rather more than you're asking for, but does in particular include polyhedra and "boolean"-like operations on them (I'm not sure about "view from any angle" as a primitive, though -- as I recall it wasn't there when I last used it, but that was a while ago -- you may have to iterate projecting the hedges on the appropriate plane).
The Python bindings are here and I believe the only "big" dependency is Boost Python (used for the bindings).
| library for representing 3D polyhedra | Are there any libraries that provide 3D polyhedra, and support calculating the intersection of two polyhedra?
If it makes a difference, the polyhedra I want to model do not have 'holes' in them.
The focus would be on correctness first and speed a close second!
Ideally this library would:
have existing tidy python bindings
be free-standing or have reasonable and small dependencies
support calculating the outline of the polyhedron when view from any given angle
| [
"CGAL offers rather more than you're asking for, but does in particular include polyhedra and \"boolean\"-like operations on them (I'm not sure about \"view from any angle\" as a primitive, though -- as I recall it wasn't there when I last used it, but that was a while ago -- you may have to iterate projecting the ... | [
5
] | [] | [] | [
"3d",
"polygon",
"python"
] | stackoverflow_0003151524_3d_polygon_python.txt |
Q:
python: how to find \r\n\r\n in one single search
I have to split the file content based on first occurrence of \r\n\r\n
I need flexibility such a way that the lines can just ends with \r\n\r\n or \n\n.
How to split the text?
Example added:
\===================FILE BEGIN==========================================
name: about
title: About
publish: True
order: -1
\r\n
\r\n
**example.com** is a example website provides the latest examples in organized way.
Blah blah blah....
Blah blah blah....
Blah blah blah....
\===================File END==========================================
First portion is my header(in yaml format) used for file identity and second portion is markdown text.
A:
import re
linend = re.compile(r'\r\n\r\n|\n\n')
s = 'an example\n\nstring\n\nhere'
print linend.split(s, 1)
s = 'another\r\n\r\nexample\r\n\r\nhere'
print linend.split(s, 1)
prints:
['an example', 'string\n\nhere']
['another', 'example\r\n\r\nhere']
as requested.
A:
The regex pattern "\r\n\r\n|\n\n" should work. Simply use re.split or Regex.split and set maxsplit=1.
| python: how to find \r\n\r\n in one single search | I have to split the file content based on first occurrence of \r\n\r\n
I need flexibility such a way that the lines can just ends with \r\n\r\n or \n\n.
How to split the text?
Example added:
\===================FILE BEGIN==========================================
name: about
title: About
publish: True
order: -1
\r\n
\r\n
**example.com** is a example website provides the latest examples in organized way.
Blah blah blah....
Blah blah blah....
Blah blah blah....
\===================File END==========================================
First portion is my header(in yaml format) used for file identity and second portion is markdown text.
| [
"import re\n\nlinend = re.compile(r'\\r\\n\\r\\n|\\n\\n')\ns = 'an example\\n\\nstring\\n\\nhere'\nprint linend.split(s, 1)\ns = 'another\\r\\n\\r\\nexample\\r\\n\\r\\nhere'\nprint linend.split(s, 1)\n\nprints:\n['an example', 'string\\n\\nhere']\n['another', 'example\\r\\n\\r\\nhere']\n\nas requested.\n",
"The r... | [
2,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0003151842_python_regex_string.txt |
Q:
How to decode a Google App Engine entity Key path str in Python?
In Google App Engine, an entity has a Key. A key can be made from a path, in which case str(key) is an opaque hex string. Example:
from google.appengine.ext import db
foo = db.Key.from_path(u'foo', u'bar', _app=u'baz')
print foo
gives
agNiYXpyDAsSA2ZvbyIDYmFyDA
if you set up the right paths to run the code.
So, how can one take the hex string and get the path back? I thought the answer would be in Key or entity group docs, but I can't see it.
A:
from google.appengine.ext import db
k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')
_app = k.app()
path = []
while k is not None:
path.append(k.id_or_name())
path.append(k.kind())
k = k.parent()
path.reverse()
print 'app=%r, path=%r' % (_app, path)
when run in a Development Console, this outputs:
app=u'baz', path=[u'foo', u'bar']
as requested. A shorter alternative is to use the (unfortunately, I believe, undocumented) to_path method of Key instances:
k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')
_app = k.app()
path = k.to_path()
print 'app=%r, path=%r' % (_app, path)
with the same results. But the first, longer version relies only on documented methods.
A:
Once you have the Key object (which can be created by passing that opaque identifier to the constructor), use Key.to_path() to get the path of a Key as a list. For example:
from google.appengine.ext import db
opaque_id = 'agNiYXpyDAsSA2ZvbyIDYmFyDA'
path = db.Key(opaque_id).to_path()
| How to decode a Google App Engine entity Key path str in Python? | In Google App Engine, an entity has a Key. A key can be made from a path, in which case str(key) is an opaque hex string. Example:
from google.appengine.ext import db
foo = db.Key.from_path(u'foo', u'bar', _app=u'baz')
print foo
gives
agNiYXpyDAsSA2ZvbyIDYmFyDA
if you set up the right paths to run the code.
So, how can one take the hex string and get the path back? I thought the answer would be in Key or entity group docs, but I can't see it.
| [
"from google.appengine.ext import db\n\nk = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')\n_app = k.app()\npath = []\nwhile k is not None:\n path.append(k.id_or_name())\n path.append(k.kind())\n k = k.parent()\npath.reverse()\nprint 'app=%r, path=%r' % (_app, path)\n\nwhen run in a Development Console, this outputs:\napp... | [
7,
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003151379_google_app_engine_python.txt |
Q:
Python + SQLAlchemy problem: The transaction is inactive due to a rollback in a subtransaction
I have a problem with Python + SQLAlchemy.
When something goes wrong (in my case it is an integrity error, due to a race condition) and the database error is raised, all following requests result in the error being raised:
InvalidRequestError: The transaction is inactive due to a rollback in a subtransaction. Issue rollback() to cancel the transaction.
While I can prevent this original error (race condition) from happening, but I would like a more robust solution, I want to prevent a single error from crashing the entire application.
What is the best way to do this? Is there a way to tell Python to rollback the failed transaction?
A:
The easiest thing is to make sure you are using a new SQLAlchemy Session when you start work in your controller. in /project/lib/base.py, add a method for BaseController:
def __before__(self):
model.Session.close()
Session.close() will clear out the session and close any open transactions if there are any. You want to make sure that each time you use a session it's cleared when you're done with your work in the controller. Doing it at the start of the controller's handling of the request will make sure that it's always cleared, even if the thread's previous request had an exception and there is a rollback waiting.
A:
Do you use in your controllers yoursapp.lib.base.BaseController?
You can look at
Handle mysql restart in SQLAlchemy
Also you can catch SA exception in BaseController try-finally block and do session rollback()
In BaseController SA Session removed http://www.sqlalchemy.org/docs/05/session.html#lifespan-of-a-contextual-session
| Python + SQLAlchemy problem: The transaction is inactive due to a rollback in a subtransaction | I have a problem with Python + SQLAlchemy.
When something goes wrong (in my case it is an integrity error, due to a race condition) and the database error is raised, all following requests result in the error being raised:
InvalidRequestError: The transaction is inactive due to a rollback in a subtransaction. Issue rollback() to cancel the transaction.
While I can prevent this original error (race condition) from happening, but I would like a more robust solution, I want to prevent a single error from crashing the entire application.
What is the best way to do this? Is there a way to tell Python to rollback the failed transaction?
| [
"The easiest thing is to make sure you are using a new SQLAlchemy Session when you start work in your controller. in /project/lib/base.py, add a method for BaseController:\ndef __before__(self):\n model.Session.close()\n\nSession.close() will clear out the session and close any open transactions if there are an... | [
3,
0
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0003139211_pylons_python_sqlalchemy.txt |
Q:
Trying to match '#' in a text
I'm trying to match a "#" followed by letters if and only if it's preceded by newline, whitespace or is the first character in a string. The first two I've done, but I'm having a hard time matching if it's the first character in a string. I'm trying to find a use for '\A', but it doesn't work to just add it to the class containing newline and whitespace. What have I missed?
The regular expression I've come up with so far is:
from re import findall, escape
from string import punctuation, whitespace
NEWLINE = """\r\n?|\n"""
INVALID_TAG_CHARACTERS = escape(punctuation.replace('-', '').replace('_', '') + whitespace)
VALID_TAGS = r'[\s%s]+#[^%s]+' % (NEWLINE, INVALID_TAG_CHARACTERS)
tags = findall(VALID_TAGS, text)
A:
I think this is what you're looking for:
result = re.findall("(?:^|\s)(#[a-zA-Z]+)", text, re.MULTILINE)
The (?:^|\s) is a set of non-grouping parentheses (we don't want this part in our results). With the multiline flag, it will match the beginning of the string, or a preceding newline or whitespace. The next group is your 'tag,' I believe. If it's other than letters following the #, you'll have to fiddle with that second group.
A:
Turn on the multi-line flag, so ^ matches the position after a newline, then just use:
re.compile(r"(?m)^\s*#") # includes the flag for multi-line
Or
re.compile(r"(?m)^\s*#.*$")
to get the full line (with dot matching newline mode disabled).
For the "first character in string", that depends on what a string is defined as - you may need to use a full parser for this, rather than a single regex.
| Trying to match '#' in a text | I'm trying to match a "#" followed by letters if and only if it's preceded by newline, whitespace or is the first character in a string. The first two I've done, but I'm having a hard time matching if it's the first character in a string. I'm trying to find a use for '\A', but it doesn't work to just add it to the class containing newline and whitespace. What have I missed?
The regular expression I've come up with so far is:
from re import findall, escape
from string import punctuation, whitespace
NEWLINE = """\r\n?|\n"""
INVALID_TAG_CHARACTERS = escape(punctuation.replace('-', '').replace('_', '') + whitespace)
VALID_TAGS = r'[\s%s]+#[^%s]+' % (NEWLINE, INVALID_TAG_CHARACTERS)
tags = findall(VALID_TAGS, text)
| [
"I think this is what you're looking for:\nresult = re.findall(\"(?:^|\\s)(#[a-zA-Z]+)\", text, re.MULTILINE)\n\nThe (?:^|\\s) is a set of non-grouping parentheses (we don't want this part in our results). With the multiline flag, it will match the beginning of the string, or a preceding newline or whitespace. The ... | [
2,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003150899_python_regex.txt |
Q:
to get number of frames between a time range?
I want to find the number of frames in wav file between certain time range that is generally using the function wave.getnframes we can get the number of frames in the complete wave file but here i want to know how to find the number frames between a certain time range such number of frames between 5.43 sec to 5.81 secs..
how can we do this??
please suggest ways to do this...
thanks in advance
A:
frame rate is equal to the number of frames per a second
so 5.81 minus 5.43 equals 0.38 seconds
number of frames is equal to 0.38 * wave.getframerate()
Like so:
import wave
start_time = 5.43
stop_time = 5.81
time_period = stop_time - start_time
wav = wave.open('test.wav')
time_period_frames = time_period * wav.getnframes()
Sometimes it is easier to figure these things out by starting a python interactive session at the command line by typing 'python' all by itself.
This is how I figured it out I created a 60 second clip. Then I divided wave.getnframes() by wave.getframerate(). The result was 60. The docs don't spell this out because it is common knowledge in multimedia. But it always pays to check twice.
| to get number of frames between a time range? | I want to find the number of frames in wav file between certain time range that is generally using the function wave.getnframes we can get the number of frames in the complete wave file but here i want to know how to find the number frames between a certain time range such number of frames between 5.43 sec to 5.81 secs..
how can we do this??
please suggest ways to do this...
thanks in advance
| [
"frame rate is equal to the number of frames per a second\nso 5.81 minus 5.43 equals 0.38 seconds\nnumber of frames is equal to 0.38 * wave.getframerate()\nLike so:\nimport wave\n\nstart_time = 5.43\nstop_time = 5.81\ntime_period = stop_time - start_time\nwav = wave.open('test.wav')\ntime_period_frames = time_perio... | [
5
] | [] | [] | [
"python",
"wav"
] | stackoverflow_0003152196_python_wav.txt |
Q:
Splitting items in a list into two and appending one of them to another list
Hey all. Trying to get a little more efficient with lists in Python but I cant seem to figure out if I can do what I want or even if it is worth figuring out.
stream is a list. Each item in the list is something like :
10,123400FFFE001DB9AA
I am trying to get to the second part of each item after the comma so I run through the list splitting each one and storing it in temp . I them append temp[1) to the other list called incoming_data.
I would like to combine the line that splits and saves to temp and appends to the incoming_data list into one line, something like:
incoming_data.append(item.split(','))
I know the above syntax is totally incorrect but I hope it gets the point across. Here is my current code.
Other critiques welcome as usual. Thanks!
#init the final list
incoming_data = list()
#iterate over each item in the list
for item in stream:
#clear the temp variable for next time
temp = ''
#we sometimes get blank items in the stream list so check first
if item <> '':
#split each item in the stream list using the comma as delimiter
temp = item.split(',')
#append to the final data lis
incoming_data.append(temp[1])
A:
incoming_data = [item.split(",")[1] for item in stream if item]
The if item discards the blank lines in stream.
A:
You can use Python's handy-dandy list comprehensions to do this in one line:
incoming_data = [ item.split(',')[1] for item in stream ]
A:
Actually, you could do incoming_data.append(item.split(',')[1]). If you really wanted you could combine the whole shebang into a one liner using a list comprehension (mine is now corrected for the blank line thanks to Richard):
incoming_data = [item.split(',')[0] for item in stream if item]
Though if you're actually streaming something you should look at generators(PDF) - they're absolutely amazing.
| Splitting items in a list into two and appending one of them to another list | Hey all. Trying to get a little more efficient with lists in Python but I cant seem to figure out if I can do what I want or even if it is worth figuring out.
stream is a list. Each item in the list is something like :
10,123400FFFE001DB9AA
I am trying to get to the second part of each item after the comma so I run through the list splitting each one and storing it in temp . I them append temp[1) to the other list called incoming_data.
I would like to combine the line that splits and saves to temp and appends to the incoming_data list into one line, something like:
incoming_data.append(item.split(','))
I know the above syntax is totally incorrect but I hope it gets the point across. Here is my current code.
Other critiques welcome as usual. Thanks!
#init the final list
incoming_data = list()
#iterate over each item in the list
for item in stream:
#clear the temp variable for next time
temp = ''
#we sometimes get blank items in the stream list so check first
if item <> '':
#split each item in the stream list using the comma as delimiter
temp = item.split(',')
#append to the final data lis
incoming_data.append(temp[1])
| [
"incoming_data = [item.split(\",\")[1] for item in stream if item]\n\nThe if item discards the blank lines in stream.\n",
"You can use Python's handy-dandy list comprehensions to do this in one line:\nincoming_data = [ item.split(',')[1] for item in stream ]\n\n",
"Actually, you could do incoming_data.append(it... | [
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003152815_python.txt |
Q:
python refactoring (similar methods in class)
Python refactoring
Both the add and sub are very similar. How does one re-factor code like this? The logic is basically inverse of each other.
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def add( self, p ):
x = self.x + p.x
y = self.y + p.y
return point( x, y )
def sub( self, p ):
x = self.x - p.x
y = self.y - p.y
return point( x, y )
A:
First, standard practice is to capitalize classes (so Point, not point). I'd make use of the __add__ and __sub__ (and possibly __iadd__ and __isub__) methods, as well. A first cut might look like this:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
I know you're looking to pull the logic out into a single method, something like:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def _adjust(self, x, y):
return Point(self.x + x, self.y + y)
def __add__(self, p):
return self._adjust(p.x, p.y)
def __sub__(self, p):
return self._adjust(-p.x, -p.y)
... but that seems more complicated, without much gain.
A:
What about that:
import operator
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def _do_op(self, op, p):
x = op(self.x, p.x)
y = op(self.y, p.y)
return point(x, y)
def add( self, p ):
return self._do_op(operator.add, p)
def sub( self, p ):
return self._do_op(operator.sub, p)
A:
Here's something you could do.
def __add__(self, p): # used this so that you can add using the + operator
x = self.x + p.x
y = self.y + p.y
return point(x, y)
def __sub__(self, p):
return self + point(-p.x, -p.y)
| python refactoring (similar methods in class) | Python refactoring
Both the add and sub are very similar. How does one re-factor code like this? The logic is basically inverse of each other.
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def add( self, p ):
x = self.x + p.x
y = self.y + p.y
return point( x, y )
def sub( self, p ):
x = self.x - p.x
y = self.y - p.y
return point( x, y )
| [
"First, standard practice is to capitalize classes (so Point, not point). I'd make use of the __add__ and __sub__ (and possibly __iadd__ and __isub__) methods, as well. A first cut might look like this:\nclass Point(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add_... | [
2,
2,
0
] | [] | [] | [
"python",
"refactoring"
] | stackoverflow_0003152820_python_refactoring.txt |
Q:
How can I change name of option in django select box
I got 2 models
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
class Post(models.Model):
......
category = models.ForeginKey(Category)
........
And when I create a form, in select box i got options "Category object", but i would like to display name of category, i am sure it's basic, just missed it in doc's :C
A:
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
def __unicode__(self):
return self.name
| How can I change name of option in django select box | I got 2 models
class Category(models.Model):
name = models.CharField(max_length=30, unique=True)
class Post(models.Model):
......
category = models.ForeginKey(Category)
........
And when I create a form, in select box i got options "Category object", but i would like to display name of category, i am sure it's basic, just missed it in doc's :C
| [
"class Category(models.Model):\n name = models.CharField(max_length=30, unique=True)\n\n def __unicode__(self):\n return self.name\n\n"
] | [
1
] | [] | [] | [
"django_forms",
"python"
] | stackoverflow_0003153092_django_forms_python.txt |
Q:
Python Class scope & lists
I'm still fairly new to Python, and my OO experience comes from Java. So I have some code I've written in Python that's acting very unusual to me, given the following code:
class MyClass():
mylist = []
mynum = 0
def __init__(self):
# populate list with some value.
self.mylist.append("Hey!")
# increment mynum.
self.mynum += 1
a = MyClass()
print a.mylist
print a.mynum
b = MyClass()
print b.mylist
print b.mynum
Running this results in the following output:
['Hey!']
1
['Hey!', 'Hey!']
1
Clearly, I would expect the class variables to result in the same exact data, and the same exact output... What I can't seem to find anywhere is what makes a list different than say a string or number, why is the list referencing the same list from the first instantiation in subsequent ones? Clearly I'm probably misunderstanding some kind of scope mechanics or list creation mechanics..
A:
tlayton's answer is part of the story, but it doesn't explain everything.
Add a
print MyClass.mynum
to become even more confused :). It will print '0'. Why? Because the line
self.mynum += 1
creates an instance variable and subsequently increases it. It doesn't increase the class variable.
The story of the mylist is different.
self.mylist.append("Hey!")
will not create a list. It expects a variable with an 'append' function to exist. Since the instance doesn't have such a variable, it ends up referring the one from the class, which does exist, since you initialized it. Just like in Java, an instance can 'implicitly' reference a class variable. A warning like 'Class fields should be referenced by the class, not by an instance' (or something like that; it's been a while since I saw it in Java) would be in order. Add a line
print MyClass.mylist
to verify this answer :).
In short: you are initializing class variables and updating instance variables. Instances can reference class variables, but some 'update' statements will automagically create the instance variables for you.
A:
What you are doing here is not just creating a class variable. In Python, variables defined in the class body result in both a class variable ("MyClass.mylist") and in an instance variable ("a.mylist"). These are separate variables, not just different names for a single variable.
However, when a variable is initialized in this way, the initial value is only evaluated once and passed around to each instance's variables. This means that, in your code, the mylist variable of each instance of MyClass are referring to a single list object.
The difference between a list and a number in this case is that, like in Java, primitive values such as numbers are copied when passed from one variable to another. This results in the behavior you see; even though the variable initialization is only evaluated once, the 0 is copied when it is passed to each instance's variable. As an object, though, the list does no such thing, so your append() calls are all coming from the same list. Try this instead:
class MyClass():
def __init__(self):
self.mylist = ["Hey"]
self.mynum = 1
This will cause the value to be evaluated separately each time an instance is created. Very much unlike Java, you don't need the class-body declarations to accompany this snippet; the assignments in the __init__() serve as all the declaration that is needed.
A:
I believe the difference is that += is an assignment (just the same as = and +), while append changes an object in-place.
mylist = []
mynum = 0
This assigns some class variables, once, at class definition time.
self.mylist.append("Hey!")
This changes the value MyClass.mylist by appending a string.
self.mynum += 1
This is the same as self.mynum = self.mynum + 1, i.e., it assigns self.mynum (instance member). Reading from self.mynum falls through to the class member since at that time there is no instance member by that name.
| Python Class scope & lists | I'm still fairly new to Python, and my OO experience comes from Java. So I have some code I've written in Python that's acting very unusual to me, given the following code:
class MyClass():
mylist = []
mynum = 0
def __init__(self):
# populate list with some value.
self.mylist.append("Hey!")
# increment mynum.
self.mynum += 1
a = MyClass()
print a.mylist
print a.mynum
b = MyClass()
print b.mylist
print b.mynum
Running this results in the following output:
['Hey!']
1
['Hey!', 'Hey!']
1
Clearly, I would expect the class variables to result in the same exact data, and the same exact output... What I can't seem to find anywhere is what makes a list different than say a string or number, why is the list referencing the same list from the first instantiation in subsequent ones? Clearly I'm probably misunderstanding some kind of scope mechanics or list creation mechanics..
| [
"tlayton's answer is part of the story, but it doesn't explain everything.\nAdd a \nprint MyClass.mynum\n\nto become even more confused :). It will print '0'. Why? Because the line\nself.mynum += 1\n\ncreates an instance variable and subsequently increases it. It doesn't increase the class variable.\nThe story of t... | [
8,
5,
5
] | [] | [] | [
"python"
] | stackoverflow_0003153017_python.txt |
Q:
Expose __main__
is this legal in python?. Seems to work ...
Thanks
# with these lines you not need global variables anymore
if __name__ == '__main__':
import __main__ as main
else:
main = __import__(os.path.basename(os.path.splitext(__file__)))
var_in_main = 0 # now any var is a global var, you can access any var from everywhere
def fun(*args, **kwargs):
self = fun
self.var_in_fun = 'I am a var into fun'
if args:
returnList = []
for request in args:
returnList.append( getattr(self, request , 'Sorry, no var named "%s" into fun.' % request ) )
if len(returnList) == 1:
return returnList[0]
else:
return returnList
elif kwargs:
for k,v in kwargs.iteritems():
reset = kwargs.get('reset', None)
if reset:
main.var_in_main = 0
if k == 'times':
for i in range(v):
fun()
setattr(self, k, v)
else: # when no args or kwars, execute.
main.var_in_main += 1
print ' -', main.var_in_main
return self
# testing
print '\nSETTING AND GETTING VARS'
print ' ', fun('var_in_fun')
print ' ', fun('var_in_fun','erroneus_var_name')
print ' ', fun('var_in_fun','erroneus_var_name')[0]
fun( new_var_in_fun = fun )
print ' ', fun( 'new_var_in_fun' )
print ' ', fun
print '\nMULTIFUNCTION'
fun()()()()
fun()
fun()()()
print '\nRESET AND THEN LOOP'
fun( reset = 1)
fun( times = 3 )
print '\nRESET AND LOOP, IN ONE SHOT'
fun( reset= 1, times = 100 )
output
SETTING AND GETTING VARS
I am a var into fun
['I am a var into fun', 'Sorry, no var named "erroneus_var_name" into fun.']
I am a var into fun
<function fun at 0x44f930>
<function fun at 0x44f930>
MULTIFUNCTION
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
RESET AND THEN LOOP
- 1
- 2
- 3
RESET AND LOOP, IN ONE SHOT
- 1
- 2
- 3
- 4
- 5
- 6
- 7
--- goes on and on -----
- 95
- 96
- 97
- 98
- 99
- 100
A:
if __name__ == '__main__':
import __main__ as main
else:
main = __import__(os.path.basename(os.path.splitext(__file__)))
This is quite a fragile approach, since it relies on relative import behavior for all modules from within a package. There is a much better solution -- faster, more concise, and more reliable:
import sys
main = sys.modules[__name__]
The weird choice of main for the name remains (I normally use something like thismodule when I use this approach) but the approach taken to bind that name is now sound.
| Expose __main__ | is this legal in python?. Seems to work ...
Thanks
# with these lines you not need global variables anymore
if __name__ == '__main__':
import __main__ as main
else:
main = __import__(os.path.basename(os.path.splitext(__file__)))
var_in_main = 0 # now any var is a global var, you can access any var from everywhere
def fun(*args, **kwargs):
self = fun
self.var_in_fun = 'I am a var into fun'
if args:
returnList = []
for request in args:
returnList.append( getattr(self, request , 'Sorry, no var named "%s" into fun.' % request ) )
if len(returnList) == 1:
return returnList[0]
else:
return returnList
elif kwargs:
for k,v in kwargs.iteritems():
reset = kwargs.get('reset', None)
if reset:
main.var_in_main = 0
if k == 'times':
for i in range(v):
fun()
setattr(self, k, v)
else: # when no args or kwars, execute.
main.var_in_main += 1
print ' -', main.var_in_main
return self
# testing
print '\nSETTING AND GETTING VARS'
print ' ', fun('var_in_fun')
print ' ', fun('var_in_fun','erroneus_var_name')
print ' ', fun('var_in_fun','erroneus_var_name')[0]
fun( new_var_in_fun = fun )
print ' ', fun( 'new_var_in_fun' )
print ' ', fun
print '\nMULTIFUNCTION'
fun()()()()
fun()
fun()()()
print '\nRESET AND THEN LOOP'
fun( reset = 1)
fun( times = 3 )
print '\nRESET AND LOOP, IN ONE SHOT'
fun( reset= 1, times = 100 )
output
SETTING AND GETTING VARS
I am a var into fun
['I am a var into fun', 'Sorry, no var named "erroneus_var_name" into fun.']
I am a var into fun
<function fun at 0x44f930>
<function fun at 0x44f930>
MULTIFUNCTION
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
RESET AND THEN LOOP
- 1
- 2
- 3
RESET AND LOOP, IN ONE SHOT
- 1
- 2
- 3
- 4
- 5
- 6
- 7
--- goes on and on -----
- 95
- 96
- 97
- 98
- 99
- 100
| [
"if __name__ == '__main__':\n import __main__ as main\nelse:\n main = __import__(os.path.basename(os.path.splitext(__file__)))\n\nThis is quite a fragile approach, since it relies on relative import behavior for all modules from within a package. There is a much better solution -- faster, more concise, and m... | [
3
] | [] | [] | [
"function",
"iterable",
"program_entry_point",
"python"
] | stackoverflow_0003153112_function_iterable_program_entry_point_python.txt |
Q:
Localhost bottleneck with python sockets
I'm sending a very large string from one application to another on localhost using sockets in python. Small strings move instantly, but large strings seem to take a while longer (I say large, but I'm talking maybe a MB or two at the very most). Enough that I have to sit and wait a few seconds after I do something in one app before it shows up in another.
What bottlenecks are involved here? As I understand it, with sockets on 127.0.0.1, all I'm really doing is moving data from one point in memory to another. So transferring even hundreds of MB at a time should move perceptually instantly on my workstation.
A:
You are still moving the data through the entire network stack, just not going out through the network interface card itself.
There may be some shortcuts taken around the network stack with localhost, but it's most likely dependent on how the stack is implemented on the system you are using. Regardless shared memory or pipes will be much faster.
Here is a high level overview: http://docs.python.org/howto/sockets.html
PS: Not sure if this will work for your case, but the multiprocessing module has a some ways of sharing data between several processes in an efficient way.
PPS: You could try using a UDP socket instead of a TCP socket. This could potentially give you better throughput and not change drastically your method of IPC.
| Localhost bottleneck with python sockets | I'm sending a very large string from one application to another on localhost using sockets in python. Small strings move instantly, but large strings seem to take a while longer (I say large, but I'm talking maybe a MB or two at the very most). Enough that I have to sit and wait a few seconds after I do something in one app before it shows up in another.
What bottlenecks are involved here? As I understand it, with sockets on 127.0.0.1, all I'm really doing is moving data from one point in memory to another. So transferring even hundreds of MB at a time should move perceptually instantly on my workstation.
| [
"You are still moving the data through the entire network stack, just not going out through the network interface card itself. \nThere may be some shortcuts taken around the network stack with localhost, but it's most likely dependent on how the stack is implemented on the system you are using. Regardless shared m... | [
3
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003153147_python_sockets.txt |
Q:
Choosing a random sample from each row of Numpy array, excluding negative numbers
I have a Numpy array that looks like
>>> a
array([[ 3. , 2. , -1. ],
[-1. , 0.1, 3. ],
[-1. , 2. , 3.5]])
I would like to select a value from each row at random, but I would like to exclude the -1 values from the random sampling.
What I do currently is:
x=[]
for i in range(a.shape[0]):
idx=numpy.where(a[i,:]>0)[0]
idxr=random.sample(idx,1)[0]
xi=a[i,idxr]
x.append(xi)
and get
>>> x
[3.0, 3.0, 2.0]
This is becoming a bit slow for large arrays and I would like to know if there is a way to conditionally select random values from the original a matrix without dealing with each row individually.
A:
I really don't think that you will find anything in Numpy that does exactly what you are asking as packaged so I've decided to offer what optimizations I could think up.
There are several things that could make this slow here. First off, numpy.where() is rather slow because it has to check every value in the sliced array (the slice is generated for each row as well) and then generate an array of values. The best thing that you could do if you plan on doing this process over and over again on the same matrix would be to sort each row. Then you would just use a binary search to find where the positive values start and just use a random number to select a value from them. Of course, you could also just store the indices where the positive values start after finding them once with binary searches.
If you don't plan on doing this process many times over, then I would recommend using Cython to speed up the numpy.where line. Cython would allow you to not need to slice the rows out and speed up the process overall.
My last suggestion is to use random.choice rather than random.sample unless you really do plan on choosing sample sizes that are larger than 1.
| Choosing a random sample from each row of Numpy array, excluding negative numbers | I have a Numpy array that looks like
>>> a
array([[ 3. , 2. , -1. ],
[-1. , 0.1, 3. ],
[-1. , 2. , 3.5]])
I would like to select a value from each row at random, but I would like to exclude the -1 values from the random sampling.
What I do currently is:
x=[]
for i in range(a.shape[0]):
idx=numpy.where(a[i,:]>0)[0]
idxr=random.sample(idx,1)[0]
xi=a[i,idxr]
x.append(xi)
and get
>>> x
[3.0, 3.0, 2.0]
This is becoming a bit slow for large arrays and I would like to know if there is a way to conditionally select random values from the original a matrix without dealing with each row individually.
| [
"I really don't think that you will find anything in Numpy that does exactly what you are asking as packaged so I've decided to offer what optimizations I could think up.\nThere are several things that could make this slow here. First off, numpy.where() is rather slow because it has to check every value in the slic... | [
3
] | [] | [] | [
"numpy",
"python",
"random"
] | stackoverflow_0003151157_numpy_python_random.txt |
Q:
Open a file in a function and write to it
I created the function below:
def print_form(x):
f = open('/home/rv/Plone/Zope-2.10.11-final-py2.4/Extensions/test.fasta', 'w')
f.write(str(x))
f.close()
return x
The function returns and prints, but doesnt write it to a file or creates it?
EDIT
I editied the above code the so the file is created in a specific location but it still isnt there
A:
The file 'form.fasta' will be created in the current working directory. This is usually whatever directory you're in when you invoke the script.
To see what your current directory is, add:
print(os.path.abspath(os.curdir))
or equivalent.
Also, make sure f.write(x) converts x to something fit to be written; you might want f.write(str(x)) or f.write(repr(x)) or even f.write(unicode(x)).
Finally, just because you called f.close() doesn't necessarily mean the OS has immediately flushed it out to the disk. (I can't seem to find a Python equivalent to C's setvbuf() function, which would let you switch a file stream to unbuffered mode.)
P.S. One more thing: If x is, say, an integer, just writing it to a file doesn't end the file with a line end character. If you have a one-line file without a line end, and you print it out, and you're like me and have a bash prompt string that starts with the line-clear control code, it will look exactly like the output you get from an empty file.
| Open a file in a function and write to it | I created the function below:
def print_form(x):
f = open('/home/rv/Plone/Zope-2.10.11-final-py2.4/Extensions/test.fasta', 'w')
f.write(str(x))
f.close()
return x
The function returns and prints, but doesnt write it to a file or creates it?
EDIT
I editied the above code the so the file is created in a specific location but it still isnt there
| [
"The file 'form.fasta' will be created in the current working directory. This is usually whatever directory you're in when you invoke the script.\nTo see what your current directory is, add:\nprint(os.path.abspath(os.curdir))\n\nor equivalent.\nAlso, make sure f.write(x) converts x to something fit to be written; ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0003153730_python.txt |
Q:
Perspective detection with OpenCv
If I want to detect perspective distorted objects (e.g rectangles) and calculate the correction transformation, what would be a good method?
For example, I have a lot of photos of papers lying on a flat surface (the photos are shot from an angle), and I want to correct the perspective and crop them.
I am thinking of using the OpenCv Python bindings to whip something up. I thought it would be a "standard problem" with lots of examples, but I failed to find any relevant info. Clues?
EDIT: I should add that I know it can be done by using some Web services, but I see this as a chance of doing something useful while learning OpenCv :)
A:
You have to specify exactly what you mean with detecting the distortion. I assume you want to detect the corners of such a paper (or your table/flat surface) and make it axis-parallel to your display. This can be done using cvFindHomography and cvWarpPerspective. I have written some example code a while ago for python, note that those are still the old bindings (shouldn't take long to update to opencv 2.0 though): http://ioctl.eu/blog/2009/05/13/opencv_homography
The other thing you obviously have to do is detecting the corners. In my sample code, the user is required to click four corners using the mouse. In your case, it is hard to tell because I need an example. OpenCV offers several means to detect corners (see Harris), also in the examples there should be code on how to find rectangles. If you could be more specific, I might be of greater assistence.
UPDATE
This might be interesting for you as well: I've just heard a talk on manipulating perspective distortion in images (to e.g. increase the foreshortening). They require heavy user interaction, but optimize some grid with some constrains to maintain a smooth warping.
Here is the acm link: http://portal.acm.org/citation.cfm?id=1778765.1778864
Maybe you can draw some ideas from that paper and the mentioned references, however I haven't read it myself (yet).
| Perspective detection with OpenCv | If I want to detect perspective distorted objects (e.g rectangles) and calculate the correction transformation, what would be a good method?
For example, I have a lot of photos of papers lying on a flat surface (the photos are shot from an angle), and I want to correct the perspective and crop them.
I am thinking of using the OpenCv Python bindings to whip something up. I thought it would be a "standard problem" with lots of examples, but I failed to find any relevant info. Clues?
EDIT: I should add that I know it can be done by using some Web services, but I see this as a chance of doing something useful while learning OpenCv :)
| [
"You have to specify exactly what you mean with detecting the distortion. I assume you want to detect the corners of such a paper (or your table/flat surface) and make it axis-parallel to your display. This can be done using cvFindHomography and cvWarpPerspective. I have written some example code a while ago for py... | [
3
] | [] | [] | [
"opencv",
"python"
] | stackoverflow_0003151034_opencv_python.txt |
Q:
slice (unsorted) array at value in python
Given the array a = [1,1,12,3,5,8,13,21] I can slice off the first 3 elements like a[:3] giving [1,1,2]. What I want is to slice off up to the element of vlaue i (e.g. if i=8 I want [1,1,12,3,5,8] or [1,1,12,3,5] (I can work with either)).
This works:
return a[:a.index(i)]
but only if I give it a value that's in the array.
Is there a clean built in way to do this that does something sane on the missing value case?
A:
That's a list.
Try
>>> a = [1,1,2,3,5,8,13,21]
>>> import itertools
>>> for x in itertools.takewhile(lambda val: val != 8, a):
... print x
...
1
1
2
3
5
A:
Assuming the array is sorted, use a binary search. The function is in the bisect module.
from bisect import bisect_right
a[:bisect_right(a, value)]
A:
Create a generator, and use that:
a = [1,1,2,3,5,8,13,21]
def _gen(listing, cutoff):
for i in listing:
if i == cutoff:
return
yield i
new_a = list(_gen(a, 5))
... or, if you really want a slice ...
for i, val in enumerate(a):
if val == cutoff:
break
new_a = a[:i]
| slice (unsorted) array at value in python | Given the array a = [1,1,12,3,5,8,13,21] I can slice off the first 3 elements like a[:3] giving [1,1,2]. What I want is to slice off up to the element of vlaue i (e.g. if i=8 I want [1,1,12,3,5,8] or [1,1,12,3,5] (I can work with either)).
This works:
return a[:a.index(i)]
but only if I give it a value that's in the array.
Is there a clean built in way to do this that does something sane on the missing value case?
| [
"\nThat's a list.\nTry \n>>> a = [1,1,2,3,5,8,13,21]\n>>> import itertools\n>>> for x in itertools.takewhile(lambda val: val != 8, a):\n... print x\n...\n1\n1\n2\n3\n5\n\n\n",
"Assuming the array is sorted, use a binary search. The function is in the bisect module.\nfrom bisect import bisect_right\na[:bisect_... | [
5,
0,
0
] | [] | [] | [
"arrays",
"python",
"slice"
] | stackoverflow_0003153975_arrays_python_slice.txt |
Q:
How to pass a specific argument to a decorator in python
I want to write a python function decorator that tests that certain arguments to a function pass some criterion. For eg, Suppose I want to test that some arguments are always even, then I want to be able to do something like this (not valid python code)
def ensure_even( n ) :
def decorator( function ) :
@functools.wraps( function )
def wrapper(*args, **kwargs):
assert(n % 2 == 0)
return function(*args, **kwargs)
return wrapper
return decorator
@ensure_even(arg2)
def foo(arg1, arg2, arg3) : pass
@ensure_even(arg3)
def bar(arg1, arg2, arg3) : pass
But I cannot figure how to achieve the above. Is there a way to pass specific arguments to the decorator? (like arg2 for foo and arg3 for bar in the above)
Thanks!
A:
You can do this:
def ensure_even(argnum):
def fdec(func):
def f(*args, **kwargs):
assert(args[argnum] % 2 == 0) #or assert(not args[argnum] % 2)
return func(*args, **kwargs)
return f
return fdec
So then:
@ensure_even(1) #2nd argument must be even
def test(arg1, arg2):
print(arg2)
test(1,2) #succeeds
test(1,3) #fails
A:
My previous answer missed the point of your question.
Here's a longer solution:
def ensure_even(*argvars):
def fdec(func):
def f(*args,**kwargs):
for argvar in argvars:
try:
assert(not args[func.func_code.co_varnames.index(argvar)] % 2)
except IndexError:
assert(not kwargs[argvar] % 2)
return func(*args,**kwargs)
return f
return fdec
and so this is the usage:
@ensure_even('a','b')
def both_even(a,b):
print a,b
@ensure_even('even')
def first_even(even, arg2):
print even, arg2
both_even(2,2)
first_even(2,3)
both_even(2,1) #fails
although I'm not sure if it will work in all situations.
| How to pass a specific argument to a decorator in python | I want to write a python function decorator that tests that certain arguments to a function pass some criterion. For eg, Suppose I want to test that some arguments are always even, then I want to be able to do something like this (not valid python code)
def ensure_even( n ) :
def decorator( function ) :
@functools.wraps( function )
def wrapper(*args, **kwargs):
assert(n % 2 == 0)
return function(*args, **kwargs)
return wrapper
return decorator
@ensure_even(arg2)
def foo(arg1, arg2, arg3) : pass
@ensure_even(arg3)
def bar(arg1, arg2, arg3) : pass
But I cannot figure how to achieve the above. Is there a way to pass specific arguments to the decorator? (like arg2 for foo and arg3 for bar in the above)
Thanks!
| [
"You can do this:\ndef ensure_even(argnum):\n def fdec(func):\n def f(*args, **kwargs):\n assert(args[argnum] % 2 == 0) #or assert(not args[argnum] % 2)\n return func(*args, **kwargs)\n return f\n return fdec\n\nSo then:\n@ensure_even(1) #2nd argument must be even\ndef test(arg1, arg2):\n print... | [
11,
4
] | [] | [] | [
"decorator",
"function",
"python"
] | stackoverflow_0003152007_decorator_function_python.txt |
Q:
lexical analyse or series of regular expressions to parse unstructured text into structured form
I am trying to write some code that will function like google calendars quick add feature . You know the One where you can input any of the following :
1) 24th sep 2010 , Johns Birthday
2) John's Birthday , 24/9/10
3) 24 September 2010 , Birthday of John Doe
4) 24-9-2010 : John Does Birthday
5) John Does Birthday 24th of September 2010
And it can figure out that we want an event on a date 24/9/2010 have the rest of the material as the event text.
I want to do this is python .
I am thinking of a design where I write regular expressions that may match all of the cases listed above and extract the date. But I am sur there is a smarter way to approach this problem . Since I clearly am not trained in lexical analysis or the many types of parsers styles. I am looking for whats a good way to approach this problem.
A:
NOTE: The python code here is not correct! It is just a rough pseudo-code of how it might look.
Regular Expressions are good at finding and extracting data from text in a fixed format (e.g. a DD/MM/YYYY date).
A lexer/parser pair is good at processing data in a structured, but somewhat variable format. Lexers split text into tokens. These tokens are units of information of a given type (number, string, etc.). Parsers take this series of tokens and does something depending on the order of the tokens.
Looking at the data, you have a basic (subject, verb, object) structure in different combinations for the relation (person, 'birthday', date):
I would handle 29/9/10 and 24-9-2010 as a single token using a regex, returning it as a date type. You could probably do the same for the other dates, with a map to convert September and sep to 9.
You could then return the everything else as strings (separated by whitespace).
You then have:
date ',' string 'birthday'
string 'birthday' ',' date
date 'birthday' 'of' string string
date ':' string string 'birthday'
string string 'birthday' date
NOTE: 'birthday', ',', ':' and 'of' here are keywords, so:
class Lexer:
DATE = 1
STRING = 2
COMMA = 3
COLON = 4
BIRTHDAY = 5
OF = 6
keywords = { 'birthday': BIRTHDAY, 'of': OF, ',': COMMA, ':', COLON }
def next_token():
if have_saved_token:
have_saved_token = False
return saved_type, saved_value
if date_re.match(): return DATE, date
str = read_word()
if str in keywords.keys(): return keywords[str], str
return STRING, str
def keep(type, value):
have_saved_token = True
saved_type = type
saved_value = value
All except 3 use the possessive form of the person ('s if the last character is a consonant, s if it is a vowel). This can be tricky, as 'Alexis' could be the plural form of 'Alexi', but since you are restricting where plural forms can be, it is easy to detect:
def parseNameInPluralForm():
name = parseName()
if name.ends_with("'s"): name.remove_from_end("'s")
elif name.ends_with("s"): name.remove_from_end("s")
return name
Now, name can either be first-name or first-name last-name (yes, I know Japan swaps these around, but from a processing perspective, the above problem does not need to differentiate first and last names). The following will handle these two forms:
def parseName():
type, firstName = Lexer.next_token()
if type != Lexer.STRING: raise ParseError()
type, lastName = Lexer.next_token()
if type == Lexer.STRING: # first-name last-name
return firstName + ' ' + lastName
else:
Lexer.keep(type, lastName)
return firstName
Finally, you can process forms 1-5 using something like this:
def parseBirthday():
type, data = Lexer.next_token()
if type == Lexer.DATE: # 1, 3 & 4
date = data
type, data = Lexer.next_token()
if type == Lexer.COLON or type == Lexer.COMMA: # 1 & 4
person = parsePersonInPluralForm()
type, data = Lexer.next_token()
if type != Lexer.BIRTHDAY: raise ParseError()
elif type == Lexer.BIRTHDAY: # 3
type, data = Lexer.next_token()
if type != Lexer.OF: raise ParseError()
person = parsePerson()
elif type == Lexer.STRING: # 2 & 5
Lexer.keep(type, data)
person = parsePersonInPluralForm()
type, data = Lexer.next_token()
if type != Lexer.BIRTHDAY: raise ParseError()
type, data = Lexer.next_token()
if type == Lexer.COMMA: # 2
type, data = Lexer.next_token()
if type != Lexer.DATE: raise ParseError()
date = data
else:
raise ParseError()
return person, date
| lexical analyse or series of regular expressions to parse unstructured text into structured form | I am trying to write some code that will function like google calendars quick add feature . You know the One where you can input any of the following :
1) 24th sep 2010 , Johns Birthday
2) John's Birthday , 24/9/10
3) 24 September 2010 , Birthday of John Doe
4) 24-9-2010 : John Does Birthday
5) John Does Birthday 24th of September 2010
And it can figure out that we want an event on a date 24/9/2010 have the rest of the material as the event text.
I want to do this is python .
I am thinking of a design where I write regular expressions that may match all of the cases listed above and extract the date. But I am sur there is a smarter way to approach this problem . Since I clearly am not trained in lexical analysis or the many types of parsers styles. I am looking for whats a good way to approach this problem.
| [
"NOTE: The python code here is not correct! It is just a rough pseudo-code of how it might look.\nRegular Expressions are good at finding and extracting data from text in a fixed format (e.g. a DD/MM/YYYY date).\nA lexer/parser pair is good at processing data in a structured, but somewhat variable format. Lexers sp... | [
2
] | [] | [] | [
"lexical_analysis",
"parsing",
"python",
"regex"
] | stackoverflow_0003153869_lexical_analysis_parsing_python_regex.txt |
Q:
Python XLWT adjusting column widths
I am enormously impressed with the ease of use of XLWT, but there is one thing I have not figured out how to do. I am trying to adjust certain rows to the minimum width they would need to display all characters (in other words, what excel would do if you double clicked on the divider between cells).
I know how to adjust the column widths to a predetermined amount, but I am not certain how to determine the minimum width needed to display everything.
A:
Width is 1/256 the width of the zero character for the default font. A good enough approximation is:
def get_width(num_characters):
return int((1+num_characters) * 256)
| Python XLWT adjusting column widths | I am enormously impressed with the ease of use of XLWT, but there is one thing I have not figured out how to do. I am trying to adjust certain rows to the minimum width they would need to display all characters (in other words, what excel would do if you double clicked on the divider between cells).
I know how to adjust the column widths to a predetermined amount, but I am not certain how to determine the minimum width needed to display everything.
| [
"Width is 1/256 the width of the zero character for the default font. A good enough approximation is:\ndef get_width(num_characters):\n return int((1+num_characters) * 256)\n\n"
] | [
29
] | [] | [] | [
"python",
"xlwt"
] | stackoverflow_0003154270_python_xlwt.txt |
Q:
Cleaning up and removing tags with BeautifulSoup
I have the following script so far:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import urllib2
br = Browser()
br.open("http://www.foo.com")
html = br.response().read();
soup = BeautifulSoup(html)
items = soup.findAll(id="info")
and it runs perfectly, and results in the following "items":
<div id="info">
<span class="customer"><b>John Doe</b></span><br>
123 Main Street<br>
Phone:5551234<br>
<b><span class="paid">YES</span></b>
</div>
However, I'd like to take items and clean it up to get
John Doe
123 Main Street
5551234
How can you remove such tags in BeautifulSoup and Python?
As always, thanks!
A:
This will do it for this EXACT html. Obviously this isn't tolerant of any deviation, so you'll want to add quite a lot of bounds checking and null checking, but here's the nuts and bolts to get your data into plain text.
items = soup.findAll(id="info")
print items[0].span.b.contents[0]
print items[0].contents[3].strip()
print items[0].contents[5].strip().split(":", 1)[1]
| Cleaning up and removing tags with BeautifulSoup | I have the following script so far:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import urllib2
br = Browser()
br.open("http://www.foo.com")
html = br.response().read();
soup = BeautifulSoup(html)
items = soup.findAll(id="info")
and it runs perfectly, and results in the following "items":
<div id="info">
<span class="customer"><b>John Doe</b></span><br>
123 Main Street<br>
Phone:5551234<br>
<b><span class="paid">YES</span></b>
</div>
However, I'd like to take items and clean it up to get
John Doe
123 Main Street
5551234
How can you remove such tags in BeautifulSoup and Python?
As always, thanks!
| [
"This will do it for this EXACT html. Obviously this isn't tolerant of any deviation, so you'll want to add quite a lot of bounds checking and null checking, but here's the nuts and bolts to get your data into plain text.\nitems = soup.findAll(id=\"info\")\nprint items[0].span.b.contents[0]\nprint items[0].content... | [
1
] | [] | [] | [
"beautifulsoup",
"extract",
"python",
"web_scraping"
] | stackoverflow_0003153882_beautifulsoup_extract_python_web_scraping.txt |
Q:
How to mock a free function in python?
I have a python program with a global function that is painful to test (it needs a large dataset to work properly). What is the best way to get around this while testing functions that call it?
I've found that the following works (but it make me feel dirty to use it).
module foo:
def PainLiesHere():
return 4; #guaranteed to be random
module test
import foo
def BlissLiesHere():
return 5
foo.PainLiesHere = BlissLiesHere
# test stuff
A:
This is a perfectly fine way to do it. As long as you know that BlissLiesHere does not change the overall behavior of the unit you are testing...
EDIT:
This is what is being done, under all the nice extras they provide, by different kinds of mocking libraries, such as Mock, Mox, etc.
| How to mock a free function in python? | I have a python program with a global function that is painful to test (it needs a large dataset to work properly). What is the best way to get around this while testing functions that call it?
I've found that the following works (but it make me feel dirty to use it).
module foo:
def PainLiesHere():
return 4; #guaranteed to be random
module test
import foo
def BlissLiesHere():
return 5
foo.PainLiesHere = BlissLiesHere
# test stuff
| [
"This is a perfectly fine way to do it. As long as you know that BlissLiesHere does not change the overall behavior of the unit you are testing...\nEDIT:\nThis is what is being done, under all the nice extras they provide, by different kinds of mocking libraries, such as Mock, Mox, etc.\n"
] | [
8
] | [] | [] | [
"mocking",
"python"
] | stackoverflow_0003154441_mocking_python.txt |
Q:
'METHODNAME' as Client method versus irc_'METHODNAME' in twisted
Looking at twisted.words.protocols.irc.IRCClient, it seems to me like there are some strangely redundant methods. For instance, there is a method 'privmsg' but also a method 'irc_PRIVMSG'
As another example consider 'join' and 'irc_JOIN'
What I want to know is why the redundancy, those are just two examples of many. Are the two different types used in different contexts? Are we supposed to use one type and not another?
A:
You're on the right track about the two different types of methods being used in different contexts. This can actually be seen quite easily by examining the way IRCClient handles data it receives. First it parses them into lines, then it splits the lines up and passes the pieces to its own handleCommand method:
def handleCommand(self, command, prefix, params):
"""Determine the function to call for the given command and call
it with the given arguments.
"""
method = getattr(self, "irc_%s" % command, None)
try:
if method is not None:
method(prefix, params)
else:
self.irc_unknown(prefix, command, params)
except:
log.deferr()
This is an example of a pattern that's quite common in Twisted protocol implementations and, even more generally, in Python programs as a whole. Some piece of the input is used to construct a method name dynamically. Then getattr is used to look up that method. If it is found, it is called.
Since the server is sending the client lines like "PRIVMSG ..." and "JOIN ...", this results in IRCClient looking up methods like irc_PRIVMSG and irc_JOIN.
These irc_* methods are just called with the split up but otherwise unparsed remainder of the line. This provides all of the information that came with the message, but it's not always the nicest format for the data to be in. For example, JOIN messages include usernames that include a hostmask, but often the hostmask is irrelevant and only the nickname is desired. So JOIN does something that's fairly typical for irc_* methods: it turns the rough data into something more pleasant to work with and passes the result on to userJoined:
def irc_JOIN(self, prefix, params):
"""
Called when a user joins a channel.
"""
nick = string.split(prefix,'!')[0]
channel = params[-1]
if nick == self.nickname:
self.joined(channel)
else:
self.userJoined(nick, channel)
You can see that there's also a conditional here, sometimes it calls joined instead of userJoined. This is another example of a transformation from the low-level data into something which is supposed to be more convenient for the application developer to work with.
This layering should help you decide which methods to override when handling events. If the highest level callback, such as userJoined, joined, or privmsg is sufficient for your requirements, then you should use those because they'll make your task the easiest. On the other hand, if they present the data in an inconvenient format or are awkward to use in some other way, you can drop down to the irc_* level. Your method will be called instead of the one defined on IRCClient, so you can handle the data in the lower-level format and the higher level callback won't even be invoked (unless you also invoke the base implementation when you override the method).
You'll also find there are IRC messages which IRCClient doesn't even define an irc_* method for. As we saw above in the handleCommand method, these all go to the irc_unknown callback. But if you define an irc_* method on your IRCClient subclass, then handleCommand will start passing the data to that method. Clearly in these cases, your only choice is to define the irc_* method, since there is no higher-level callback (like privmsg in the irc_PRIVMSG/privmsg case).
You can structure your implementations of irc_* methods similarly to the way IRCClient does, if you like - I usually find it helpful to do so, since it makes unit testing easier and keeps the protocol parsing logic separate from the application logic - but it's up to you.
| 'METHODNAME' as Client method versus irc_'METHODNAME' in twisted | Looking at twisted.words.protocols.irc.IRCClient, it seems to me like there are some strangely redundant methods. For instance, there is a method 'privmsg' but also a method 'irc_PRIVMSG'
As another example consider 'join' and 'irc_JOIN'
What I want to know is why the redundancy, those are just two examples of many. Are the two different types used in different contexts? Are we supposed to use one type and not another?
| [
"You're on the right track about the two different types of methods being used in different contexts. This can actually be seen quite easily by examining the way IRCClient handles data it receives. First it parses them into lines, then it splits the lines up and passes the pieces to its own handleCommand method:\... | [
4
] | [] | [] | [
"client",
"irc",
"libraries",
"python",
"twisted"
] | stackoverflow_0003153666_client_irc_libraries_python_twisted.txt |
Q:
How do I pipe the output of file to a variable in Python?
How do I pipe the output of file to a variable in Python?
Is it possible? Say to pipe the output of netstat to a variable x in Python?
A:
It is possible. See:
http://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote
In Python 2.4 and above:
from subprocess import *
x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0]
A:
Two parts:
Shell
netstat | python read_netstat.py
Python read_netstat.py
import sys
variable = sys.stdin.read()
That will read the output from netstat into a variable.
A:
Take a look at the subprocess module. It allows you to start new processes, interact with them, and read their output.
In particular see the section Replacing /bin/sh shell backquote:
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
| How do I pipe the output of file to a variable in Python? | How do I pipe the output of file to a variable in Python?
Is it possible? Say to pipe the output of netstat to a variable x in Python?
| [
"It is possible. See:\nhttp://docs.python.org/library/subprocess.html#replacing-bin-sh-shell-backquote\nIn Python 2.4 and above:\nfrom subprocess import *\nx = Popen([\"netstat\", \"-x\", \"-y\", \"-z\"], stdout=PIPE).communicate()[0]\n\n",
"Two parts:\nShell\nnetstat | python read_netstat.py\n\nPython read_netst... | [
6,
5,
2
] | [] | [] | [
"python"
] | stackoverflow_0003153460_python.txt |
Q:
Django form.save step by step
Let's say I have a form for adding/editing products (with field 'user' being a foreign key to my User) triggered from two separate view functions - add/edit :
def product_add(request):
userprofile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = ProductAddForm(request.POST, request.FILES,)
if form.is_valid():
form.save(user=request.user)
else:
form = ProductAddForm()
return render_to_response('products/product_add.html', {
'form':form, 'user':request.user,
}, context_instance=RequestContext(request))
def product_edit(request, id):
product = get_object_or_404(Product, id=id, user=request.user)
if product.user.id!=request.user.id:
raise Http404
if request.method == 'POST':
form = ProductAddForm(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save(user=request.user)
else:
form = ProductAddForm(instance=product)
return render_to_response('products/product_edit.html', {
'form':form, 'user':request.user,
}, context_instance=RequestContext(request))
The form's save method looks as follows :
def save(self, user, *args, **kwargs):
self.instance.user = user
post = super(ProductAddForm, self).save(*args, **kwargs)
post.save()
Can somebody tell me what's happening in this save method step by step ?Why do we call super on this form and what is the difference in whole processing when we edit and save new product if function call is the same ?
A:
self.instance.user = user
Save the user argument into the self.instance object's user attribute
post = super(ProductAddForm, self).save(*args, **kwargs)
Invoke the superclass save method to get a resulting object.
post.save()
Save the resulting object. This may be needless, or it may be essential, depending on the arguments to save.
See http://docs.djangoproject.com/en/1.2/topics/forms/modelforms/#the-save-method. If commit is False, then the post object has not been saved to the database.
| Django form.save step by step | Let's say I have a form for adding/editing products (with field 'user' being a foreign key to my User) triggered from two separate view functions - add/edit :
def product_add(request):
userprofile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = ProductAddForm(request.POST, request.FILES,)
if form.is_valid():
form.save(user=request.user)
else:
form = ProductAddForm()
return render_to_response('products/product_add.html', {
'form':form, 'user':request.user,
}, context_instance=RequestContext(request))
def product_edit(request, id):
product = get_object_or_404(Product, id=id, user=request.user)
if product.user.id!=request.user.id:
raise Http404
if request.method == 'POST':
form = ProductAddForm(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save(user=request.user)
else:
form = ProductAddForm(instance=product)
return render_to_response('products/product_edit.html', {
'form':form, 'user':request.user,
}, context_instance=RequestContext(request))
The form's save method looks as follows :
def save(self, user, *args, **kwargs):
self.instance.user = user
post = super(ProductAddForm, self).save(*args, **kwargs)
post.save()
Can somebody tell me what's happening in this save method step by step ?Why do we call super on this form and what is the difference in whole processing when we edit and save new product if function call is the same ?
| [
"\nself.instance.user = user \n\nSave the user argument into the self.instance object's user attribute\n\npost = super(ProductAddForm, self).save(*args, **kwargs)\n\nInvoke the superclass save method to get a resulting object.\n\npost.save()\n\nSave the resulting object. This may be needless, or it may be essentia... | [
3
] | [] | [] | [
"django",
"python",
"super"
] | stackoverflow_0003154624_django_python_super.txt |
Q:
Problem about recursion
Please suggest me the solution to the following problem
consider a function
function recurse(a):
for child in a.childs:
recurse(child)
Now I want to execute some code lets say
print "Program ends here"
when the program is done with recursion,so how can I know when the recursion will end?
Thank you
A:
The various answers proposed so far, which sum up to "do it outside of recurse", are fine. But if you're keen to do it inside recurse, that's not hard either (just marginally less efficient):
function recurse(a, _toplevel=True):
for child in a.childs:
recurse(child, False)
if _toplevel:
print "Recursion done!"
The leading _ in the name of the _toplevel argument indicates it's private, so callers know not to pass it.
Similar solutions involve keeping track of the level of recursion (not just whether it's top level or not, but "how deep you are" in general):
function recurse(a, _level=0):
for child in a.childs:
recurse(child, _level + 1)
if _level == 0:
print "Recursion done!"
While precious in other cases (e.g. printing out nested structures with indents) it's not needed here (and there's another marginal loss of efficiency compared with the first solution I gave, based on the _toplevel boolean).
A:
Do you mean like this?
recurse(something)
print "Program ends here"
When the recursive function is done, the program will continue with the next statement, just like with any other function. That the function was recursive doesn't matter.
A:
You could use a default parameter:
function recurse(a, top=True):
for child in a.childs:
recurse(child, False)
if top: print("Program ends here.")
recurse(a)
A:
I may be misunderstanding your question, but the recursion will be done when the highest level completes.
A new function that wraps recurse() could do this:
function do_recursion(a):
res = recurse(a)
print "Program ends here"
return res
A:
Put the print statement after the first call to recurse.
def main():
a = NodeOfSomeSort()
recurse(a)
print "Recursion done!"
| Problem about recursion | Please suggest me the solution to the following problem
consider a function
function recurse(a):
for child in a.childs:
recurse(child)
Now I want to execute some code lets say
print "Program ends here"
when the program is done with recursion,so how can I know when the recursion will end?
Thank you
| [
"The various answers proposed so far, which sum up to \"do it outside of recurse\", are fine. But if you're keen to do it inside recurse, that's not hard either (just marginally less efficient):\nfunction recurse(a, _toplevel=True):\n for child in a.childs:\n recurse(child, False)\n if _toplevel:\n pri... | [
3,
2,
2,
0,
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0003154651_python_recursion.txt |
Q:
Breaking a parent function from within a child function (PHP Preferrably)
I was challenged how to break or end execution of a parent function without modifying the code of the parent, using PHP
I cannot figure out any solution, other than die(); in the child, which would end all execution, and so anything after the parent function call would end. Any ideas?
code example:
function victim() {
echo "I should be run";
killer();
echo "I should not";
}
function killer() {
//code to break parent here
}
victim();
echo "This should still run";
A:
function victim() {
echo "I should be run";
killer();
echo "I should not";
}
function killer() {
throw new Exception('Die!');
}
try {
victim();
} catch (Exception $e) {
// note that catch blocks shouldn't be empty :)
}
echo "This should still run";
A:
Note that Exceptions are not going to work in the following scenario:
function victim() {
echo "this runs";
try {
killer();
}
catch(Exception $sudden_death) {
echo "still alive";
}
echo "and this runs just fine, too";
}
function killer() { throw new Exception("This is not going to work!"); }
victim();
You would need something else, the only thing more robust would be something like installing your own error handler, ensure all errors are reported to the error handler and ensure errors are not converted to exceptions; then trigger an error and have your error handler kill the script when done. This way you can execute code outside of the context of killer()/victim() and prevent victim() from completing normally (only if you do kill the script as part of your error handler).
| Breaking a parent function from within a child function (PHP Preferrably) | I was challenged how to break or end execution of a parent function without modifying the code of the parent, using PHP
I cannot figure out any solution, other than die(); in the child, which would end all execution, and so anything after the parent function call would end. Any ideas?
code example:
function victim() {
echo "I should be run";
killer();
echo "I should not";
}
function killer() {
//code to break parent here
}
victim();
echo "This should still run";
| [
"function victim() {\n echo \"I should be run\";\n killer();\n echo \"I should not\";\n}\nfunction killer() {\n throw new Exception('Die!');\n}\n\ntry {\n victim();\n} catch (Exception $e) {\n // note that catch blocks shouldn't be empty :)\n}\necho \"This should still run\";\n\n",
"Note that Ex... | [
7,
1
] | [] | [] | [
"break",
"function",
"php",
"python"
] | stackoverflow_0003154489_break_function_php_python.txt |
Q:
Good resources to start python for web development?
I'm really interested in learning Python for web development. Can anyone point me in the right direction? I've been looking at stuff on Google, but haven't really found anything that shows proper documentation and how to get started. Any recommended frameworks? Tutorials?
I've been doing PHP for 5 years now, so I just want to try something new.
A:
Django is probably the best starting point. It's got great documentation and an easy tutorial (at http://djangoproject.com/) and a free online book too (http://www.djangobook.com/).
A:
Web Server Gateway Interface
About
http://www.wsgi.org/en/latest/index.html
http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface
Tutorials
http://webpython.codepoint.net/wsgi_tutorial
http://lucumr.pocoo.org/2007/5/21/getting-started-with-wsgi/
http://archimedeanco.com/wsgi-tutorial/
A:
There are three major parts to python web frameworks, in my experience. From the front to back:
Views/Templates: Application frameworks don't function as independent scripts - instead, you map paths to python functions or objects which return html. To generate the html you probably need templates (aka views). Check out Cheetah.
Application framework/Server: There are plenty. CherryPy is my favorite, and is good for understanding how a python application server works because a) it's simple and b) unlike django and others, it is just the application server and doesn't include a templating engine or a database abstraction layer.
Database layer: I've actually never used it, but everyone seems to like SQLAlchemy. I prefer, in simple applications, executing SQL directly using a tool like psycopg2 (for postgres).
A:
You can try Django. It's easy to learn, and it works with GAE (though the default version is 0.96, a little bit old, but you can change it). And there's a video about rapid development (by Guido Van Rossum) that goes through the basics of setting up a Django project in App Engine.
| Good resources to start python for web development? | I'm really interested in learning Python for web development. Can anyone point me in the right direction? I've been looking at stuff on Google, but haven't really found anything that shows proper documentation and how to get started. Any recommended frameworks? Tutorials?
I've been doing PHP for 5 years now, so I just want to try something new.
| [
"Django is probably the best starting point. It's got great documentation and an easy tutorial (at http://djangoproject.com/) and a free online book too (http://www.djangobook.com/).\n",
"Web Server Gateway Interface\nAbout\n\nhttp://www.wsgi.org/en/latest/index.html\nhttp://en.wikipedia.org/wiki/Web_Server_Gatew... | [
5,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003154921_python.txt |
Q:
why does response codes returned by httplib and urllib not match?
I'm writing a dead link detector and wondering which lib i should use, httplib and urllib, so I tried both.
def http_response_code(url):
host = urlparse(url)[1]
req = '/'.join(urlparse(url)[2:5])
conn = httplib.HTTPConnection(host)
conn.request('HEAD', req)
res = conn.getresponse()
return res.status, res.reason
def urllib_response_code(url):
a = urllib.urlopen(url)
return a.getcode()
def main():
url = 'http://1010wins.com/content_page.php?contenttype=4&contentid=6077355'
print http_response_code(url)
print urllib_response_code(url)
But I'm confused about the mismatch of results returned by the above 2 methods, which are:
(302, 'Found')
200
I think maybe it's because urllib automatically detect the redirect and fetch the final destination page, and then return the response code?
Thanks.
A:
302 is the HTTP status code for a redirect (see for example here), and httplib (the lower-level library) returns it faithfully, while urllib is automatically following the redirect and giving you the final resulting status code (200 for "everything OK").
Pick the library that best suits the abstraction layer you want to work at -- httplib gives you a lot more control, but it's less general (won't do anything with URLs with other protocols such as ftp:, etc, for example) and lower-level (so you have to do a bit more work!-).
| why does response codes returned by httplib and urllib not match? | I'm writing a dead link detector and wondering which lib i should use, httplib and urllib, so I tried both.
def http_response_code(url):
host = urlparse(url)[1]
req = '/'.join(urlparse(url)[2:5])
conn = httplib.HTTPConnection(host)
conn.request('HEAD', req)
res = conn.getresponse()
return res.status, res.reason
def urllib_response_code(url):
a = urllib.urlopen(url)
return a.getcode()
def main():
url = 'http://1010wins.com/content_page.php?contenttype=4&contentid=6077355'
print http_response_code(url)
print urllib_response_code(url)
But I'm confused about the mismatch of results returned by the above 2 methods, which are:
(302, 'Found')
200
I think maybe it's because urllib automatically detect the redirect and fetch the final destination page, and then return the response code?
Thanks.
| [
"302 is the HTTP status code for a redirect (see for example here), and httplib (the lower-level library) returns it faithfully, while urllib is automatically following the redirect and giving you the final resulting status code (200 for \"everything OK\").\nPick the library that best suits the abstraction layer yo... | [
5
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003155073_http_python.txt |
Q:
extract parts of the string in python
I have to parse an input string in python and extract certain parts from it.
the format of the string is
(xx,yyy,(aa,bb,...)) // Inner parenthesis can hold one or more characters in it
I want a function to return xx, yyyy and a list containing aa, bb ... etc
I can ofcourse do it by trying to split of the parenthesis and stuff but I want to know if there a proper pythonic way of extracting such info from a string
I have this code which works, but is there a better way to do it (without regex)
def processInput(inputStr):
value = inputStr.strip()[1:-1]
parts = value.split(',', 2)
return parts[0], parts[1], (parts[2].strip()[1:-1]).split(',')
A:
If your parenthesis nesting can be arbitrarily deep, then regexen won't do, you'll need a state machine or a parser. Pyparsing supports recursive grammars using forward-declaration class Forward:
from pyparsing import *
LPAR,RPAR,COMMA = map(Suppress,"(),")
nestedParens = Forward()
listword = Word(alphas) | '...'
nestedParens << Group(LPAR + delimitedList(listword | nestedParens) + RPAR)
text = "(xx,yyy,(aa,bb,...))"
results = nestedParens.parseString(text).asList()
print results
text = "(xx,yyy,(aa,bb,(dd,ee),ff,...))"
results = nestedParens.parseString(text).asList()
print results
Prints:
[['xx', 'yyy', ['aa', 'bb', '...']]]
[['xx', 'yyy', ['aa', 'bb', ['dd', 'ee'], 'ff', '...']]]
A:
If you're allergic to REs, you could use pyparsing:
>>> import pyparsing as p
>>> ope, clo, com = map(p.Suppress, '(),')
>>> w = p.Word(p.alphas)
>>> s = ope + w + com + w + com + ope + p.delimitedList(w) + clo + clo
>>> x = '(xx,yyy,(aa,bb,cc))'
>>> list(s.parseString(x))
['xx', 'yyy', 'aa', 'bb', 'cc']
pyparsing also makes it easy to control the exact form of results (e.g. by grouping the last 3 items into their own sublist), if you want. But I think the nicest aspect is how natural (depending on how much space you want to devote to it) you can make the "grammar specification" read: an open paren, a word, a comma, a word, a comma, an open paren, a delimited list of words, two closed parentheses (if you find the assignment to s above not so easy to read, I guess it's my fault for not choosing longer identifiers;-).
A:
Let's use regular expressions!
/\(([^,]+),([^,]+),\(([^)]+)\)\)/
Match against that, first capturing group contains xx, second contains yyy, split the third on , and you have your list.
A:
How about like this?
>>> import ast
>>> import re
>>>
>>> s="(xx,yyy,(aa,bb,ccc))"
>>> x=re.sub("(\w+)",'"\\1"',s)
# '("xx","yyy",("aa","bb","ccc"))'
>>> ast.literal_eval(x)
('xx', 'yyy', ('aa', 'bb', 'ccc'))
>>>
A:
I don't know that this is better, but it's a different way to do it. Using the regex previously suggested
def processInput(inputStr):
value = [re.sub('\(*\)*','',i) for i in inputStr.split(',')]
return value[0], value[1], value[2:]
Alternatively, you could use two chained replace functions in lieu of the regex.
A:
Your solution is decent (simple, efficient). You could use regular expressions to restrict the syntax if you don't trust your data source.
import re
parser_re = re.compile(r'\(([^,)]+),([^,)]+),\(([^)]+)\)')
def parse(input):
m = parser_re.match(input)
if m:
first = m.group(1)
second = m.group(2)
rest = m.group(3).split(",")
return (first, second, rest)
else:
return None
print parse( '(xx,yy,(aa,bb,cc,dd))' )
print parse( 'xx,yy,(aa,bb,cc,dd)' ) # doesn't parse, returns None
# can use this to unpack the various parts.
# first,second,rest = parse(...)
Prints:
('xx', 'yy', ['aa', 'bb', 'cc', 'dd'])
None
| extract parts of the string in python | I have to parse an input string in python and extract certain parts from it.
the format of the string is
(xx,yyy,(aa,bb,...)) // Inner parenthesis can hold one or more characters in it
I want a function to return xx, yyyy and a list containing aa, bb ... etc
I can ofcourse do it by trying to split of the parenthesis and stuff but I want to know if there a proper pythonic way of extracting such info from a string
I have this code which works, but is there a better way to do it (without regex)
def processInput(inputStr):
value = inputStr.strip()[1:-1]
parts = value.split(',', 2)
return parts[0], parts[1], (parts[2].strip()[1:-1]).split(',')
| [
"If your parenthesis nesting can be arbitrarily deep, then regexen won't do, you'll need a state machine or a parser. Pyparsing supports recursive grammars using forward-declaration class Forward:\nfrom pyparsing import *\n\nLPAR,RPAR,COMMA = map(Suppress,\"(),\")\nnestedParens = Forward()\nlistword = Word(alphas)... | [
3,
3,
2,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003154743_python.txt |
Q:
creating and intersecting hexahedrons with CGAL
Using the Python bindings for CGAL, I can't work out how create a hexahedron, nor how to calculate its intersection with another hexahedron.
I have 8 input points, which are the corners of the hexahedron:
My code does this:
P = Polyhedron_3()
bottom = P.make_tetrahedron(p[0],p[1],p[2],p[3])
top = P.make_tetrahedron(p[4],p[5],p[6],p[7])
left = P.make_tetrahedron(p[0],p[1],p[5],p[4])
right = P.make_tetrahedron(p[3],p[2],p[6],p[7])
front = P.make_tetrahedron(p[4],p[7],p[3],p[0])
back = P.make_tetrahedron(p[1],p[2],p[6],p[5])
but when I count the points in the resulting polyhedron there are 24 - each face is unjoined with its neighbours.
How can I build a solid hexahedron using Python CGAL?
And, finally, having successfully constructed two such polyhedron, how do I calculate their intersection?
A:
You're going to want to create an initial tetrahedron, then use split_edge three times and moving the newly created vertices to where they are supposed to be. Then use another combination of split_facet and split_edge to "mold" the hexahedron into place.
See Section 25.3.7 of CGAL Documentation to see this being done in explicit detail for a special case hexahedron with vertices [0,0,0],[1,0,0],[0,1,0],[0,0,1],[1,1,0],[1,0,1],[0,1,1], and [1,1,1], without (I believe) any loss of generality.
| creating and intersecting hexahedrons with CGAL | Using the Python bindings for CGAL, I can't work out how create a hexahedron, nor how to calculate its intersection with another hexahedron.
I have 8 input points, which are the corners of the hexahedron:
My code does this:
P = Polyhedron_3()
bottom = P.make_tetrahedron(p[0],p[1],p[2],p[3])
top = P.make_tetrahedron(p[4],p[5],p[6],p[7])
left = P.make_tetrahedron(p[0],p[1],p[5],p[4])
right = P.make_tetrahedron(p[3],p[2],p[6],p[7])
front = P.make_tetrahedron(p[4],p[7],p[3],p[0])
back = P.make_tetrahedron(p[1],p[2],p[6],p[5])
but when I count the points in the resulting polyhedron there are 24 - each face is unjoined with its neighbours.
How can I build a solid hexahedron using Python CGAL?
And, finally, having successfully constructed two such polyhedron, how do I calculate their intersection?
| [
"You're going to want to create an initial tetrahedron, then use split_edge three times and moving the newly created vertices to where they are supposed to be. Then use another combination of split_facet and split_edge to \"mold\" the hexahedron into place.\nSee Section 25.3.7 of CGAL Documentation to see this bei... | [
1
] | [] | [] | [
"cgal",
"geometry",
"python"
] | stackoverflow_0003154269_cgal_geometry_python.txt |
Q:
Python 2.6: parallel parsing with urllib2
I'm currently retrieving and parsing pages from a website using urllib2. However, there are many of them (more than 1000), and processing them sequentially is painfully slow.
I was hoping there was a way to retrieve and parse pages in a parallel fashion. If that's a good idea, is it possible, and how do I do it?
Also, what are "reasonable" values for the number of pages to process in parallel (I wouldn't want to put too much strain on the server or get banned because I'm using too many connections)?
Thanks!
A:
You can always use threads (i.e. run each download in a separate thread). For large numbers, this could be a little too resource hogging, in which case I recommend you take a look at gevent and specifically this example, which may be just what you need.
(from gevent.org: "gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libevent event loop")
| Python 2.6: parallel parsing with urllib2 | I'm currently retrieving and parsing pages from a website using urllib2. However, there are many of them (more than 1000), and processing them sequentially is painfully slow.
I was hoping there was a way to retrieve and parse pages in a parallel fashion. If that's a good idea, is it possible, and how do I do it?
Also, what are "reasonable" values for the number of pages to process in parallel (I wouldn't want to put too much strain on the server or get banned because I'm using too many connections)?
Thanks!
| [
"You can always use threads (i.e. run each download in a separate thread). For large numbers, this could be a little too resource hogging, in which case I recommend you take a look at gevent and specifically this example, which may be just what you need.\n(from gevent.org: \"gevent is a coroutine-based Python netwo... | [
3
] | [] | [] | [
"parallel_processing",
"parsing",
"python",
"urllib2"
] | stackoverflow_0003155382_parallel_processing_parsing_python_urllib2.txt |
Q:
Python's lambda iteration not working as intended
In the code below I intend to have two buttons, and when each is pressed '0' and '1' are to be printed to stdout, respectively. However when the program is run, they both print '1', which is the last value i had in the for iteration. Why?
import Tkinter as tk
import sys
root = tk.Tk()
for i in range(0,2):
cmd = lambda: sys.stdout.write(str(i))
tk.Button(text="print '%d'" % i,command=cmd).pack()
root.mainloop()
A:
The i is not captured in the lambda when you create it (as you wanted). Instead, both functions refer back to the i in the external for loop, which changes after the function is created and before it is run. To capture it, you can use a default value:
for i in range(0,2):
cmd = lambda i=i: sys.stdout.write(str(i))
tk.Button(text="print '%d'" % i,command=cmd).pack()
A:
Surely it's the issue in
On lambdas, capture, and mutability
that comes up over and over...
A:
I think it's a bit odd to use an anonymous function just to then give it a name. Why not write it like this?
for i in 0,1:
def cmd():
return sys.stdout.write(str(i))
tk.Button(text="print '%d'"%i, command=cmd).pack()
| Python's lambda iteration not working as intended | In the code below I intend to have two buttons, and when each is pressed '0' and '1' are to be printed to stdout, respectively. However when the program is run, they both print '1', which is the last value i had in the for iteration. Why?
import Tkinter as tk
import sys
root = tk.Tk()
for i in range(0,2):
cmd = lambda: sys.stdout.write(str(i))
tk.Button(text="print '%d'" % i,command=cmd).pack()
root.mainloop()
| [
"The i is not captured in the lambda when you create it (as you wanted). Instead, both functions refer back to the i in the external for loop, which changes after the function is created and before it is run. To capture it, you can use a default value:\nfor i in range(0,2):\n cmd = lambda i=i: sys.stdout.write(s... | [
5,
3,
1
] | [] | [] | [
"lambda",
"python",
"tkinter"
] | stackoverflow_0003155603_lambda_python_tkinter.txt |
Q:
How to test a function that deals with setting file ownership without being root
I wrote a function that copies the /etc/skel directory on a linux machine during a "create new user" RPC call. Now, there is quite a few things about this I want to test, for example the files in /etc/skel and the targets of symlinks should not have changed permissions afterwards, whereas the copied files including the actual symlinks should have a changed owner. Now, i can create my test directory and files using mkdtemp and stuff, but I can't chown those to another user without root privileges. How would you write a test for this?
A:
You could make an object which does the chmod, and inject a mock when testing. This mock would not really do the chmod, but make it possible to test if it was called with the right parameters.
| How to test a function that deals with setting file ownership without being root | I wrote a function that copies the /etc/skel directory on a linux machine during a "create new user" RPC call. Now, there is quite a few things about this I want to test, for example the files in /etc/skel and the targets of symlinks should not have changed permissions afterwards, whereas the copied files including the actual symlinks should have a changed owner. Now, i can create my test directory and files using mkdtemp and stuff, but I can't chown those to another user without root privileges. How would you write a test for this?
| [
"You could make an object which does the chmod, and inject a mock when testing. This mock would not really do the chmod, but make it possible to test if it was called with the right parameters.\n"
] | [
2
] | [] | [] | [
"linux",
"python",
"testing"
] | stackoverflow_0003155748_linux_python_testing.txt |
Q:
XML instance generation from XML schema (xsd)
I was wondering if there's a way I can automate the generation of XML files from XSD schemas given that I have the data and the labels. I'd like to do this in python/java. It seems very possible, yet I can't find any library that allows me to do this. I'm looking for a fairly quick solution..
Any ideas?
See also: how-to-generate-sample-xml-documents-from-their-dtd-or-xsd
A:
Look at pyXSD for Python tools that are similar to JAXB.
XSD's are used to create Python classes. Python objects are used to emit XML.
A:
Microsoft has published a "document generator" tool as a sample. This is an article that describes the architecture and operation of the sample app in some detail.
If you just want to use the document generation tool, click here and install the MSI. It requires no programming.
It's free. The source is available. Requires the .NET Framework to run. Works only with XSDs. (not Relax NG or DTD).
A:
I recommend two approaches:
Xstream - it let's you generate XML files by defining a Java file and either putting Java annotations on the items or just defining aliases. It is very easy, but it is not fully automatic;
XMLBeans - these tools let's you generate Java files from XML schema definitions (xsd) so that you can import, manipulate, create and export XML files using JavaBeans-like method calls.
Regards,
Luis
A:
JAXB works fantastic for generating classes from xsd.
Ibatis works fantastic for getting data into classes.
You can use Ibatis to feed data and automatically create classes, then use JAXB to marshal the classes into an XML file! Mind you, that's a lot of effort if you're not going to be doing it over and over again.
A:
I use Exchanger XML Editor for this purpose. You can download it for free for multiple operating systems at: http://www.exchangerxml.com/
The option is in menu "Schema" -> "Schema instance generation".
| XML instance generation from XML schema (xsd) | I was wondering if there's a way I can automate the generation of XML files from XSD schemas given that I have the data and the labels. I'd like to do this in python/java. It seems very possible, yet I can't find any library that allows me to do this. I'm looking for a fairly quick solution..
Any ideas?
See also: how-to-generate-sample-xml-documents-from-their-dtd-or-xsd
| [
"Look at pyXSD for Python tools that are similar to JAXB.\nXSD's are used to create Python classes. Python objects are used to emit XML. \n",
"Microsoft has published a \"document generator\" tool as a sample. This is an article that describes the architecture and operation of the sample app in some detail. \nI... | [
8,
3,
2,
1,
0
] | [] | [] | [
"java",
"python",
"xml",
"xsd"
] | stackoverflow_0000307616_java_python_xml_xsd.txt |
Q:
python for loop range(bigint)
In Python, is there some short way to do something like
"for i in range(n)"
when n is too big for Python to actually create the array range(n)?
(short because otherwise I'd just use a while loop)
A:
You could use xrange()... although that is restricted to "short" integers in CPython:
CPython implementation detail:
xrange() is intended to be simple and
fast. Implementations may impose
restrictions to achieve this. The C
implementation of Python restricts all
arguments to native C longs (“short”
Python integers), and also requires
that the number of elements fit in a
native C long. If a larger range is
needed, an alternate version can be
crafted using the itertools module:
takewhile(lambda x: x<stop,
(start+i*step for i in count())).
I don't know whether that restriction also applies to other implementations (or which ones) - but there's a workaround listed...
I know you mention bigint in your question title, but the question body talks about the number being too big to create the array - I suspect there are plenty of numbers which are small enough for xrange to work, but big enough to cause you memory headaches with range.
A:
I would use a generator function: example forthcoming.
def gen():
i = 0
while 1: # or your special terminating logic
yield i
i = i + 1
for j in gen():
do stuff
A:
You could upgrade to python3. There, range isn't limited to 'short' integers.
Another workaround would be to use xrange for small integers and add them to some constant inside the loop, e.g.
offset, upperlimit = 2**65, 2**65+100
for i in xrange(upperlimit-offset):
j = i + offset
# ... do something with j
A:
you should always use xrange rather than range for just looping n times over sth., but keep in mind that xrange has also a limit (if it is too small you need to do your own while loop with a counter)
EDIT: too late...
| python for loop range(bigint) | In Python, is there some short way to do something like
"for i in range(n)"
when n is too big for Python to actually create the array range(n)?
(short because otherwise I'd just use a while loop)
| [
"You could use xrange()... although that is restricted to \"short\" integers in CPython:\n\nCPython implementation detail:\n xrange() is intended to be simple and\n fast. Implementations may impose\n restrictions to achieve this. The C\n implementation of Python restricts all\n arguments to native C longs (“sh... | [
5,
3,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003155441_python.txt |
Q:
Any way to improve this python function?
def __number():
# This line returns the number of the latest created object
# as a "Factura" object in format "n/year"
last = Factura.objects.filter(f_type__exact=False).latest('number')
# We convert it into a string and split it to get only the first number
spl = str(last).split('/')[0]
# Convert it into integer so we can do math
n = int(spl)
# Get the current year
y = date.today().strftime('%y')
# If none return 1/year
if n == None:
return str(1) + '/' + str(y)
# Else we increment the number in one.
else:
n = n + 1
return str(n) + '/' + str(y)
What it does: It autogenerates a number in the format '1/year' '2/year' etc. If the user introduces other number, p.e. 564/10 the function follows it and the next will be 565/10.
Even if the user introduces p.e. 34/10 after the entry with 564/10 the function will follow the largest number.
Did I do this right or there's a better way to do it?
Update:
def __number():
current_year = date.today().strftime('%y')
try:
facturas_emmited = Factura.objects.filter(f_type__exact=False)
latest_object = facturas_emmited.latest('number').__str__()
first_number = int(latest_object.split("/")[0]) + 1
except Factura.DoesNotExist:
first_number = 1
return '%s/%s' % (first_number, current_year)
A:
This is really just the beginning, but I'd start by replacing some comments with self-documenting code.
def __number():
# "Factura" object in format "n/year"
latest_object = Factura.objects.filter(f_type__exact=False).latest('number')
# Better name can be available if you explain why the first number is important and what it means
# Do Factura objects not have a __repr__ or __str__ method that you must cast it?
first_number = int(str(latest_object).split('/')[0])
current_year = date.today().strftime('%y')
# Use "is None" rather than "== None"
if first_number is None:
return '1/%d' % current_year
# No else needed because of return above
# Why do we add 1 to first number? Comments should explain _why_, not how
return '%d/%d' % (first_number + 1, current_year)
A:
Can last be None? If so it would be good to check for that:
# get last as before
if last:
n = int(str(last).split("/")[0]) + 1
else:
n = 1
# get y as before
return str(n) + "/" + str(y)
Another improvement here is that you only build the result string in one place.
I don't know what the Factura object is, but can you not get the value of n by calling some method on it? This would be better than converting it to a string, splitting it and taking the last part.
A:
I solved similar problem some time ago by using object.id/year (where object/id is database id).
It guarantees that this will be unique, autoincremented (you don't need to do n = n + 1, which theoretically can lead to duplicate values in a db).
You can do this by overriding save method and only trick is that you need first to save an object (id is assigned) and then create id/year number and save again (maybe there is better way to do this than double save).
def save(self, force_insert = False, force_update = False):
super(Factura, self).save(force_insert, force_update)
current_year = date.today().strftime('%y')
self.identifier = '%s/%s'%(self.id, current_year)
super(Factura, self).save(force_insert, force_update)
| Any way to improve this python function? | def __number():
# This line returns the number of the latest created object
# as a "Factura" object in format "n/year"
last = Factura.objects.filter(f_type__exact=False).latest('number')
# We convert it into a string and split it to get only the first number
spl = str(last).split('/')[0]
# Convert it into integer so we can do math
n = int(spl)
# Get the current year
y = date.today().strftime('%y')
# If none return 1/year
if n == None:
return str(1) + '/' + str(y)
# Else we increment the number in one.
else:
n = n + 1
return str(n) + '/' + str(y)
What it does: It autogenerates a number in the format '1/year' '2/year' etc. If the user introduces other number, p.e. 564/10 the function follows it and the next will be 565/10.
Even if the user introduces p.e. 34/10 after the entry with 564/10 the function will follow the largest number.
Did I do this right or there's a better way to do it?
Update:
def __number():
current_year = date.today().strftime('%y')
try:
facturas_emmited = Factura.objects.filter(f_type__exact=False)
latest_object = facturas_emmited.latest('number').__str__()
first_number = int(latest_object.split("/")[0]) + 1
except Factura.DoesNotExist:
first_number = 1
return '%s/%s' % (first_number, current_year)
| [
"This is really just the beginning, but I'd start by replacing some comments with self-documenting code.\ndef __number():\n # \"Factura\" object in format \"n/year\"\n latest_object = Factura.objects.filter(f_type__exact=False).latest('number')\n\n # Better name can be available if you explain why the firs... | [
2,
1,
0
] | [] | [] | [
"django",
"function",
"python"
] | stackoverflow_0003152913_django_function_python.txt |
Q:
Global Exception Handling in Google App Engine
Instead of encapsulating my entire code in a try{} except{} block, is there someway of catching exceptions globally?
Basically I am looking for a way to have a global exception handler which will handle all unhandled exceptions in the my python application written for google app engine
A:
If you're using the webapp framework, you should already be defining a subclass of RequestHandler that serves as a base class, with all your app's handlers extending that. You can simply override handle_exception, which serves as a global exception handler for any uncaught exceptions.
The default implementation calls self.error(500), logs the exception, and if debug is on, outputs a stacktrace.
If you're using another framework, you could write a piece of WSGI middleware that calls the wrapped WSGI app, and catches any thrown exceptions, dealing with them as you wish.
A:
Well, at the most basic level you could wrap all of your handler scripts referenced by app.yaml in a giant try-except block.
If you are using the webapp framework, consider overriding handle_exception() for each of your request handlers. If you want all of your request handlers to have some basic exception handling that you specify, you could a request handler which implements this method and then derive all of your handlers from it.
A:
You application probably has a main() function, put the try/except in that function, and it'll catch everything from your application.
| Global Exception Handling in Google App Engine | Instead of encapsulating my entire code in a try{} except{} block, is there someway of catching exceptions globally?
Basically I am looking for a way to have a global exception handler which will handle all unhandled exceptions in the my python application written for google app engine
| [
"If you're using the webapp framework, you should already be defining a subclass of RequestHandler that serves as a base class, with all your app's handlers extending that. You can simply override handle_exception, which serves as a global exception handler for any uncaught exceptions.\nThe default implementation c... | [
1,
0,
0
] | [] | [] | [
"exception_handling",
"global",
"google_app_engine",
"python"
] | stackoverflow_0003154900_exception_handling_global_google_app_engine_python.txt |
Q:
Filtering treeview content recursively
I have GUI application with gtk.Treeview component. It's model is set to gtk.Treestore, which I fill with a hierarchical structure. Everything is working fine - the treeview is what I expect it to be.
Now I'd like to filter the leaf nodes to contain only a given string. I tried creating model filter like this:
self.modelfilter = treestore.filter_new()
self.modelfilter.set_visible_func(self.visible_cb, self.txt)
and define filtering function like the one below (self.txt is the text i'm filtering):
def visible_cb(self, model, iter, data):
return self.txt.lower() in model.get_value(iter, 0).lower()
Unfortunately this approach is not a good one because filtering is done on all nodes, and not only leafs.
Is there an elegant solution for this problem in GTK?
A:
I've never used the toolkit, but after browsing through the api docs... wouldn't the following work?
def visible_cb(self, model, iter, data):
return model.iter_has_child(iter) or data.lower() in model.get_value(iter, 0).lower()
Not sure why you're passing self.txt to set_visible_func and not using the corresponding data argument to visible_cb.
| Filtering treeview content recursively | I have GUI application with gtk.Treeview component. It's model is set to gtk.Treestore, which I fill with a hierarchical structure. Everything is working fine - the treeview is what I expect it to be.
Now I'd like to filter the leaf nodes to contain only a given string. I tried creating model filter like this:
self.modelfilter = treestore.filter_new()
self.modelfilter.set_visible_func(self.visible_cb, self.txt)
and define filtering function like the one below (self.txt is the text i'm filtering):
def visible_cb(self, model, iter, data):
return self.txt.lower() in model.get_value(iter, 0).lower()
Unfortunately this approach is not a good one because filtering is done on all nodes, and not only leafs.
Is there an elegant solution for this problem in GTK?
| [
"I've never used the toolkit, but after browsing through the api docs... wouldn't the following work?\ndef visible_cb(self, model, iter, data):\n return model.iter_has_child(iter) or data.lower() in model.get_value(iter, 0).lower()\n\nNot sure why you're passing self.txt to set_visible_func and not using the cor... | [
1
] | [] | [] | [
"gtk",
"python",
"user_interface"
] | stackoverflow_0003155842_gtk_python_user_interface.txt |
Q:
What should itertools.product() yield when supplied an empty list?
I guess it's an academic question, but the second result does not make sense to me. Shouldn't it be as thoroughly empty as the first? What is the rationale for this behavior?
from itertools import product
one_empty = [ [1,2], [] ]
all_empty = []
print [ t for t in product(*one_empty) ] # []
print [ t for t in product(*all_empty) ] # [()]
Updates
Thanks for all of the answers -- very informative.
Wikipedia's discussion of the Nullary Cartesian Product provides a definitive statement:
The Cartesian product of no sets ...
is the singleton set containing the
empty tuple.
And here is some code you can use to work through the insightful answer from sth:
from itertools import product
def tproduct(*xss):
return ( sum(rs, ()) for rs in product(*xss) )
def tup(x):
return (x,)
xs = [ [1, 2], [3, 4, 5] ]
ys = [ ['a', 'b'], ['c', 'd', 'e'] ]
txs = [ map(tup, x) for x in xs ] # [[(1,), (2,)], [(3,), (4,), (5,)]]
tys = [ map(tup, y) for y in ys ] # [[('a',), ('b',)], [('c',), ('d',), ('e',)]]
a = [ p for p in tproduct( *(txs + tys) ) ]
b = [ p for p in tproduct( tproduct(*txs), tproduct(*tys) ) ]
assert a == b
A:
From a mathematical point of view the product over no elements should yield the neutral element of the operation product, whatever that is.
For example on integers the neutral element of multiplication is 1, since 1 ⋅ a = a for all integers a. So an empty product of integers should be 1. When implementing a python function that returns the product of a list of numbers, this happens naturally:
def iproduct(lst):
result = 1
for i in lst:
result *= i
return result
For the correct result to be calculated with this algorithm, result needs to be initialized with 1. This leads to a return value of 1 when the function is called on an empty list.
This return value is also very reasonable for the purpose of the function. With a good product function it shouldn't matter if you first concat two lists and then build the product of the elements, or if you first build the product of both individual lists and then multiply the results:
iproduct(xs + ys) == iproduct(xs) * iproduct(ys)
If xs or ys is empty that only works if iproduct([]) == 1.
Now the more complicated product() on iterators. Here also, from a mathematical point of view, product([]) should return the neutral element of that operation, whatever that is. It is not [] since product([], xs) == [], while for the neutral elements product([], xs) == xs should hold. It turns out, though, that [()] also isn't a neutral element:
>>> list(product([()], [1,2,3]))
[((), 1), ((), 2), ((), 3)]
In fact, product() is not really a very nice mathematical product at all, since this above equation doesn't hold:
product(*(xs + ys)) != product(product(*xs), product(*ys))
Each application of product generates an additional layer of tuples and there is no way around that, so there can't even be a real neutral element. [()] comes pretty close though, it doesn't add or remove any elements, it just adds an empty tuple to each.
[()]would in fact be the neutral element of this slightly adapted product function that only operates on lists of tuples, but doesn't add additional tuple layers on each application:
def tproduct(*xss):
# the parameters have to be lists of tuples
return (sum(rs, ()) for rs in product(*xss))
For this function the above product equation holds:
def tup(x): return (x,)
txs = [map(tup, x) for x in xs]
tys = [map(tup, y) for y in ys]
tproduct(*(txs + tys)) == tproduct(tproduct(*txs), tproduct(*tys))
With the additional preprocessing step of packing the input lists into tuples, tproduct() gives the same result as product(), but behaves nicer from a mathematical point of view. Also its neutral element is [()],
So [()] makes some sense as the neutral element of this kind of list multiplication. Even if it doesn't exactly fit product() it is a good choice for this function since it for example allows to define tproduct() without the need to introduce a special case for empty input.
A:
As @sth already indicated, this behaviour is correct from a mathematical viewpoint. All you really need to convince yourself of is that list(itertools.product()) should have exactly one element, since once you know that it's clear what that element should be: it's got to be (for consistency) a tuple of length 0, and there's only one of those.
But the number of elements of itertools.product(l1, l2, l3, ...) should just be the product of the lengths of l1, l2, l3, ... . So the number of elements of itertools.product() should be the size of the empty product, and there's no shortage of internet sources that should persuade you that the empty product is 1.
I just wanted to point out that this is the correct practical definition as well as the correct mathematical one; that is, it's the definition that's most likely to 'just work' in boundary cases. For an example, suppose that you want to generate all strings of length n consisting of decimal digits, with the first digit nonzero. You might do something like:
import itertools
def decimal_strings(n):
"""Generate all digit strings of length n that don't start with 0."""
for lead_digit in '123456789':
for tail in itertools.product('0123456789', repeat=n-1):
yield lead_digit + ''.join(tail)
What should this produce when n = 1? Well, in that case, you end up calling itertools.product with an empty product (repeat = 0). If it returned nothing, then the body of the inner for loop above would never be executed, so decimal_strings(1) would be an empty iterator; almost certainly not what you want. But since itertools.product('0123456789', repeat=0) returns a single tuple, you get the expected result:
>>> list(decimal_strings(1))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
(When n = 0, of course, this function correctly raises a ValueError.)
So in short, the definition is mathematically sound, and more often that not it's also what you want. It's definitely not a Python bug!
| What should itertools.product() yield when supplied an empty list? | I guess it's an academic question, but the second result does not make sense to me. Shouldn't it be as thoroughly empty as the first? What is the rationale for this behavior?
from itertools import product
one_empty = [ [1,2], [] ]
all_empty = []
print [ t for t in product(*one_empty) ] # []
print [ t for t in product(*all_empty) ] # [()]
Updates
Thanks for all of the answers -- very informative.
Wikipedia's discussion of the Nullary Cartesian Product provides a definitive statement:
The Cartesian product of no sets ...
is the singleton set containing the
empty tuple.
And here is some code you can use to work through the insightful answer from sth:
from itertools import product
def tproduct(*xss):
return ( sum(rs, ()) for rs in product(*xss) )
def tup(x):
return (x,)
xs = [ [1, 2], [3, 4, 5] ]
ys = [ ['a', 'b'], ['c', 'd', 'e'] ]
txs = [ map(tup, x) for x in xs ] # [[(1,), (2,)], [(3,), (4,), (5,)]]
tys = [ map(tup, y) for y in ys ] # [[('a',), ('b',)], [('c',), ('d',), ('e',)]]
a = [ p for p in tproduct( *(txs + tys) ) ]
b = [ p for p in tproduct( tproduct(*txs), tproduct(*tys) ) ]
assert a == b
| [
"From a mathematical point of view the product over no elements should yield the neutral element of the operation product, whatever that is.\nFor example on integers the neutral element of multiplication is 1, since 1 ⋅ a = a for all integers a. So an empty product of integers should be 1. When implementing a pytho... | [
11,
4
] | [] | [] | [
"cross_product",
"python",
"python_itertools"
] | stackoverflow_0003154301_cross_product_python_python_itertools.txt |
Q:
os.chdir(path) not working as expected due to path formatting in Python 2.6.5?
I cannot os.chdir(path) in Python 2.6.5 under WindowsXP SP2. It works fine under CygWin and MAC OS X, but for WinXP regardless of path format, I always get this error:
AttributeError: 'str' object has no attribute 'chdir'.
I thought it was the problem with format of path but after trying r"C:\WINDOWS", 'C:\WINDOWS' and combinations of \\, / or even "\"C:\Windows\"", I gave up. With formatting I'm using os.path.exists(path) works perfectly fine...
What I am missing here? What should I be aware of when working with paths consisting of white spaces?
Cheers,
Martin
A:
It seems that problem is that in some place you redefine 'os'. Somewhere in your code you do something like this:
import os
os = 'some string'
| os.chdir(path) not working as expected due to path formatting in Python 2.6.5? | I cannot os.chdir(path) in Python 2.6.5 under WindowsXP SP2. It works fine under CygWin and MAC OS X, but for WinXP regardless of path format, I always get this error:
AttributeError: 'str' object has no attribute 'chdir'.
I thought it was the problem with format of path but after trying r"C:\WINDOWS", 'C:\WINDOWS' and combinations of \\, / or even "\"C:\Windows\"", I gave up. With formatting I'm using os.path.exists(path) works perfectly fine...
What I am missing here? What should I be aware of when working with paths consisting of white spaces?
Cheers,
Martin
| [
"It seems that problem is that in some place you redefine 'os'. Somewhere in your code you do something like this:\nimport os\nos = 'some string'\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0003156314_python.txt |
Q:
How to broadcast to ALL subscribers w/identical queue name/routing key vals on a direct exchange
Consider a tier of N-many subscribers, all connected to a direct exchange using identical queue name and routing key values. This creates a load-balanced system where an inbound message is send round-robin to 1 of the subscribers. This works very well for dealing with scale-out issues as more subscribers can be added as load increases and can later be withdrawn if necessary.
Now consider the requirement of being able to send messages to ALL subscribers in that tier, without knowing how many there are (for example a "reset your state" or "shutdown now please" administrative message). Is there any way to do this in rabbitmq? If this isn't possible, is there a better approach?
My environment is Python using amqplib.
A:
If I understand correctly, this is your setup:
you have a producer publishing to a direct exchange;
you have a queue bound to that exchange;
you have many subscribers, all consuming from the above queue.
This works perfectly for sending a message to an arbitrary subscriber (thus sort-of load balancing), but you want to be able to send some messages to ALL the subscribers.
You could do this with a fanout exchange and an extra queue for each subscriber:
your producer publishes system-wide messages to a fanout exchange;
there's a queue for each subscriber bound to that exchange;
each subscriber first attempts to consume from this queue; if it doesn't succeed, it tries to consume from the common queue you currently use.
| How to broadcast to ALL subscribers w/identical queue name/routing key vals on a direct exchange | Consider a tier of N-many subscribers, all connected to a direct exchange using identical queue name and routing key values. This creates a load-balanced system where an inbound message is send round-robin to 1 of the subscribers. This works very well for dealing with scale-out issues as more subscribers can be added as load increases and can later be withdrawn if necessary.
Now consider the requirement of being able to send messages to ALL subscribers in that tier, without knowing how many there are (for example a "reset your state" or "shutdown now please" administrative message). Is there any way to do this in rabbitmq? If this isn't possible, is there a better approach?
My environment is Python using amqplib.
| [
"If I understand correctly, this is your setup:\n\nyou have a producer publishing to a direct exchange;\nyou have a queue bound to that exchange;\nyou have many subscribers, all consuming from the above queue.\n\nThis works perfectly for sending a message to an arbitrary subscriber (thus sort-of load balancing), bu... | [
2
] | [] | [] | [
"python",
"rabbitmq"
] | stackoverflow_0003151989_python_rabbitmq.txt |
Q:
how do I set a value for a ShapeKey in Blender Python?
I've managed to insert Shape Keys from Python using:
ob = Scene.GetCurrent().object.active;
if(ob.activeShape == 0):
ob.insertShapeKey()
ob.insertShapeKey()
Now how do I change a key value ?
A:
Ok here's how I did it:
#get the key
k = ob.getData().getKey()
#create a new Ipo
ni = Ipo.New('Key','ni')
#if there check if there already a key by that name, otherwise add key
if(k.ipo['Key 1'] == None): k.ipo.addCurve('Key 1')
#add a point to the 'Key 1' ipo curve
k.ipo['Key 1'].append(BezTriple.New(6.0,0.8,0.1))
And that's about it.
The first ShapeKey inserted creates 'Basis', then keys are added,
'Key 1' is the default name
| how do I set a value for a ShapeKey in Blender Python? | I've managed to insert Shape Keys from Python using:
ob = Scene.GetCurrent().object.active;
if(ob.activeShape == 0):
ob.insertShapeKey()
ob.insertShapeKey()
Now how do I change a key value ?
| [
"Ok here's how I did it:\n#get the key\nk = ob.getData().getKey()\n#create a new Ipo\nni = Ipo.New('Key','ni')\n#if there check if there already a key by that name, otherwise add key\nif(k.ipo['Key 1'] == None): k.ipo.addCurve('Key 1')\n#add a point to the 'Key 1' ipo curve\nk.ipo['Key 1'].append(BezTriple.New(6.... | [
0
] | [] | [] | [
"3d",
"blender",
"bpy",
"bpython",
"python"
] | stackoverflow_0003104908_3d_blender_bpy_bpython_python.txt |
Q:
Is IronPython usable as a replacement for CPython?
Has IronPython gotten to a point where you can just drop it in as a replacement for CPython?
To clarify: I mean can IronPython run applications originally written for CPython (no .NET involved, of course)
A:
Yes, pretty much, at least on Windows with "real" (Microsoft) .NET underneath. If you're depending on C-coded extensions, chances are that ironclad can bail you out; you get 2.6 support, just about every CPython standard library or third-party extension module (maybe not trivial for those coded in Fortran, or C++, but that's a minority), plus of course every .NET module on the planet -- not a bad tradeoff!
How well this works with Mono on MacOSX or Linux is a different issue...
A:
It has been tested to work well with mono on Linux and I use it regularly to open up opportunities to use - as Alex Martelli so eloquently put it - "every .NET module on the planet".
I have faced some troubles in accessing third party extension modules, but that has pretty much always been a path issue, which is easy to correct.
I don't know how well this works on a Mac, though.
| Is IronPython usable as a replacement for CPython? | Has IronPython gotten to a point where you can just drop it in as a replacement for CPython?
To clarify: I mean can IronPython run applications originally written for CPython (no .NET involved, of course)
| [
"Yes, pretty much, at least on Windows with \"real\" (Microsoft) .NET underneath. If you're depending on C-coded extensions, chances are that ironclad can bail you out; you get 2.6 support, just about every CPython standard library or third-party extension module (maybe not trivial for those coded in Fortran, or C... | [
8,
3
] | [
"Ironpython have some prolbems to replace the cpython,like\nBase on cpy, you can use some libs directly, but, in ipy, you must use ironclad, and the effiencency is insufferable.\nAnd, if you want use py files, there will be many errors, even if you use same gramma.\nSo, there are two different things, only same gra... | [
-1
] | [
"cpython",
"dynamic_language_runtime",
"ironpython",
"python"
] | stackoverflow_0001905023_cpython_dynamic_language_runtime_ironpython_python.txt |
Q:
Python, unittest: Can one make the TestRunner completely quiet?
Is there a way to make unittest.TextTestRunner completely quiet, meaning it never prints to output on its own? Even at verbosity=0 it prints results when done.
I want to process the TestResult object returned by the runner before anything is printed.
A:
TextTestRunner has a stream=sys.stderr in its constructor:
def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1)
Change it to a null stream.
result = unittest.TextTestRunner(stream = open(os.devnull, 'w')).run(alltests)
if len(result.failures) or len(result.errors):
print "Sorry."
| Python, unittest: Can one make the TestRunner completely quiet? | Is there a way to make unittest.TextTestRunner completely quiet, meaning it never prints to output on its own? Even at verbosity=0 it prints results when done.
I want to process the TestResult object returned by the runner before anything is printed.
| [
"TextTestRunner has a stream=sys.stderr in its constructor:\ndef __init__(self, stream=sys.stderr, descriptions=1, verbosity=1)\n\nChange it to a null stream. \nresult = unittest.TextTestRunner(stream = open(os.devnull, 'w')).run(alltests)\nif len(result.failures) or len(result.errors):\n print \"Sorry.\"\n\n"
] | [
8
] | [] | [] | [
"python",
"unit_testing",
"verbosity"
] | stackoverflow_0003157456_python_unit_testing_verbosity.txt |
Q:
What can be the use of SymbolType in Python?
Here's the SymbolType package that adds symbols to Python. Can those who have done anything useful with Lisp/Scheme tell me what how can I take advantage of this type in Python?
Can it be used to isolate strings coming from outside (from the web) from internal code?
$ sudo easy_install SymbolType
$ ipython
Unfortunately, you can't use symbols to pass values as kwargs:
In [7]: X = s('X', __name__)
In [9]: a = {X: 10}
In [12]: Y = s('Y', __name__)
In [13]: a.update({Y: 20})
In [14]: a
Out[14]: {X: 10, Y: 20}
In [15]: for (k, v) in a.items():
....: print k, v
Y 20
X 10
In [16]: def z(X=0,Y=1):
....: print X, Y
....:
In [17]: z(**a)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
...<ipython console> in <module>()
TypeError: z() keywords must be strings
A:
Symbols are not a replacement for strings. While both are represented by a
sequence of characters, a symbol shouldn't be used in place of a string when
this is the dominant property. Symbols represent a unique identity.
This means that pointer equality
(instead of content equality) can be used to compare them.
For this reason, symbols are often used as constants, enumeration elements, hash table keys
or identifiers (in lisp).
In Lisp, the first time you reference a symbol, a corresponding entry in the
symbol table is created. If the same symbol is referenced thereafter,
it will be looked up and represent the same value.
I'm not a Python programmer, but since symbols are not built into
the Python language, their use may be limited or not very convenient.
You shouldn't use them for isolating strings. Use a wrapper class for that.
Edit: reading through the SymbolType docs, i saw that they bundle the originating
namespace (through __name__). Common Lisp does that, too. One might be able to use this
facility in some fashion.
Also read this question.
| What can be the use of SymbolType in Python? | Here's the SymbolType package that adds symbols to Python. Can those who have done anything useful with Lisp/Scheme tell me what how can I take advantage of this type in Python?
Can it be used to isolate strings coming from outside (from the web) from internal code?
$ sudo easy_install SymbolType
$ ipython
Unfortunately, you can't use symbols to pass values as kwargs:
In [7]: X = s('X', __name__)
In [9]: a = {X: 10}
In [12]: Y = s('Y', __name__)
In [13]: a.update({Y: 20})
In [14]: a
Out[14]: {X: 10, Y: 20}
In [15]: for (k, v) in a.items():
....: print k, v
Y 20
X 10
In [16]: def z(X=0,Y=1):
....: print X, Y
....:
In [17]: z(**a)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
...<ipython console> in <module>()
TypeError: z() keywords must be strings
| [
"Symbols are not a replacement for strings. While both are represented by a \nsequence of characters, a symbol shouldn't be used in place of a string when\nthis is the dominant property. Symbols represent a unique identity. \nThis means that pointer equality\n(instead of content equality) can be used to compare the... | [
3
] | [] | [] | [
"lisp",
"python",
"scheme",
"symbols",
"types"
] | stackoverflow_0003123935_lisp_python_scheme_symbols_types.txt |
Q:
setuptools easyinstall mysql-python-1.2.3
I have read a bunch of threads on setuptools here.
A lot of people seem not to like it very much.
But I need to install MySQL-python-1.2.3. and when I do that I get this error:
MySQL-python-1.2.3 X$ python setup.py cleanTraceback (most recent call last):
File "setup.py", line 5, in <module>
from setuptools import setup, Extension
ImportError: No module named setuptools
So it seems I need setuptools and that it is assumed that it is installed.
On the setuptools python homepage it says:
Setuptools will install itself using the matching version of Python (e.g. python2.4), and will place the easy_install executable in the default location for installing Python scripts (as determined by the standard distutils configuration files, or by the Python installation).
Does this mean it will replace any default easy install from python?
If so I dont want to use it.
If so can I install MySQL-python-1.2.3 without setupttools?
Thanks
A:
You should use virtualenv and pip.
Virtualenv automatically creates a setuptools version within the new environment, so the default one is intact.
You may want to read how the packaging and installing works: 1, 2
| setuptools easyinstall mysql-python-1.2.3 | I have read a bunch of threads on setuptools here.
A lot of people seem not to like it very much.
But I need to install MySQL-python-1.2.3. and when I do that I get this error:
MySQL-python-1.2.3 X$ python setup.py cleanTraceback (most recent call last):
File "setup.py", line 5, in <module>
from setuptools import setup, Extension
ImportError: No module named setuptools
So it seems I need setuptools and that it is assumed that it is installed.
On the setuptools python homepage it says:
Setuptools will install itself using the matching version of Python (e.g. python2.4), and will place the easy_install executable in the default location for installing Python scripts (as determined by the standard distutils configuration files, or by the Python installation).
Does this mean it will replace any default easy install from python?
If so I dont want to use it.
If so can I install MySQL-python-1.2.3 without setupttools?
Thanks
| [
"You should use virtualenv and pip.\nVirtualenv automatically creates a setuptools version within the new environment, so the default one is intact.\nYou may want to read how the packaging and installing works: 1, 2\n"
] | [
0
] | [] | [] | [
"mysql",
"mysql_python",
"python",
"setuptools"
] | stackoverflow_0003156337_mysql_mysql_python_python_setuptools.txt |
Q:
Integration testing in python, suggested tools and practices?
I've some hard time understanding Integration testing in general, I want to do some integration testing in python expecially for network programming in twisted (but I want to know something more in general).
There are any good resource I must read, and tools (python tools if possible), practices that introduces me in integration testing?
A:
The recent Pycon had many talks on testing. All of the videos are available on Vimeo and the slides can be downloaded.: http://us.pycon.org/2010/conference/talks/?filter=testing
Specifically, I recommend the talk by Ned Batchelder. The other ones are probably good too. (altho' I haven't seen them)
| Integration testing in python, suggested tools and practices? | I've some hard time understanding Integration testing in general, I want to do some integration testing in python expecially for network programming in twisted (but I want to know something more in general).
There are any good resource I must read, and tools (python tools if possible), practices that introduces me in integration testing?
| [
"The recent Pycon had many talks on testing. All of the videos are available on Vimeo and the slides can be downloaded.: http://us.pycon.org/2010/conference/talks/?filter=testing\nSpecifically, I recommend the talk by Ned Batchelder. The other ones are probably good too. (altho' I haven't seen them)\n"
] | [
6
] | [] | [] | [
"integration_testing",
"python"
] | stackoverflow_0003156421_integration_testing_python.txt |
Q:
Upload a file with rest
I created a rest api using django and piston and I need to create a script that uploads a file to that api.
currently I'm using this code:
import urllib
import urllib2
user = 'patrick'
password = 'my_password'
url = 'http://localhost:8000/api/odl/'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(
None, url, user, password
)
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
f = open('test.pdf')
params = {
'name': 'ODL Name',
}
postData = urllib.urlencode(params)
fh = urllib2.urlopen(url, postData)
When I run this code I can see that params are sent to the api, but I don't know how to send the file (f) to the api :(
Can you help me?
Thanks
A:
You should include content of the file as a part of the POST data and modify the headers of the Request, to tell the server that there is a file in the post.
| Upload a file with rest | I created a rest api using django and piston and I need to create a script that uploads a file to that api.
currently I'm using this code:
import urllib
import urllib2
user = 'patrick'
password = 'my_password'
url = 'http://localhost:8000/api/odl/'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(
None, url, user, password
)
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
f = open('test.pdf')
params = {
'name': 'ODL Name',
}
postData = urllib.urlencode(params)
fh = urllib2.urlopen(url, postData)
When I run this code I can see that params are sent to the api, but I don't know how to send the file (f) to the api :(
Can you help me?
Thanks
| [
"You should include content of the file as a part of the POST data and modify the headers of the Request, to tell the server that there is a file in the post.\n"
] | [
1
] | [] | [] | [
"file_upload",
"python",
"rest",
"upload"
] | stackoverflow_0003157568_file_upload_python_rest_upload.txt |
Q:
ctypes initializing c_int array by reading file
Using a Python array, I can initialize a 32,487,834 integer array (found in a file HR.DAT) using the following (not perfectly Pythonic, of course) commands:
F = open('HR.DAT','rb')
HR = array('I',F.read())
F.close()
I need to do the same in ctypes. So far the best I have is:
HR = c_int * 32487834
I'm not sure how to initilize each element of the array using HR.DAT. Any thoughts?
Thanks,
Mike
A:
File objects have a 'readinto(..)' method that can be used to fill objects that support the buffer interface.
So, something like this should work:
f = open('hr.dat', 'rb')
array = (c_int * 32487834)()
f.readinto(array)
A:
Try something like this to convert array to ctypes array
>>> from array import array
>>> a = array("I")
>>> a.extend([1,2,3])
>>> from ctypes import c_int
>>> ca = (c_int*len(a))(*a)
>>> print ca[0], ca[1], ca[2]
1 2 3
| ctypes initializing c_int array by reading file | Using a Python array, I can initialize a 32,487,834 integer array (found in a file HR.DAT) using the following (not perfectly Pythonic, of course) commands:
F = open('HR.DAT','rb')
HR = array('I',F.read())
F.close()
I need to do the same in ctypes. So far the best I have is:
HR = c_int * 32487834
I'm not sure how to initilize each element of the array using HR.DAT. Any thoughts?
Thanks,
Mike
| [
"File objects have a 'readinto(..)' method that can be used to fill objects that support the buffer interface.\nSo, something like this should work:\nf = open('hr.dat', 'rb')\narray = (c_int * 32487834)()\nf.readinto(array)\n\n",
"Try something like this to convert array to ctypes array\n>>> from array import arr... | [
11,
1
] | [] | [] | [
"arrays",
"ctypes",
"initialization",
"python"
] | stackoverflow_0003154439_arrays_ctypes_initialization_python.txt |
Q:
What's the best library for video capture in Python on linux?
I want to write an application to video capture from web-cams in linux. Is there a python library to do that?
A:
You should look at Gstreamer and its Python bindings. Here http://pygstdocs.berlios.de/pygst-tutorial/webcam-viewer.html is some sample code to display video from a webcam. To record the video you would have to change the pipeline definition from autovideosink to an encoder and filesink.
A:
You could look into WebCamsPy, which appears to do what you are asking.
Also, see a related question, which asks more generally for windows and Linux but might still help you.
A:
OpenCV is the easiest thing I've seen. Take a look at this post:
http://www.jperla.com/blog/2007/09/26/capturing-frames-from-a-webcam-on-linux/
You can $ sudo apt-get install python-opencv (I believe), as well as pygame and PIL if you haven't already installed them. Once you have those libraries you can start viewing/saving images - technically if you just want to capture you don't need to use pygame, but it does allow you to also view the images. Technically speaking, the "meat" of the work is done with PIL and opencv, so you can use any type of graphical framework (gtk, tk, wx, qt, etc) that you're familiar with.
I've been trying to do something like this with mine, and I've been getting a crash course in PIL, and it's actually a pretty easy library to use, though I think I'll really need to include numpy for processing in that mix...
Anyway, opencv+PIL == super easy.
A:
If you have a favorite video capture C library, you can probably write a simple facade to it using the ctypes module.
A:
there is a lib called open-cv. Try that. It has a lot of features for handling images as well.
| What's the best library for video capture in Python on linux? | I want to write an application to video capture from web-cams in linux. Is there a python library to do that?
| [
"You should look at Gstreamer and its Python bindings. Here http://pygstdocs.berlios.de/pygst-tutorial/webcam-viewer.html is some sample code to display video from a webcam. To record the video you would have to change the pipeline definition from autovideosink to an encoder and filesink.\n",
"You could look into... | [
3,
1,
1,
0,
0
] | [] | [] | [
"linux",
"python",
"video_capture",
"webcam"
] | stackoverflow_0003155961_linux_python_video_capture_webcam.txt |
Q:
Python: concatenating bytes with a string
I'm working on a python project in 2.6 that also has future support for python 3 being worked in. Specifically I'm working on a digest-md5 algorithm.
In python 2.6 without running this import:
from __future__ import unicode_literals
I am able to write a piece of code such as this:
a1 = hashlib.md5("%s:%s:%s" % (self.username, self.domain, self.password)).digest()
a1 = "%s:%s:%s" %(a1, challenge["nonce"], cnonce )
Without any issues, my authentication works fine. When I try the same line of code with the unicode_literals imported I get an exception:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa8 in position 0: unexpected code byte
Now I'm relatively new to python so I'm a bit stuck in figuring this out. if I replace the %s in the formatting string as %r I am able to concatenate the string, but the authentication doesn't work. The digest-md5 spec that I had read says that the 16 octet binary digest must be appended to these other strings.
Any thoughts?
A:
The reason for the behaviour you observed is that from __future__ import unicode_literals switches the way Python works with strings:
In the 2.x series, strings without the u prefix are treated as sequences of bytes, each of which may be in the range \x00-\xff (inclusive). Strings with the u prefix are ucs-2 encoded unicode sequences.
In Python 3.x -- as well as in the unicode_literals future, strings without the u prefix are unicode strings encoded in either UCS-2 or UCS-4 (depends on the compiler flag used when compiling Python). Strings with the b prefix are literals for the data type bytes which are rather similar to pre-3.x non-unicode strings.
In either version of Python, byte-strings and unicode-strings must be converted. The conversion performed by default depends on your system's default charset; in your case this is UTF-8. Without setting anything, it should be ascii, which rejects all characters above \x7f.
The message digest returned by hashlib.md5(...).digest() is a bytes-string, and I suppose you want the result of the whole operation to be a byte-string as well. If you want that, convert the nonce and cnonce-strings to byte-strings.:
a1 = hashlib.md5("%s:%s:%s" % (self.username, self.domain, self.password)).digest()
# note that UTF-8 may not be the encoding required by your counterpart, please check
a1 = b"%s:%s:%s" %(a1, challenge["nonce"].encode("UTF-8"), cnonce.encode("UTF-8") )
Alternatively, you can convert the byte-string coming from the call to digest() to a unicode string (not recommended). As the lower 8 bit of UCS-2 are equivalent to ISO-8859-1, this might serve your needs:
a1 = hashlib.md5("%s:%s:%s" % (self.username, self.domain, self.password)).digest()
a1 = "%s:%s:%s" %(a1.decode("ISO-8859-1"), challenge["nonce"], cnonce)
A:
The problem is that "%s:%s:%s" became a unicode string once you imported unicode_literals.
The output of the hash is a "regular" string. Python tried to decode the regular string into a unicode string and failed (as expected. The hash output is supposed to look like noise).
Change your code to this:
a1 = a1 + str(':') + str(challenge["nonce"]) + str(':') + str(cnonce)
I'm assuming cnonce and challenge["nonce"] are regular strings. To have more control over their conversion to strings (if needed), use:
a1 += str(':') + challenge["nonce"].encode('UTF-8') + str(':') + cnonce.encode('UTF-8')
| Python: concatenating bytes with a string | I'm working on a python project in 2.6 that also has future support for python 3 being worked in. Specifically I'm working on a digest-md5 algorithm.
In python 2.6 without running this import:
from __future__ import unicode_literals
I am able to write a piece of code such as this:
a1 = hashlib.md5("%s:%s:%s" % (self.username, self.domain, self.password)).digest()
a1 = "%s:%s:%s" %(a1, challenge["nonce"], cnonce )
Without any issues, my authentication works fine. When I try the same line of code with the unicode_literals imported I get an exception:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa8 in position 0: unexpected code byte
Now I'm relatively new to python so I'm a bit stuck in figuring this out. if I replace the %s in the formatting string as %r I am able to concatenate the string, but the authentication doesn't work. The digest-md5 spec that I had read says that the 16 octet binary digest must be appended to these other strings.
Any thoughts?
| [
"The reason for the behaviour you observed is that from __future__ import unicode_literals switches the way Python works with strings:\n\nIn the 2.x series, strings without the u prefix are treated as sequences of bytes, each of which may be in the range \\x00-\\xff (inclusive). Strings with the u prefix are ucs-2 ... | [
8,
3
] | [] | [] | [
"md5",
"python",
"string"
] | stackoverflow_0003157529_md5_python_string.txt |
Q:
WxPython: deriving wx.ListItem but wx.ListCtrl only returns old class
I've got a small issue with derived classes, namely wx.ListItem with wx.ListCtrl. I succesfully derived wx.ListItem as a MediaItem, the code is not finished but you get the point:
class MediaItem(wx.ListItem):
def __init__ (self, fullname):
wx.ListItem.__init__(self)
self.fullname = fullname
self.filename = os.path.basename(fullname)
# snap...
def getFullname(self):
return self.fullname
wx.ListCtrl gladly accepts that because of Pythons duck philosophy. But now the problem is that using the method wx.ListCtrl.GetItem(index) returns a ListItem, not MediaItem. Python complained about wx.ListItem not having an attribute getFullname.
Casting objects seems to be the wrong way to approach the solution. This probably has nothing to do with the problem, but I paste the offending line as is as well:
filename = self.filelist.GetItem(event.GetIndex()).getFullname()
Where self.filelist is a wx.ListCtrl.
A:
I guess I should just suck it up, and regress to the suboptimal manual bookkeeping. When done tastefully, it's not a big deal but I had higher hopes for wxPython.
Supposedly (from what I searched and collected) the issue is with the proxy nature of wxPython class base. Were they written in pure Python, or I coded in C++, this would have worked well. But now the polymorphism of objects fails because of limitations in the design: the native C++ wx class won't get anything but a wx.ListItem and it will certainly only return a wx.ListItem back to wxPython.
My "solution" thus is to derive wx.ListCtrl instead of wx.ListItem, store needed information and control the appearances there.
| WxPython: deriving wx.ListItem but wx.ListCtrl only returns old class | I've got a small issue with derived classes, namely wx.ListItem with wx.ListCtrl. I succesfully derived wx.ListItem as a MediaItem, the code is not finished but you get the point:
class MediaItem(wx.ListItem):
def __init__ (self, fullname):
wx.ListItem.__init__(self)
self.fullname = fullname
self.filename = os.path.basename(fullname)
# snap...
def getFullname(self):
return self.fullname
wx.ListCtrl gladly accepts that because of Pythons duck philosophy. But now the problem is that using the method wx.ListCtrl.GetItem(index) returns a ListItem, not MediaItem. Python complained about wx.ListItem not having an attribute getFullname.
Casting objects seems to be the wrong way to approach the solution. This probably has nothing to do with the problem, but I paste the offending line as is as well:
filename = self.filelist.GetItem(event.GetIndex()).getFullname()
Where self.filelist is a wx.ListCtrl.
| [
"I guess I should just suck it up, and regress to the suboptimal manual bookkeeping. When done tastefully, it's not a big deal but I had higher hopes for wxPython.\nSupposedly (from what I searched and collected) the issue is with the proxy nature of wxPython class base. Were they written in pure Python, or I coded... | [
2
] | [] | [] | [
"listctrl",
"python",
"wxpython"
] | stackoverflow_0003152153_listctrl_python_wxpython.txt |
Q:
Django: ImageField disable image deletion
Greetings
Having an ImageField object in my Foo model as such:
class Foo(models.Model):
name = models.CharField(max_length=50)
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
I want Foo to disable to delete the uploaded photo once a Foo object is deleted and a specific . How can I do this?
Ie:
If self.name == "foo":
#skip deleting the image from the harddisk.
A:
the best thing is to write a custom File Storage:
http://docs.djangoproject.com/en/dev/howto/custom-file-storage/#howto-custom-file-storage
override the delete method and set it the like described in
http://docs.djangoproject.com/en/dev/topics/files/#the-built-in-filesystem-storage-class
| Django: ImageField disable image deletion | Greetings
Having an ImageField object in my Foo model as such:
class Foo(models.Model):
name = models.CharField(max_length=50)
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
I want Foo to disable to delete the uploaded photo once a Foo object is deleted and a specific . How can I do this?
Ie:
If self.name == "foo":
#skip deleting the image from the harddisk.
| [
"the best thing is to write a custom File Storage:\nhttp://docs.djangoproject.com/en/dev/howto/custom-file-storage/#howto-custom-file-storage\noverride the delete method and set it the like described in \nhttp://docs.djangoproject.com/en/dev/topics/files/#the-built-in-filesystem-storage-class\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003158272_django_django_models_python.txt |
Q:
Loop Java HashMap like Python Dictionary?
In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
A:
Yes - for example:
Map<String, String> map = new HashMap<String, String>();
// add entries to the map here
for (Map.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
System.out.printf("%s %s\n", k, v);
}
A:
The HashMap.entrySet() will return beans of key value pairs similar to the dictionary.iteritems(). You can then loop through them.
I think is the closest thing to the Python version.
A:
As shown in the answers, there are basically two ways to iterate over a Map (let's assume Map<String, String> in those examples).
Iterate over Map#entrySet():
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
Iterate over Map#keySet() and then use Map#get() to get the value for every key:
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
The second one is maybe more readable, but it has a performance cost of unnecessarily calling get() on every iteration. One may argument that creating the keyset iterator is less expensive because it doesn't need to take values into account. But believe it or not, the keySet().iterator() creates and uses the same iterator as entrySet().iterator(). The only difference is that in case of the keySet() the next() call of the iterator returns it.next().getKey() instead of it.next().
The AbstractMap#keySet()'s javadoc proves this:
The subclass's iterator method returns a "wrapper object" over this map's entrySet() iterator.
The AbstractMap source code also proves this. Here's an extract of keySet() method (somewhere around line 300 in Java 1.6):
public Iterator<K> iterator() {
return new Iterator<K>() {
private Iterator<Entry<K,V>> i = entrySet().iterator(); // <-----
public boolean hasNext() {
return i.hasNext();
}
public K next() {
return i.next().getKey(); // <-----
}
public void remove() {
i.remove();
}
};
}
Note that readability should be preferred over premature optimization, but it's important to have this in mind.
A:
Set<Map.Entry> set = d.entrySet();
for(Map.Entry i : set){
System.out.println(i.getKey().toString() + i.getValue().toString);
}
Something like that...
A:
In Java, you can do the same like the following.
HashMap<String, String> h = new HashMap<String, String>();
h.put("1","one");
h.put("2","two");
h.put("3","three");
for(String key:h.keySet()){
System.out.println("Key: "+ key + " Value: " + h.get(key));
}
| Loop Java HashMap like Python Dictionary? | In Python, you can have key,value pairs in a dictionary where you can loop through them, as shown below:
for k,v in d.iteritems():
print k,v
Is there a way to do this with Java HashMaps?
| [
"Yes - for example:\nMap<String, String> map = new HashMap<String, String>();\n// add entries to the map here\n\nfor (Map.Entry<String, String> entry : map.entrySet()) {\n String k = entry.getKey();\n String v = entry.getValue();\n System.out.printf(\"%s %s\\n\", k, v);\n}\n\n",
"The HashMap.entrySet() w... | [
21,
6,
6,
3,
1
] | [] | [] | [
"equivalent",
"hashmap",
"java",
"python"
] | stackoverflow_0003157558_equivalent_hashmap_java_python.txt |
Q:
Django formsets required
How to make all forms in django formset required? I tried to validate presence of all fields in cleaned_data overriding formset's clean() method but it just fails silently without any error displayed.
Thanks!
Source code:
class BaseScheduleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseScheduleForm, self).__init__(*args, **kwargs)
self.fields['day'].widget = forms.HiddenInput()
self.fields['user'].widget = forms.HiddenInput()
class Meta:
model = Schedule
def clean_end_time(self):
start_time = self.cleaned_data.get('start_time')
end_time = self.cleaned_data['end_time']
if start_time and end_time:
if end_time <= start_time:
raise forms.ValidationError("End time must be later that start time.")
return end_time
class BaseScheduleFormset(forms.models.BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(BaseScheduleFormset, self).__init__(*args, **kwargs)
for number, weekday in enumerate(WEEKDAYS):
self.forms[number].day_name = weekday[1]
def clean(self):
raise forms.ValidationError('You must specify schedule for the whole week')
ScheduleFormset = forms.models.modelformset_factory(Schedule, extra=7, max_num=7,
form=BaseScheduleForm, formset=BaseScheduleFormset)
There are 7 forms each for one day and all of them must be filled to be valid. In example above I just tried to raise error in clean. is_valid() became False, but no errors were displayed.
A:
It's a bit hard to understand where the errors are not being displayed.
If is_valid is False, then good, the validation it self is working. Then the next place to look is for the templating layer. How are you checking for errors? {{form.errors}} or {{somefield.errors}}.
The way the clean methods are setup here, their errors will not be associated with any fields, but should go in the all erros slot.
Cheers
A:
I had this same problem and figured out where these errors were stored by checking the source. When you override the clean method of a formset and raise a validation error the errors are stored in the non_form_errors property.
So in your template you would need to add the following assuming the template variable for formset is named 'formset':
{{ formset.non_form_errors }}
| Django formsets required | How to make all forms in django formset required? I tried to validate presence of all fields in cleaned_data overriding formset's clean() method but it just fails silently without any error displayed.
Thanks!
Source code:
class BaseScheduleForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(BaseScheduleForm, self).__init__(*args, **kwargs)
self.fields['day'].widget = forms.HiddenInput()
self.fields['user'].widget = forms.HiddenInput()
class Meta:
model = Schedule
def clean_end_time(self):
start_time = self.cleaned_data.get('start_time')
end_time = self.cleaned_data['end_time']
if start_time and end_time:
if end_time <= start_time:
raise forms.ValidationError("End time must be later that start time.")
return end_time
class BaseScheduleFormset(forms.models.BaseModelFormSet):
def __init__(self, *args, **kwargs):
super(BaseScheduleFormset, self).__init__(*args, **kwargs)
for number, weekday in enumerate(WEEKDAYS):
self.forms[number].day_name = weekday[1]
def clean(self):
raise forms.ValidationError('You must specify schedule for the whole week')
ScheduleFormset = forms.models.modelformset_factory(Schedule, extra=7, max_num=7,
form=BaseScheduleForm, formset=BaseScheduleFormset)
There are 7 forms each for one day and all of them must be filled to be valid. In example above I just tried to raise error in clean. is_valid() became False, but no errors were displayed.
| [
"It's a bit hard to understand where the errors are not being displayed.\nIf is_valid is False, then good, the validation it self is working. Then the next place to look is for the templating layer. How are you checking for errors? {{form.errors}} or {{somefield.errors}}.\nThe way the clean methods are setup here, ... | [
0,
0
] | [] | [] | [
"django",
"forms",
"formset",
"python"
] | stackoverflow_0001636923_django_forms_formset_python.txt |
Q:
Creating/making directories in python (complex)
I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No_Weights. Male and Female following. Within each of Male and Female folders, I have each ethnicity (Caucasian, African-American, Asian, Hispanic, Indo, Other, Unknown). Within each of those folders, I have age ranges from Below 20, all the way to 70+ (B20, 20, 30, 40, 50, 60, 70).
I have tried to generate all of the paths so all I would have to call is mkdir about 50 times, but that is about 150 lines of code (almost).
Is there any simple way to create all of these folders without having to do it by hand?
A:
import itertools
import os
dirs = [["Weights", "No_Weights"],
["Male", "Female"],
["Caucasian", "African-American", "Asian", "Hispanic", "Indo", "Other", "Unknown"],
["B20", "20", "30", "40", "50", "60", "70"]]
for item in itertools.product(*dirs):
os.makedirs(os.path.join(*item))
itertools.product() will construct all possible path variations, then os.path.join() will join the subpaths together using the correct syntax for your platform.
EDIT: os.makedirs() is needed instead of os.mkdir(). Only the former will construct all the intermediate subdirectories in a full path.
A:
This example should get you started:
import itertools
import os.path
ROOT = r'C:\base\path'
sex = ('male', 'female')
ethnicity = ('Caucasian', 'African-American', 'Asian')
ages = ('B20', '20', '30')
for path in itertools.product(sex, ethnicity, ages):
print os.path.join(ROOT, *path)
The itertools module is your friend:
http://docs.python.org/library/itertools.html#itertools.product
A:
Just do something like this:
main = 'somedir'
weight = ['weights', 'No_weights']
ethnicity = ['Caucasian', #the rest]
ages = ['B20'] + range(20, 71, 10)
for w in weights:
os.mkdir(os.path.join(main, w)
for e in ethnicity:
os.mkdir(os.path.join(main, w, e))
for a in ages:
os.mkdir(os.path.join(main, w, e, a))
and that should take care of it for you...
A:
Have a few nested for-loops, then os.mkdir for each one. Use os.path.join to concatenate the directory path together.
Something like:
loop weights
mkdir weight
loop sexes
mkdir weights + sex
loop ethnicities
mkdir weights + sex + ethnicity
loop ages
mkdir weights + sex + ethnicity + age
here loop is just a normal for-loop:
for weight in ('weights', 'no_weights'):
mkdir is os.mkdir
'+' is os.path.join:
os.mkdir(os.path.join(weights, sex, ethnicity, age))
Edit: dir_util might be of some use here so you don't have to make each subdirectory:
http://docs.python.org/release/2.5.2/dist/module-distutils.dirutil.html
loop weights
loop sexes
loop ethnicities
loop ages
mkpath weights + sex + ethnicity + age
A:
os.makedirs can help -- it makes all intermediate directories all the way down to the "leaf" one you specify.
The other issue (generating all the "one from column A, one from column B, ..." combinations) is best approached as a problem of "counting in mixed bases" -- roughly, s/thing like...:
choices = [ ['Weights', 'Noweights'],
['Male', 'Female'],
['Caucasian', 'AfricanAmerican', ...
...
]
Ls = [len(x) for x in choices]
ct = [0] * len(Ls)
while True:
p = [c[i] for i, c in zip(ct, choices)]
os.makedirs(os.path.join(p))
n = -1
while n > -len(Ls):
ct[n] += 1
if ct[n] < Ls[n]: break
ct[n] = 0
n -= 1
else:
break
itertools.product is the modern and concise approach to generating all the "one from column A, etc etc" picks, and what I would advise in production software -- just:
for p in itertools.product(*choices):
os.makedirs(os.path.join(p))
can replace all of the above code (!). I think it's also worth being aware of the "counting in mixed bases" lower-abstraction-level approach because it comes in handy in many cases (including times in which one is stuck using a Python release < 2.6;-).
| Creating/making directories in python (complex) | I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No_Weights. Male and Female following. Within each of Male and Female folders, I have each ethnicity (Caucasian, African-American, Asian, Hispanic, Indo, Other, Unknown). Within each of those folders, I have age ranges from Below 20, all the way to 70+ (B20, 20, 30, 40, 50, 60, 70).
I have tried to generate all of the paths so all I would have to call is mkdir about 50 times, but that is about 150 lines of code (almost).
Is there any simple way to create all of these folders without having to do it by hand?
| [
"import itertools\nimport os\n\ndirs = [[\"Weights\", \"No_Weights\"],\n [\"Male\", \"Female\"],\n [\"Caucasian\", \"African-American\", \"Asian\", \"Hispanic\", \"Indo\", \"Other\", \"Unknown\"], \n [\"B20\", \"20\", \"30\", \"40\", \"50\", \"60\", \"70\"]]\n\nfor item in itertools.product(*di... | [
18,
3,
2,
0,
0
] | [] | [] | [
"directory",
"mkdir",
"python"
] | stackoverflow_0003158921_directory_mkdir_python.txt |
Q:
Do you know any other programming languages that have interactive mode like Python?
Python language has a well known feature named interactive mode where the interpreter can read commands directly from tty.
I typically use this mode to test if a given module is in the classpath or to play around and test some snippets.
Do you know any other programming languages that have Interactive Mode?
If you can, give the name of the languages and where possible, a web reference.
If it is already mentioned, you can just vote for it.
A:
Most (all?) lisps (including common lisp, scheme and clojure), sml, ocaml, haskell, F#, erlang, scala, ruby, python, lua, groovy, prolog.
A:
PHP can do that too: PHP from the command line
Does mySQL count? mySQL Commands
JavaScript shell in SpiderMonkey (including, but not limited to, Firefox)
A:
bash / tcsh / csh / ksh /...
they all are programming languages and have a CLI :)
A:
Haskell even has two (mainstream) interactive interpreters, Hugs and ghci.
A:
Tcl/tk has one. It's been there since day one. This is not a feature unique to Python.
A:
As has been pointed out lots of languages can be used interactively, though how conveniently they can be so used varies quite a bit. The interactive environment I'm most familiar with, and one that I have found among the most congenial of all the free environments for interactive programming I've tried (not that I've tried them all) is Slime, a mode for emacs that allows interaction with a running Common Lisp, and can also be used with Clojure, a Lisp for the JVM.
If Lisp isn't your cup of tea a variety of Smalltalk environments are worth mentioning. One of the interesting things about many Smalltalk systems is that they expose almost all of the code that implements the system in the programming environment- if you want you can browse or even rewrite parts of the programming environment as you are using it, just as you would write new code. In fact the line between the system provided to you and the code you are writing is pretty blurry. Squeak is an interesting free Smalltalk, and Cincom offers an evaluation version of their commercial Smalltalk, which is a great environment IMHO.
Anyway, if you're interested in playing with interactive environments you could do worse than to play with those two, though of course there are a lot of other systems out there that allow interactive programming to one degree or another.
A:
Lisp and Scheme have interactive mode.
A:
C++.
Seriously.
A:
Ruby has irb, which is an interactive interpreter, and Ruby is quite similar to Python.
irb at Wikipedia
Ruby at Wikipedia
A:
Perl - interesting that there are so many answers before this
A:
Ruby has it.. also Groovy has it (allowing you to test also Java code effectively).
A:
I guess one of the first was LISP.
Just try clisp
A:
Most scripting languages will read from stdin and execute code typed at the console if you don't specify a filename to run. Php and perl will all do it.
Ruby has irb.
Lua has a more formal interactive mode like python, which will show you the indent level of your code at the prompt. It's very helpful since lua is typically used as an embedded scripting language, and you don't have to run your full application to test out code snippets.
A:
Lua has an interactive mode as well.
A:
Oh, I've forgotten the BASIC one :)
A:
Prolog has one as well
A:
Even Java has one!
It's called Beanshell: http://www.beanshell.org/
A:
There's one for C#.
A:
FORTH comes immediately to mind.
So does APL.
I remember seeing an interactive FORTRAN implementation on an SDS-930 (I think), many, many moons ago.
A:
You can do almost-interactive C# and VB.NET using LINQPad
A:
Logo programming language.
Some implementations are so interactive that some people don't even use any other mode.
A:
There's a repl for C too.
A:
R statistic program ;)
A:
Basic on the VIC20 and C64
A:
Any interpreted language is most likely going to have one.
A:
Erlang does, as well as Haskell and i'm guessing Ruby does. Also there are Javascript CLIs like Firebug
A:
Scala has REPL.
The Scala Interpreter (often called a REPL for Read-Evaluate-Print
Loop) sits in an unusual design space - an interactive interpreter for
a statically typed language straddles two worlds which historically
have been distinct. In version 2.8 the REPL further exploits the
unique possibilities.
A:
Visual Basic .NET has an interactive mode.
A:
Windows PowerShell: http://en.wikipedia.org/wiki/Windows_PowerShell
A:
Boo is a nice middle ground between Python and C# - type-inference and procedural-compatible programming, with compatibity with .Net, plus ability to compile to CLR assemblies and .EXE's.
A:
True to its name, the science-oriented and proprietary Interactive Data Language (usually just called IDL, but spelled out here to avoid confusion with the other IDL) has an interactive mode which many of its users utilize more often than they program in it.
| Do you know any other programming languages that have interactive mode like Python? | Python language has a well known feature named interactive mode where the interpreter can read commands directly from tty.
I typically use this mode to test if a given module is in the classpath or to play around and test some snippets.
Do you know any other programming languages that have Interactive Mode?
If you can, give the name of the languages and where possible, a web reference.
If it is already mentioned, you can just vote for it.
| [
"Most (all?) lisps (including common lisp, scheme and clojure), sml, ocaml, haskell, F#, erlang, scala, ruby, python, lua, groovy, prolog.\n",
"\nPHP can do that too: PHP from the command line\nDoes mySQL count? mySQL Commands\nJavaScript shell in SpiderMonkey (including, but not limited to, Firefox)\n\n",
"bas... | [
26,
5,
5,
5,
5,
5,
3,
3,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0
] | [] | [] | [
"language_agnostic",
"language_features",
"programming_languages",
"python"
] | stackoverflow_0002575219_language_agnostic_language_features_programming_languages_python.txt |
Q:
Logging activity on Django's admin - Django
I need to track/log activity on the Django admin.
I know there are messages stored by admin somewhere, but I don't know how to access them in order to use them as a simple log.
I'm trying to track the following:
User performing the action
Action committed
Datetime of action
Thanks guys.
A:
I had to do something similar and I used something like this:
from django.contrib.admin.models import LogEntry
logs = LogEntry.objects.all() #or you can filter, etc.
for l in logs:
#perform action
You can see all of the attributes for LogEntry, but I think the ones you are looking for are l.user, l.action_time and l.obj_repr (the name of the obj) and l.action_flag ({ 1:'Add',2:'Change',3:'Delete'}). Hope that helps!
A:
Log is in django_admin_log table in database used by django.
A:
Take a look at the LogEntry class which stores the log for the actions inside the admin.
You could use it like this to insert custom entries in the logs:
from settings import LOG_SIZE, LOG_THRESHOLD
from django.contrib.admin.models import LogEntry
if not LogEntry._meta.installed:
raise ImproperlyConfigured("You'll need to put 'django.contrib.admin' in your INSTALLED_APPS setting before you can use the admin application.")
def log_action(user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
# limit log size
log_count = LogEntry.objects.count()
if log_count > LOG_THRESHOLD:
to_delete = LogEntry.objects.all()[LOG_SIZE:log_count]
#FIXME (!?): to_delete.delete()
for d in to_delete:
d.delete()
LogEntry.objects.log_action(user_id, content_type_id, object_id, object_repr, action_flag, change_message)
| Logging activity on Django's admin - Django | I need to track/log activity on the Django admin.
I know there are messages stored by admin somewhere, but I don't know how to access them in order to use them as a simple log.
I'm trying to track the following:
User performing the action
Action committed
Datetime of action
Thanks guys.
| [
"I had to do something similar and I used something like this:\nfrom django.contrib.admin.models import LogEntry\n\nlogs = LogEntry.objects.all() #or you can filter, etc.\nfor l in logs:\n #perform action\n\nYou can see all of the attributes for LogEntry, but I think the ones you are looking for are l.user, l.ac... | [
31,
17,
5
] | [] | [] | [
"django",
"django_admin",
"logging",
"python"
] | stackoverflow_0003157875_django_django_admin_logging_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.