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:
Image preview with Reportlab?
I'm generating some pdf's with Reportlab and Django using a web interface. The pdf's are always going to be a single page. I'd like to generate a png or jpg image of the generated page and return that to the browser for the user to preview before saving the final pdf and delivering it to the end user. Is there anyway to do this?
A:
This answer explains that you can use ghostscript to convert pdf to png. Depending of the requirements of your app (traffic, response time, nb of pdfs ...) it may or may not be a solution for you.
This is just an idea, but may be you can generate the preview image in parallel using PIL ImageDraw and get rid of the pdf-to-png conversion.
I hope it helps
| Image preview with Reportlab? | I'm generating some pdf's with Reportlab and Django using a web interface. The pdf's are always going to be a single page. I'd like to generate a png or jpg image of the generated page and return that to the browser for the user to preview before saving the final pdf and delivering it to the end user. Is there anyway to do this?
| [
"This answer explains that you can use ghostscript to convert pdf to png. Depending of the requirements of your app (traffic, response time, nb of pdfs ...) it may or may not be a solution for you.\nThis is just an idea, but may be you can generate the preview image in parallel using PIL ImageDraw and get rid of th... | [
0
] | [] | [] | [
"django",
"pdf",
"preview",
"python",
"reportlab"
] | stackoverflow_0004122026_django_pdf_preview_python_reportlab.txt |
Q:
How to dynamically change a property?
My problem is quite simple, I have a string that contains a path to a property, and I want to change that property through the string.
str = "someClass.property"
data = 123
'''
I don't know what str contains, as it is created by a user
I know that I could do this, but it smells like bad practice,
in PHP it's a criminal offence
'''
exec(str + " = data" )
How do I acheive what I did above without touching exec()?
A:
You could use setattr:
setattr(someClass, property, data)
Note that this is still dangerous if done without any user validation as your user could change the definition of existing attributes that they should not be able to modify.
A safer alternative is to use a dict as a key-value store and put the user-defined properties in there.
A:
First of all, do you want to set the property on a class or an instance? In general, the best approach is to use a registry to register the objects (classes or instances) you want to change. This can be a simple dictionary:
registry = {}
Then explicitly register those objects you want to be changable by the user, e.g.
class Foo(object):
pass
f1 = Foo()
f2 = Foo()
registry['Foo'] = Foo
registry['f1'] = f1
registry['f2'] = f2
For classes in general you could encapsulate this a bit more by using <<class>>.__name__.
Lookup is easy and will fail nicely for anything that shouldn't be changable:
objectname, propertyname = str.split('.', 1)
o = registry[objectname]
Finally, setting the property can be done using setattr:
setattr(o, propertyname, data)
or a bit more OO-ish by defining explicit setting behaviour that can actually check the properties, e.g.
class Settable(object):
allowed = ('foo', 'bar')
def set(self, prop, val):
if prop not in self.allowed:
raise KeyError, prop
setattr(self, prop, val)
and derive from this class in stead:
class Foo(Settable):
allowed = Settable.allowed + ('blah',)
registry[objectname].set(propertyname, data)
| How to dynamically change a property? | My problem is quite simple, I have a string that contains a path to a property, and I want to change that property through the string.
str = "someClass.property"
data = 123
'''
I don't know what str contains, as it is created by a user
I know that I could do this, but it smells like bad practice,
in PHP it's a criminal offence
'''
exec(str + " = data" )
How do I acheive what I did above without touching exec()?
| [
"You could use setattr:\nsetattr(someClass, property, data)\n\nNote that this is still dangerous if done without any user validation as your user could change the definition of existing attributes that they should not be able to modify.\nA safer alternative is to use a dict as a key-value store and put the user-def... | [
3,
0
] | [] | [] | [
"exec",
"python"
] | stackoverflow_0004122102_exec_python.txt |
Q:
Get Data from OpenGL glReadPixels(using Pyglet)
I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: http://dpaste.com/99206/ , however it fails with an IndexError. How would I go about doing this?
A:
You must first create an array of the correct type, then pass it to glReadPixels:
a = (GLuint * 1)(0)
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)
To test this, insert the following in the Pyglet "opengl.py" example:
@window.event
def on_mouse_press(x, y, button, modifiers):
a = (GLuint * 1)(0)
glReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)
print a[0]
Now you should see the color code for the pixel under the mouse cursor whenever you click somewhere in the app window.
A:
I was able to obtain the entire frame buffer using glReadPixels(...), then used the PIL to write out to a file:
# Capture image from the OpenGL buffer
buffer = ( GLubyte * (3*window.width*window.height) )(0)
glReadPixels(0, 0, window.width, window.height, GL_RGB, GL_UNSIGNED_BYTE, buffer)
# Use PIL to convert raw RGB buffer and flip the right way up
image = Image.fromstring(mode="RGB", size=(window.width, window.height), data=buffer)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
# Save image to disk
image.save('jpap.png')
I was not interested in alpha, but I'm sure you could easily add it in.
I was forced to use glReadPixels(...), instead of the Pyglet code
pyglet.image.get_buffer_manager().get_color_buffer().save('jpap.png')
because the output using save(...) was not identical to what I saw in the Window. (Multisampling buffers missed?)
A:
You can use the PIL library, here is a code snippet which I use to capture such an image:
buffer = gl.glReadPixels(0, 0, width, height, gl.GL_RGB,
gl.GL_UNSIGNED_BYTE)
image = Image.fromstring(mode="RGB", size=(width, height),
data=buffer)
image = image.transpose(Image.FLIP_TOP_BOTTOM)
I guess including the alpha channel should be pretty straight forward (probably just replacing RGB with RGBA, but I have not tried that).
Edit: I wasn't aware that the pyglet OpenGL API is different from the PyOpenGL one. I guess one has to change the above code to use the buffer as the seventh argument (conforming to the less pythonic pyglet style).
A:
If you read the snippet you link to you can understand that the simplest and way to get the "normal" values is just accessing the array in the right order.
That snippet looks like it's supposed to do the job. If it doesn't, debug it and see what's the problem.
A:
On further review I believe my original code was based on some C specific code that worked because the array is just a pointer, so my using pointer arithmetic you could get at specific bytes, that obviously doesn't translate to Python. Does anyone how to extract that data using a different method(I assume it's just a matter of bit shifting the data).
| Get Data from OpenGL glReadPixels(using Pyglet) | I'm using Pyglet(and OpenGL) in Python on an application, I'm trying to use glReadPixels to get the RGBA values for a set of pixels. It's my understanding that OpenGL returns the data as packed integers, since that's how they are stored on the hardware. However for obvious reasons I'd like to get it into a normal format for working with. Based on some reading I've come up with this: http://dpaste.com/99206/ , however it fails with an IndexError. How would I go about doing this?
| [
"You must first create an array of the correct type, then pass it to glReadPixels:\na = (GLuint * 1)(0)\nglReadPixels(x, y, 1, 1, GL_RGB, GL_UNSIGNED_INT, a)\n\nTo test this, insert the following in the Pyglet \"opengl.py\" example:\n@window.event\ndef on_mouse_press(x, y, button, modifiers):\n a = (GLuint * 1)(... | [
4,
2,
1,
0,
0
] | [] | [] | [
"glreadpixels",
"graphics",
"opengl",
"pyglet",
"python"
] | stackoverflow_0000367684_glreadpixels_graphics_opengl_pyglet_python.txt |
Q:
Is there a way to make Mercurial give me a more verbose error message?
I'm having trouble with my hooks running on a remote server while the Mercurial process is running locally. The error message is not very informative, but I'm pretty sure it's a Python path issue. I get the error when I try to commit a changeset.
Is there anyway to get a complete stack trace? None of the following outputs are as helpful as a stack trace.
This is the regular error message:
C:\workspaces\test_next>hg commit -m "test"
Exception AttributeError: "'PPReleaseProject' object has no attribute '_projectname'" in <bound method PPReleaseProject.
__del__ of <testtrack.interface.PPReleaseProject object at 0x01BE35F0>> ignored
abort: precommit.fix_in_progress hook failed
This is the output with --traceback:
C:\workspaces\test_next>hg --traceback commit -m "test"
Exception AttributeError: "'PPReleaseProject' object has no attribute '_projectname'" in <bound method PPReleaseProject.
__del__ of <testtrack.interface.PPReleaseProject object at 0x01C065F0>> ignored
Traceback (most recent call last):
File "mercurial\dispatch.pyo", line 54, in _runcatch
File "mercurial\dispatch.pyo", line 494, in _dispatch
File "mercurial\dispatch.pyo", line 355, in runcommand
File "mercurial\dispatch.pyo", line 545, in _runcommand
File "mercurial\dispatch.pyo", line 499, in checkargs
File "mercurial\dispatch.pyo", line 492, in <lambda>
File "mercurial\util.pyo", line 420, in check
File "mercurial\commands.pyo", line 769, in commit
File "mercurial\cmdutil.pyo", line 1209, in commit
File "mercurial\commands.pyo", line 764, in commitfunc
File "mercurial\localrepo.pyo", line 892, in commit
File "mercurial\localrepo.pyo", line 153, in hook
File "mercurial\hook.pyo", line 142, in hook
File "mercurial\hook.pyo", line 84, in _pythonhook
Abort: precommit.fix_in_progress hook failed
abort: precommit.fix_in_progress hook failed
The output with --debug:
C:\workspaces\test_next>hg --debug commit -m "test"
calling hook precommit.branch_check: <function precommit_bad_branch at 0x01C585F0>
calling hook precommit.debug_code_check: <function precommit_contains_debug_code at 0x01C4A830>
calling hook precommit.fix_in_progress: <function precommit_fix_in_progress at 0x01C09270>
Exception AttributeError: "'PPReleaseProject' object has no attribute '_projectname'" in <bound method PPReleaseProject.
__del__ of <testtrack.interface.PPReleaseProject object at 0x01C5D5D0>> ignored
abort: precommit.fix_in_progress hook failed
A:
Modify your hook script to catch exceptions (wrap it in a try...except block) and within the except clause, use the traceback module to format a full-length traceback and write it out to stderr/stdout?
| Is there a way to make Mercurial give me a more verbose error message? | I'm having trouble with my hooks running on a remote server while the Mercurial process is running locally. The error message is not very informative, but I'm pretty sure it's a Python path issue. I get the error when I try to commit a changeset.
Is there anyway to get a complete stack trace? None of the following outputs are as helpful as a stack trace.
This is the regular error message:
C:\workspaces\test_next>hg commit -m "test"
Exception AttributeError: "'PPReleaseProject' object has no attribute '_projectname'" in <bound method PPReleaseProject.
__del__ of <testtrack.interface.PPReleaseProject object at 0x01BE35F0>> ignored
abort: precommit.fix_in_progress hook failed
This is the output with --traceback:
C:\workspaces\test_next>hg --traceback commit -m "test"
Exception AttributeError: "'PPReleaseProject' object has no attribute '_projectname'" in <bound method PPReleaseProject.
__del__ of <testtrack.interface.PPReleaseProject object at 0x01C065F0>> ignored
Traceback (most recent call last):
File "mercurial\dispatch.pyo", line 54, in _runcatch
File "mercurial\dispatch.pyo", line 494, in _dispatch
File "mercurial\dispatch.pyo", line 355, in runcommand
File "mercurial\dispatch.pyo", line 545, in _runcommand
File "mercurial\dispatch.pyo", line 499, in checkargs
File "mercurial\dispatch.pyo", line 492, in <lambda>
File "mercurial\util.pyo", line 420, in check
File "mercurial\commands.pyo", line 769, in commit
File "mercurial\cmdutil.pyo", line 1209, in commit
File "mercurial\commands.pyo", line 764, in commitfunc
File "mercurial\localrepo.pyo", line 892, in commit
File "mercurial\localrepo.pyo", line 153, in hook
File "mercurial\hook.pyo", line 142, in hook
File "mercurial\hook.pyo", line 84, in _pythonhook
Abort: precommit.fix_in_progress hook failed
abort: precommit.fix_in_progress hook failed
The output with --debug:
C:\workspaces\test_next>hg --debug commit -m "test"
calling hook precommit.branch_check: <function precommit_bad_branch at 0x01C585F0>
calling hook precommit.debug_code_check: <function precommit_contains_debug_code at 0x01C4A830>
calling hook precommit.fix_in_progress: <function precommit_fix_in_progress at 0x01C09270>
Exception AttributeError: "'PPReleaseProject' object has no attribute '_projectname'" in <bound method PPReleaseProject.
__del__ of <testtrack.interface.PPReleaseProject object at 0x01C5D5D0>> ignored
abort: precommit.fix_in_progress hook failed
| [
"Modify your hook script to catch exceptions (wrap it in a try...except block) and within the except clause, use the traceback module to format a full-length traceback and write it out to stderr/stdout?\n"
] | [
1
] | [] | [] | [
"mercurial",
"python"
] | stackoverflow_0004122392_mercurial_python.txt |
Q:
If users are uploading images, and I need to do a lot of resizing/uploading, how should I set up my queue?
When the user POSTS to my server, should I store the picture in the body of the queue, and then have the "worker" servers pull it out and resize/upload to S3?
The reason I'm using a queue is because resizing/uploading 20 images to S3 takes a long time.
A:
Amazon's Simple Queue Service may be used to maintain communication between your worker and frontend servers, but keep in mind that it only supports messages up to 64kb, meaning it won't be possible to keep the images in the queue. This is probably best, filesystems are designed to maintain large files, queue implementations generally aren't.
I would have the user upload directly to S3, then use the SQS to coordinate communication between your worker servers as they process the images and return them to S3.
| If users are uploading images, and I need to do a lot of resizing/uploading, how should I set up my queue? | When the user POSTS to my server, should I store the picture in the body of the queue, and then have the "worker" servers pull it out and resize/upload to S3?
The reason I'm using a queue is because resizing/uploading 20 images to S3 takes a long time.
| [
"Amazon's Simple Queue Service may be used to maintain communication between your worker and frontend servers, but keep in mind that it only supports messages up to 64kb, meaning it won't be possible to keep the images in the queue. This is probably best, filesystems are designed to maintain large files, queue imp... | [
1
] | [] | [] | [
"amazon_s3",
"data_structures",
"distributed",
"python",
"queue"
] | stackoverflow_0004122504_amazon_s3_data_structures_distributed_python_queue.txt |
Q:
Displaying list in Java as elegant as in Python
In Python it is pretty easy to display an iterable as comma separated list:
>>> iterable = ["a", "b", "c"]
>>> ", ".join(iterable)
'a, b, c'
Is there a Java way that comes close to this conciseness? (Notice that there is no "," at the end.)
A:
Here are the versions using Guava and Commons / Lang that Michael referred to:
List<String> items = Arrays.asList("a","b","c");
// Using Guava
String guavaVersion = Joiner.on(", ").join(items);
// Using Commons / Lang
String commonsLangVersion = StringUtils.join(items, ", ");
// both versions produce equal output
assertEquals(guavaVersion, commonsLangVersion);
Reference:
Guava: Joiner.on(String)
Guava: Joiner.join(Iterable<T>)
Commons / Lang: StringUtils.join(Collection, String)
A:
AbstractCollection.toString() (which is inherited by pretty much all collections in the standard API) pretty much does that. For Arrays, you can use the Arrays.toString() methods (which also work on primitive arrays).
There's probably something in Apache Commons Collections or Google Guava that allows you to choose the separator character and doesn't surround the results in brackets.
| Displaying list in Java as elegant as in Python | In Python it is pretty easy to display an iterable as comma separated list:
>>> iterable = ["a", "b", "c"]
>>> ", ".join(iterable)
'a, b, c'
Is there a Java way that comes close to this conciseness? (Notice that there is no "," at the end.)
| [
"Here are the versions using Guava and Commons / Lang that Michael referred to:\nList<String> items = Arrays.asList(\"a\",\"b\",\"c\");\n\n// Using Guava\nString guavaVersion = Joiner.on(\", \").join(items);\n\n// Using Commons / Lang\nString commonsLangVersion = StringUtils.join(items, \", \");\n\n// both versions... | [
19,
5
] | [] | [] | [
"iterator",
"java",
"join",
"list",
"python"
] | stackoverflow_0004122517_iterator_java_join_list_python.txt |
Q:
Apply a list of decorators to a callable?
Given a list of decorator methods, how would one apply those to a callable?
For example, since:
@foo
@bar
def baz():
pass
...is the same as:
def baz():
pass
baz = foo(bar(baz)))
...one would assume that with a list of decorators ([foo, bar]) they could be applied to baz dynamically.
A:
With yet another decorator!
def yad(decorators):
def decorator(f):
for d in reversed(decorators):
f = d(f)
return f
return decorator
example usage
list_of_decorators = [foo, bar]
@yad(list_of_decorators)
def foo():
print 'foo'
Without the decorator syntax, it would look like
func = yad(list_of_decorators)(func)
If you wanted to apply the same list to multiple functions, you can do it like:
dec = yad(list_of_decorators)
func1 = dec(func1)
@dec
def func2():
pass
As recursive points out in the comments, you can define yad (I'm sure there's a better name for this) to accept *decorators instead of decorators. Then you don't have to use brackets if you're creating the list in situ. The way that I've demonstrated is better if the list is created elsewhere.
A:
With an alltime classic:
def compose(f, g):
def composed(*a, **k):
return g(f(*a, **k))
return composed
@compose(foo, compose(bar, baz))
def blam():
pass
| Apply a list of decorators to a callable? | Given a list of decorator methods, how would one apply those to a callable?
For example, since:
@foo
@bar
def baz():
pass
...is the same as:
def baz():
pass
baz = foo(bar(baz)))
...one would assume that with a list of decorators ([foo, bar]) they could be applied to baz dynamically.
| [
"With yet another decorator!\ndef yad(decorators):\n def decorator(f):\n for d in reversed(decorators):\n f = d(f)\n return f\n return decorator\n\nexample usage\n list_of_decorators = [foo, bar]\n\n@yad(list_of_decorators)\ndef foo():\n print 'foo'\n\nWithout the decorator syntax,... | [
14,
2
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0004122815_decorator_python.txt |
Q:
Csv blank rows problem with Excel
I have a csv file which contains rows from a sqlite3 database. I wrote the rows to the csv file using python.
When I open the csv file with Ms Excel, a blank row appears below every row, but the file on notepad is fine(without any blanks).
Does anyone know why this is happenning and how I can fix it?
Edit: I used the strip() function for all the attributes before writing a row.
Thanks.
A:
You're using open('file.csv', 'w')--try open('file.csv', 'wb').
The Python csv module requires output files be opened in binary mode.
A:
the first that comes into my mind (just an idea) is that you might have used "\r\n" as row delimiter (which is shown as one linebrak in notepad) but excel expects to get only "\n" or only "\r" and so it interprets this as two line-breaks.
| Csv blank rows problem with Excel | I have a csv file which contains rows from a sqlite3 database. I wrote the rows to the csv file using python.
When I open the csv file with Ms Excel, a blank row appears below every row, but the file on notepad is fine(without any blanks).
Does anyone know why this is happenning and how I can fix it?
Edit: I used the strip() function for all the attributes before writing a row.
Thanks.
| [
"You're using open('file.csv', 'w')--try open('file.csv', 'wb'). \nThe Python csv module requires output files be opened in binary mode. \n",
"the first that comes into my mind (just an idea) is that you might have used \"\\r\\n\" as row delimiter (which is shown as one linebrak in notepad) but excel expects to g... | [
34,
0
] | [] | [] | [
"csv",
"excel",
"python"
] | stackoverflow_0004122794_csv_excel_python.txt |
Q:
why "return 100 if i < 10 else pass" is not valid in python?
All;
def foo(i):
return 100 if i < 10 else pass
return 200 if i < 20 else pass
return 1
Why this not works in python? I suppose this code may works same as:
def foo(i):
if i < 10:
return 100
elif i < 20:
return 200
else:
return 1
Thanks!
A:
In the documentation you will see that the "ternary operator" should be like this:
conditional_expression ::= or_test ["if" or_test "else" expression]
expression ::= conditional_expression | lambda_expr
and pass is a statement not an expression
A:
return 100 if i < 10 else pass
you should read it as return (100 if i < 10 else pass)
so pass isn't a value
A:
read your code like this:
return (100 if (i < 10) else pass)
pass is not a value you can return.
The following code would work:
def foo(i):
return 100 if i < 10 else (200 if i < 20 else 1)
A:
pass is a null operation i.e. when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed. It should not be used as part of any logic.
A:
You should read you function as
def foo(i):
if i < 10:
return 100
else:
return pass
if i < 20:
return 200
else:
return pass
return 1
return 100 if i < 10 else pass is not an "if" statement, this is a ternary operator
| why "return 100 if i < 10 else pass" is not valid in python? | All;
def foo(i):
return 100 if i < 10 else pass
return 200 if i < 20 else pass
return 1
Why this not works in python? I suppose this code may works same as:
def foo(i):
if i < 10:
return 100
elif i < 20:
return 200
else:
return 1
Thanks!
| [
"In the documentation you will see that the \"ternary operator\" should be like this:\nconditional_expression ::= or_test [\"if\" or_test \"else\" expression]\nexpression ::= conditional_expression | lambda_expr\n\nand pass is a statement not an expression\n",
"\nreturn 100 if i < 10 else pass\n\nyo... | [
19,
10,
10,
2,
0
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0004122764_if_statement_python.txt |
Q:
Python regular expression: decimal part of float
How can I accomplish the following transformations with a regular expression in Python?
0.44 -> 44
0.7867 -> 78
1.00 -> 100
A:
Parse the input as a floating point number then multiply it by 100 and truncate to an integer:
result = int(float(s) * 100)
A:
def twodigitint(x):
return int(100*float(x))
(or use round instead of int if you really want 0.7867->79)
A:
How about *100 and convert to int
t = lambda x: int (x*100)
t(0.44)
| Python regular expression: decimal part of float | How can I accomplish the following transformations with a regular expression in Python?
0.44 -> 44
0.7867 -> 78
1.00 -> 100
| [
"Parse the input as a floating point number then multiply it by 100 and truncate to an integer:\nresult = int(float(s) * 100)\n\n",
"def twodigitint(x):\n return int(100*float(x))\n\n(or use round instead of int if you really want 0.7867->79)\n",
"How about *100 and convert to int\nt = lambda x: int (x*100)\n... | [
6,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004123094_python_regex.txt |
Q:
Getting the root (head) of a DiGraph in networkx (Python)
I'm trying to use networkx to do some graph representation in a project, and I'm not sure how to do a few things that should be simple. I created a directed graph with a bunch of nodes and edges, such that there is only one root element in this graph. Now, what I'd like to do is start at the root, and then iterate through the children of each element and extract some information from them. How do I get the root element of this DiGraph?
So it would be something like this:
#This is NOT real code, just pseudopython to convey the general intent of what I'd like to do
root = myDiGraph.root()
for child in root.children():
iterateThroughChildren(child)
def iterateThroughChildren(parent):
if parent.hasNoChildren(): return
for child in parent.children():
//do something
//
iterateThroughChildren(child)
I didn't see anything in the documentation that suggested an easy way to retrieve the root of a DiGraph -- am I supposed to infer this manually? :O
I tried getting iter(myDiGraph) with the hope that it would iterate starting at the root, but the order seems to be random... :\
Help will be appreciated, thanks!
A:
If by having "one root element" you mean your directed graph is a rooted tree, then the root will be the only node with zero in-degree.
You can find that node in linear time (in the number of nodes) with:
In [1]: import networkx as nx
In [2]: G=nx.balanced_tree(2,3,create_using=nx.DiGraph()) # tree rooted at 0
In [3]: [n for n,d in G.in_degree() if d==0]
Out[3]: [0]
Or you could use a topological sort (root is first item):
In [4]: nx.topological_sort(G)
Out[4]: [0, 1, 3, 8, 7, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]
Alternatively it might be faster to start with a given (random) node and follow the predecessors until you find a node with no predecessors.
| Getting the root (head) of a DiGraph in networkx (Python) | I'm trying to use networkx to do some graph representation in a project, and I'm not sure how to do a few things that should be simple. I created a directed graph with a bunch of nodes and edges, such that there is only one root element in this graph. Now, what I'd like to do is start at the root, and then iterate through the children of each element and extract some information from them. How do I get the root element of this DiGraph?
So it would be something like this:
#This is NOT real code, just pseudopython to convey the general intent of what I'd like to do
root = myDiGraph.root()
for child in root.children():
iterateThroughChildren(child)
def iterateThroughChildren(parent):
if parent.hasNoChildren(): return
for child in parent.children():
//do something
//
iterateThroughChildren(child)
I didn't see anything in the documentation that suggested an easy way to retrieve the root of a DiGraph -- am I supposed to infer this manually? :O
I tried getting iter(myDiGraph) with the hope that it would iterate starting at the root, but the order seems to be random... :\
Help will be appreciated, thanks!
| [
"If by having \"one root element\" you mean your directed graph is a rooted tree, then the root will be the only node with zero in-degree. \nYou can find that node in linear time (in the number of nodes) with:\nIn [1]: import networkx as nx\n\nIn [2]: G=nx.balanced_tree(2,3,create_using=nx.DiGraph()) # tree rooted... | [
66
] | [] | [] | [
"directed_graph",
"networkx",
"python"
] | stackoverflow_0004122390_directed_graph_networkx_python.txt |
Q:
Is there any function that returns the out edges of a node?
I am using python with networkx package. I need to find the nodes connected to out edges of a given node.
I know there is a function networkx.DiGraph.out_edges but it returns out edges for the entire graph.
A:
I'm not a networkx expert, but have you tried networkx.DiGraph.out_edges, specifying the source node?
DiGraph.out_edges(nbunch=None, data=False)
Return a list of edges.
Edges are returned as tuples with optional data in the order (node,
neighbor, data).
If you just want the out edges for a single node, pass that node in inside the nbunch:
graph.out_edges([my_node])
A:
The simplest way is to use the successors() method:
In [1]: import networkx as nx
In [2]: G=nx.DiGraph([(0,1),(1,2)])
In [3]: G.edges()
Out[3]: [(0, 1), (1, 2)]
In [4]: G.successors(1)
Out[4]: [2]
| Is there any function that returns the out edges of a node? | I am using python with networkx package. I need to find the nodes connected to out edges of a given node.
I know there is a function networkx.DiGraph.out_edges but it returns out edges for the entire graph.
| [
"I'm not a networkx expert, but have you tried networkx.DiGraph.out_edges, specifying the source node?\n\nDiGraph.out_edges(nbunch=None, data=False)\n\nReturn a list of edges.\nEdges are returned as tuples with optional data in the order (node,\n neighbor, data).\n\nIf you just want the out edges for a single node... | [
6,
6
] | [] | [] | [
"networkx",
"python"
] | stackoverflow_0002191687_networkx_python.txt |
Q:
Looping seems to not follow sequence
I feel like I'm missing something obvious here!
seq = {'a': ['1'], 'aa': ['2'], 'aaa': ['3'], 'aaaa': ['4'], 'aaaaa': ['5']}
for s in seq:
print(s)
outputs:
a
aa
aaaa
aaaaa
aaa
Whereas surely it should output:
a
aa
aaa
aaaa
aaaaa
What's going wrong here?
A:
Dictionaries are not ordered. If you need to rely on the ordering, you need an OrderedDict - there's one in the collections module in Python 2.7, or you can use one of the many recipes around.
A:
Standard Python dictionaries are not ordered: there is no guarantee on which order the keys will be returned.
If you want your keys returned in the order in which you create keys you can use an OrderedDict from collections.
Alternatively, if you want your output sorted on the values of the keys the following would do:
for s in sorted(seq):
print s
A:
why you don't do (dictionary are not ordered):
for s in range(5):
print 'a'*s
Edit : ok as you which :)
the thing is in the expression : 'a'*s which mean create a new string which contain s time 'a'.
in the python interpreter you can play with it (isn't python wonderful :) )
>>> print 'a'*2
aa
>>> print 'a'*3
aaa
PS: if you're new to python i will suggest that you use ipython if you don't use it yet.
| Looping seems to not follow sequence | I feel like I'm missing something obvious here!
seq = {'a': ['1'], 'aa': ['2'], 'aaa': ['3'], 'aaaa': ['4'], 'aaaaa': ['5']}
for s in seq:
print(s)
outputs:
a
aa
aaaa
aaaaa
aaa
Whereas surely it should output:
a
aa
aaa
aaaa
aaaaa
What's going wrong here?
| [
"Dictionaries are not ordered. If you need to rely on the ordering, you need an OrderedDict - there's one in the collections module in Python 2.7, or you can use one of the many recipes around.\n",
"Standard Python dictionaries are not ordered: there is no guarantee on which order the keys will be returned.\nIf y... | [
15,
5,
1
] | [] | [] | [
"dictionary",
"for_loop",
"list",
"python"
] | stackoverflow_0004123266_dictionary_for_loop_list_python.txt |
Q:
How to open mutiple frames via thread in tkinter?
I tried to open mutiple frames by mutiple threads.
Here is my code.
'''
This is the module for test and studying.
Author:Roger
Date: 2010/10/10
Python version: 2.6.5
'''
import threading, Tkinter
class Application(Tkinter.Frame):
def __init__(self, master=None):
Tkinter.Frame.__init__(self, master)
self.columnconfigure(50)
self.rowconfigure(50)
self.grid()
self.createWidgets()
self.mainloop()
def createWidgets(self):
self.quitButton = Tkinter.Button (self, text='Quit', command=self.quit )
self.quitButton.grid()
class lab_404(threading.Thread):
'''
Is this the doc_string of lab_404?
Can there be mutiple_window?
I do know why is it like this?
Why is the button still on the frame?
'''
myWindow = None
def __init__(self, computer = 10, server = None, table = 1, chair = 1, student = 2, myWindow = None):
threading.Thread.__init__(self)
self.__computer = computer
self.__server = server
self.__table = table
self.__chair = chair
self.__student = student
self.myWindow = Application()
#self.myWindow.mainloop() #mainloop method is here, I don't where to put it.
def getComputer(self):
return self.__computer
def getServer(self):
return self.__server
def getMyWindow(self):
return self.myWindow
def setServer(self, Server):
self.__server = Server
def run(self):
print super(lab_404, self).getName(), 'This thread is starting now!'
print super(lab_404, self).getName(), 'This thread is ending.'
if __name__ == '__main__':
for n in xrange(1, 10, 1):
tn = lab_404(server = n) #Try to make a loop.
tn.start()
The code above has been running as a frame, then stop (mainloop?). It won't continue to the next frame until I close the formmer window. It's fitful.
How could I make it open new frames automatically?
A:
I don't think you can do what you want. Generally speaking, there's no need to run multiple frames and multiple event loops. You can have multiple frames within a single thread and within a single event loop.
| How to open mutiple frames via thread in tkinter? | I tried to open mutiple frames by mutiple threads.
Here is my code.
'''
This is the module for test and studying.
Author:Roger
Date: 2010/10/10
Python version: 2.6.5
'''
import threading, Tkinter
class Application(Tkinter.Frame):
def __init__(self, master=None):
Tkinter.Frame.__init__(self, master)
self.columnconfigure(50)
self.rowconfigure(50)
self.grid()
self.createWidgets()
self.mainloop()
def createWidgets(self):
self.quitButton = Tkinter.Button (self, text='Quit', command=self.quit )
self.quitButton.grid()
class lab_404(threading.Thread):
'''
Is this the doc_string of lab_404?
Can there be mutiple_window?
I do know why is it like this?
Why is the button still on the frame?
'''
myWindow = None
def __init__(self, computer = 10, server = None, table = 1, chair = 1, student = 2, myWindow = None):
threading.Thread.__init__(self)
self.__computer = computer
self.__server = server
self.__table = table
self.__chair = chair
self.__student = student
self.myWindow = Application()
#self.myWindow.mainloop() #mainloop method is here, I don't where to put it.
def getComputer(self):
return self.__computer
def getServer(self):
return self.__server
def getMyWindow(self):
return self.myWindow
def setServer(self, Server):
self.__server = Server
def run(self):
print super(lab_404, self).getName(), 'This thread is starting now!'
print super(lab_404, self).getName(), 'This thread is ending.'
if __name__ == '__main__':
for n in xrange(1, 10, 1):
tn = lab_404(server = n) #Try to make a loop.
tn.start()
The code above has been running as a frame, then stop (mainloop?). It won't continue to the next frame until I close the formmer window. It's fitful.
How could I make it open new frames automatically?
| [
"I don't think you can do what you want. Generally speaking, there's no need to run multiple frames and multiple event loops. You can have multiple frames within a single thread and within a single event loop.\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004123409_python_tkinter.txt |
Q:
lambda push to a list then invoking - output is not as expected
All:
def a(p):
return p+1
def gen(func, k=100):
l= []
for x in range(k):
temp = ("%s_with_parameter_%s" %(func.__name__, x), lambda: func(x))
# maybe this will be more clear to explain my quetion:
# i want to get list/dict which can bind self-defined string and function together
l.append(temp)
return l
l = gen(a, 100)
for x in range(len(l)):
l[x][1]()
100
100
100
100
100
100
100
100
...I suppose output will be a 1 to 101 print out, but it shows a 100 list.
May I get help for this snippet here?
Thanks!
A:
As other answers have noted, the lambdas are using the last value of x because they're closed over it and so see any changes made to it. The trick is to bind them to the value.
You can do this by writing them as
lambda x=x: func(x)
This binds the value of x that is current when the lambda is created to the default parameter p which means that the lambda is no longer a closure over x and is not affected by any future changes in its value. You would change the way you call it to not pass in an argument that you don't do anything with:
for x in range(len(l)):
l[x][1]()
Now, the lambda uses the default value which is bound to what you want.
If you do actually need to pass a value in, then you can just stick the default parameter that is used for binding purposes on after the 'real' parameter:
lambda p, x=x: func(p, x)
A:
The standard trick is to write your function gen() as:
def gen(func, k=100):
l= []
for x in range(k):
l.append(lambda x=x: func(x))
return l
Note the parameter to the lambda expression. This enforces that a new x is created for each lambda. Otherwise, all use the same x from the enclosing scope.
A:
Maybe with this slight variant of your code you'll understand what happens.
def a(p):
return p+1
def gen(func, k=100):
l= []
for x in range(k):
l.append(lambda p: func(x))
x = 77
return l
l = gen(a, 100)
for x in range(len(l)):
print l[x](10)
Now you always get 78 when calling lx. The problem is you always have the same variable x in the closure, not it's value at the moment of the definition of the lambda.
I believe you probably want something like Haskell curryfication. In python you can use functools.partial for that purpose. I would write your code as below. Notice I have removed the dummy parameter.
import functools
def a(p):
return p+1
def gen(func, k=100):
l= []
for x in range(k):
l.append(functools.partial(func, x))
return l
l = gen(a, 100)
for x in range(len(l)):
print l[x]()
Now let's introduce back the dummy parameter:
import functools
def a(p):
return p+1
def gen(func, k=100):
fn = lambda x, p: func(x)
l= []
for x in range(k):
l.append(functools.partial(fn, x))
return l
l = gen(a, 100)
for x in range(len(l)):
print l[x](10)
Edit: I much prefer the solution of Sven Marnach over mine :-)
A:
In your code, it looks like the value used in a() is the last value known for x (which is 100) while you're p variable is actually dummy (like you mention).
This is because the lambda function is "resolved" when you call it.
It means that calling l[x](10) would be "equivalent" to: (this is not correct, it's to explain)
lambda 10: func(100)
A:
You can use the yield statement to create a generator, I think is the most elegant solution:
>>> def a(p):
... return p+1
...
>>> def gen(func, k=100):
... for x in range(k):
... yield lambda :func(x)
...
>>> for item in gen(a, 100):
... item()
...
1
2
3
4
(...)
100
>>>
But as you can see it goes only until 100 because of the range function:
>>> range(100)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 4
2, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 6
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 8
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>>
You can use gen(a, 101) to solve this:
>>> for item in gen(a, 101):
... item()
...
1
2
3
4
5
(...)
101
>>>
| lambda push to a list then invoking - output is not as expected | All:
def a(p):
return p+1
def gen(func, k=100):
l= []
for x in range(k):
temp = ("%s_with_parameter_%s" %(func.__name__, x), lambda: func(x))
# maybe this will be more clear to explain my quetion:
# i want to get list/dict which can bind self-defined string and function together
l.append(temp)
return l
l = gen(a, 100)
for x in range(len(l)):
l[x][1]()
100
100
100
100
100
100
100
100
...I suppose output will be a 1 to 101 print out, but it shows a 100 list.
May I get help for this snippet here?
Thanks!
| [
"As other answers have noted, the lambdas are using the last value of x because they're closed over it and so see any changes made to it. The trick is to bind them to the value.\nYou can do this by writing them as \nlambda x=x: func(x)\n\nThis binds the value of x that is current when the lambda is created to the d... | [
6,
3,
2,
0,
0
] | [] | [] | [
"lambda",
"python"
] | stackoverflow_0004123174_lambda_python.txt |
Q:
python versions on winXP
I asked this question on superuser, and got the tumbleweed badge for it (13 views in 10 days), so I figured here might be the right place.
There are several versions of python installed in my windows machine. I want to be able to switch easily between the versions being used as default.
I experimented and used winexplorer to change the program associated to py files.
I set the program to be used to open these files as wordpad.
Now when I type a .py's filename in the command line, the file opens in wordpad.
In spite of this, typing the following in the command line yields:
C:\>assoc .py
.py=Python.File
C:\>ftype Python.File
Python.File="C:\Program\Python27\python.exe" "%1" %*
I don't understand why the command line runs wordpad (as set in windows explorer), although assoc and ftype say it should run Python27.
Are these associations (command line vs explorer) stored in different places? Which one overrides which one, and does setting a new association with assoc and ftype overwrite that set in explorer?
What would you recommend to do, in order to be able to switch easily?
More info from my registry:
HKEY_CLASSES_ROOT.py is Python.File
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.py\Application is wordpad.exe
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.py\OpenWithProgids\Python.File is a binary value of length 0.
HKEY_LOCAL_MACHINE\SOFTWARE\Classes.py(Standard) is Python.File
More registry:
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command(Standard) is still "C:\Program\Python27\python.exe" "%1" %*,
I suppose this is what is showing up in ftype Python.File. But it does not seem to get used.
Edit to add register information
Regedit says:
HKEY_CLASSES_ROOT\.py
+--- (Standard) REG_SZ Python.File
+--- Content Type REG_SZ text/plain
I have tried changing the value of Content Type, no effect.
also:
HKEY_CLASSES_ROOT\Python.File
+--- shell (no data)
+--- Edit with IDLE
| +--- command
| +--- (Standard) <path-to-idle>
+--- open (no data)
+--- command
+--- (Standard) <path-to-python27>
I tried to set the value of shell to open, and the value of open to the path to the python27 exe, still not working.
Somehow the command prompt still finds the association I made in winexplorer and uses wordpad to open the file, instead of using the command in open.
A:
If HKEY_CLASSES_ROOT\.py is Python.File then you have to look into HKEY_CLASSES_ROOT\Python.File\shell. Then lookup the subkey named like its value, e.g. if the shell key has the value open go to HKEY_CLASSES_ROOT\Python.File\shell\open. That's where the association is stored. If the shell key has no value, go to the open subkey.
The problem is that the ftype tool always shows the contents of the open subkey regardless of the value of the shell key.
| python versions on winXP | I asked this question on superuser, and got the tumbleweed badge for it (13 views in 10 days), so I figured here might be the right place.
There are several versions of python installed in my windows machine. I want to be able to switch easily between the versions being used as default.
I experimented and used winexplorer to change the program associated to py files.
I set the program to be used to open these files as wordpad.
Now when I type a .py's filename in the command line, the file opens in wordpad.
In spite of this, typing the following in the command line yields:
C:\>assoc .py
.py=Python.File
C:\>ftype Python.File
Python.File="C:\Program\Python27\python.exe" "%1" %*
I don't understand why the command line runs wordpad (as set in windows explorer), although assoc and ftype say it should run Python27.
Are these associations (command line vs explorer) stored in different places? Which one overrides which one, and does setting a new association with assoc and ftype overwrite that set in explorer?
What would you recommend to do, in order to be able to switch easily?
More info from my registry:
HKEY_CLASSES_ROOT.py is Python.File
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.py\Application is wordpad.exe
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts.py\OpenWithProgids\Python.File is a binary value of length 0.
HKEY_LOCAL_MACHINE\SOFTWARE\Classes.py(Standard) is Python.File
More registry:
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command(Standard) is still "C:\Program\Python27\python.exe" "%1" %*,
I suppose this is what is showing up in ftype Python.File. But it does not seem to get used.
Edit to add register information
Regedit says:
HKEY_CLASSES_ROOT\.py
+--- (Standard) REG_SZ Python.File
+--- Content Type REG_SZ text/plain
I have tried changing the value of Content Type, no effect.
also:
HKEY_CLASSES_ROOT\Python.File
+--- shell (no data)
+--- Edit with IDLE
| +--- command
| +--- (Standard) <path-to-idle>
+--- open (no data)
+--- command
+--- (Standard) <path-to-python27>
I tried to set the value of shell to open, and the value of open to the path to the python27 exe, still not working.
Somehow the command prompt still finds the association I made in winexplorer and uses wordpad to open the file, instead of using the command in open.
| [
"If HKEY_CLASSES_ROOT\\.py is Python.File then you have to look into HKEY_CLASSES_ROOT\\Python.File\\shell. Then lookup the subkey named like its value, e.g. if the shell key has the value open go to HKEY_CLASSES_ROOT\\Python.File\\shell\\open. That's where the association is stored. If the shell key has no value, ... | [
1
] | [] | [] | [
"associations",
"python",
"windows"
] | stackoverflow_0004123009_associations_python_windows.txt |
Q:
searching a wsgi testing plugin in python
i was wondering what you'r using to test your python wsgi apps and which one is the most updated and easiest to setup.
im on appengine python and i would like to start writing tests for my handlers.
i've see gaeunit and nose-gae and if there are some more out there and what you think about them.
A:
I use webtest with nose-gae. While it doesn't emulate javascript, it is a great way to exercise each handler in your app, and has nice support for forms too.
For more detail testing of each edge case, I would factor our utilities / model related logic from the handlers and write tests for those separately. But it is nice to have some end to end tests, and webtest works great for that.
| searching a wsgi testing plugin in python | i was wondering what you'r using to test your python wsgi apps and which one is the most updated and easiest to setup.
im on appengine python and i would like to start writing tests for my handlers.
i've see gaeunit and nose-gae and if there are some more out there and what you think about them.
| [
"I use webtest with nose-gae. While it doesn't emulate javascript, it is a great way to exercise each handler in your app, and has nice support for forms too.\nFor more detail testing of each edge case, I would factor our utilities / model related logic from the handlers and write tests for those separately. But ... | [
2
] | [] | [] | [
"httpwebrequest",
"python",
"testing",
"wsgi"
] | stackoverflow_0004124071_httpwebrequest_python_testing_wsgi.txt |
Q:
Python: multiple possible values for function arguments
I've inherited some Python code that looks like this:
name = 'London'
code = '0.1'
notes = 'Capital of England'
ev = model.City(key=key, code=code, name=name or code, notes=notes)
In the spirit of learning, I'd like to know what's going on with the name or code argument. Is this saying 'Use name if it's not null, otherwise use code'?
And what is the technical term for supplying multiple possible arguments like this, so I can read up on it in the Python docs?
Thanks!
A:
Almost. It says use name if it does not evaluate to false. Things that evaluate to false include, but are not limited to:
False
empty sequences ((), [], "")
empty mappings ({})
0
None
Edit Added the link provided by SilentGhost in his comment to the answer.
A:
In python, the or operator returns the first operand, unless it evaluates to false, in which case it returns the second operand. In effect this will use name, with a default fallback of code if name is not specified.
A:
Fire up a Python console:
>>> name = None
>>> code = 0.1
>>> name or code
0.10000000000000001
In case name evaluates to false the expression will evaluate to code. Otherwise name will be used.
A:
Correct, that idiom take the first value that evaluates to True (generally not None). Use with care since valid values (like zero) may inadvertently be forsaken. A safer approach is something like:
if name is not None:
# use name
or
name if name is not None else code
A:
You've it it roughly correct, but 'null' is not precisely what decides. Basically anything that will evaluate to false (0, false, empty string '') will cause the second string to be displayed instead of the first. 'x or y' in this sense is kind of equivalent to:
if x: x
else: y
Some console play:
x = ''
y = 'roar'
x or y
-'roar'
x = 'arf'
x or y
-'arf'
x = False
x or y
-'roar'
A:
In the spirit of learning, I'd like to
know what's going on with the name or
code argument. Is this saying 'Use
name if it's not null, otherwise use
code'?
yes basically but Null in python can mean more than one thing (empty string , none ..)
like in your case:
>>> name = 'London'
>>> code = 0.1
>>> name or code
'London'
>>> name = ''
>>> code = 0.1
>>> name or code
0.1000....
but it weird thew that a function parameter can be integer sometimes and a string other times.
Hope this can help :=)
| Python: multiple possible values for function arguments | I've inherited some Python code that looks like this:
name = 'London'
code = '0.1'
notes = 'Capital of England'
ev = model.City(key=key, code=code, name=name or code, notes=notes)
In the spirit of learning, I'd like to know what's going on with the name or code argument. Is this saying 'Use name if it's not null, otherwise use code'?
And what is the technical term for supplying multiple possible arguments like this, so I can read up on it in the Python docs?
Thanks!
| [
"Almost. It says use name if it does not evaluate to false. Things that evaluate to false include, but are not limited to:\n\nFalse\nempty sequences ((), [], \"\")\nempty mappings ({})\n0\nNone\n\nEdit Added the link provided by SilentGhost in his comment to the answer.\n",
"In python, the or operator returns the... | [
13,
7,
1,
1,
0,
0
] | [] | [] | [
"boolean_expression",
"python"
] | stackoverflow_0004124787_boolean_expression_python.txt |
Q:
Python serialize lexical closures?
Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example:
def foo(bar, baz) :
def closure(waldo) :
return baz * waldo
return closure
I'd like to just be able to dump instances of closure to a file and read them back.
Edit:
One relatively obvious way that this could be solved is with some reflection hacks to convert lexical closures into class objects and vice-versa. One could then convert to classes, serialize, unserialize, convert back to closures. Heck, given that Python is duck typed, if you overloaded the function call operator of the class to make it look like a function, you wouldn't even really need to convert it back to a closure and the code using it wouldn't know the difference. If any Python reflection API gurus are out there, please speak up.
A:
PiCloud has released an open-source (LGPL) pickler which can handle function closure and a whole lot more useful stuff. It can be used independently of their cloud computing infrastructure - it's just a normal pickler. The whole shebang is documented here, and you can download the code via 'pip install cloud'. Anyway, it does what you want. Let's demonstrate that by pickling a closure:
import pickle
from StringIO import StringIO
import cloud
# generate a closure
def foo(bar, baz):
def closure(waldo):
return baz * waldo
return closure
closey = foo(3, 5)
# use the picloud pickler to pickle to a string
f = StringIO()
pickler = cloud.serialization.cloudpickle.CloudPickler(f)
pickler.dump(closey)
#rewind the virtual file and reload
f.seek(0)
closey2 = pickle.load(f)
Now we have closey, the original closure, and closey2, the one that has been restored from a string serialisation. Let's test 'em.
>>> closey(4)
20
>>> closey2(4)
20
Beautiful. The module is pure python—you can open it up and easily see what makes the magic work. (The answer is a lot of code.)
A:
If you simply use a class with a __call__ method to begin with, it should all work smoothly with pickle.
class foo(object):
def __init__(self, bar, baz):
self.baz = baz
def __call__(self,waldo):
return self.baz * waldo
On the other hand, a hack which converted a closure into an instance of a new class created at runtime would not work, because of the way pickle deals with classes and instances. pickle doesn't store classes; only a module name and class name. When reading back an instance or class it tries to import the module and find the required class in it. If you used a class created on-the-fly, you're out of luck.
A:
Yes! I got it (at least I think) -- that is, the more generic problem of pickling a function. Python is so wonderful :), I found out most of it though the dir() function and a couple of web searches. Also wonderful to have it [hopefully] solved, I needed it also.
I haven't done a lot of testing on how robust this co_code thing is (nested fcns, etc.), and it would be nice if someone could look up how to hook Python so functions can be pickled automatically (e.g. they might sometimes be closure args).
Cython module _pickle_fcn.pyx
# -*- coding: utf-8 -*-
cdef extern from "Python.h":
object PyCell_New(object value)
def recreate_cell(value):
return PyCell_New(value)
Python file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author gatoatigrado [ntung.com]
import cPickle, marshal, types
import pyximport; pyximport.install()
import _pickle_fcn
def foo(bar, baz) :
def closure(waldo) :
return baz * waldo
return closure
# really this problem is more about pickling arbitrary functions
# thanks so much to the original question poster for mentioning marshal
# I probably wouldn't have found out how to serialize func_code without it.
fcn_instance = foo("unused?", -1)
code_str = marshal.dumps(fcn_instance.func_code)
name = fcn_instance.func_name
defaults = fcn_instance.func_defaults
closure_values = [v.cell_contents for v in fcn_instance.func_closure]
serialized = cPickle.dumps((code_str, name, defaults, closure_values),
protocol=cPickle.HIGHEST_PROTOCOL)
code_str_, name_, defaults_, closure_values_ = cPickle.loads(serialized)
code_ = marshal.loads(code_str_)
closure_ = tuple([_pickle_fcn.recreate_cell(v) for v in closure_values_])
# reconstructing the globals is like pickling everything :)
# for most functions, it's likely not necessary
# it probably wouldn't be too much work to detect if fcn_instance global element is of type
# module, and handle that in some custom way
# (have the reconstruction reinstantiate the module)
reconstructed = types.FunctionType(code_, globals(),
name_, defaults_, closure_)
print(reconstructed(3))
cheers,
Nicholas
EDIT - more robust global handling is necessary for real-world cases. fcn.func_code.co_names lists global names.
A:
#!python
import marshal, pickle, new
def dump_func(f):
if f.func_closure:
closure = tuple(c.cell_contents for c in f.func_closure)
else:
closure = None
return marshal.dumps(f.func_code), f.func_defaults, closure
def load_func(code, defaults, closure, globs):
if closure is not None:
closure = reconstruct_closure(closure)
code = marshal.loads(code)
return new.function(code, globs, code.co_name, defaults, closure)
def reconstruct_closure(values):
ns = range(len(values))
src = ["def f(arg):"]
src += [" _%d = arg[%d]" % (n, n) for n in ns]
src += [" return lambda:(%s)" % ','.join("_%d"%n for n in ns), '']
src = '\n'.join(src)
try:
exec src
except:
raise SyntaxError(src)
return f(values).func_closure
if __name__ == '__main__':
def get_closure(x):
def the_closure(a, b=1):
return a * x + b, some_global
return the_closure
f = get_closure(10)
code, defaults, closure = dump_func(f)
dump = pickle.dumps((code, defaults, closure))
code, defaults, closure = pickle.loads(dump)
f = load_func(code, defaults, closure, globals())
some_global = 'some global'
print f(2)
A:
Recipe 500261: Named Tuples contains a function that defines a class on-the-fly. And this class supports pickling.
Here's the essence:
result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
Combined with @Greg Ball's suggestion to create a new class at runtime it might answer your question.
| Python serialize lexical closures? | Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example:
def foo(bar, baz) :
def closure(waldo) :
return baz * waldo
return closure
I'd like to just be able to dump instances of closure to a file and read them back.
Edit:
One relatively obvious way that this could be solved is with some reflection hacks to convert lexical closures into class objects and vice-versa. One could then convert to classes, serialize, unserialize, convert back to closures. Heck, given that Python is duck typed, if you overloaded the function call operator of the class to make it look like a function, you wouldn't even really need to convert it back to a closure and the code using it wouldn't know the difference. If any Python reflection API gurus are out there, please speak up.
| [
"PiCloud has released an open-source (LGPL) pickler which can handle function closure and a whole lot more useful stuff. It can be used independently of their cloud computing infrastructure - it's just a normal pickler. The whole shebang is documented here, and you can download the code via 'pip install cloud'. A... | [
20,
18,
1,
1,
0
] | [] | [] | [
"closures",
"python",
"serialization"
] | stackoverflow_0000573569_closures_python_serialization.txt |
Q:
How do I get case-insensitive queries on non-ASCII with python and sqlite3?
There are some obvious tips and resources about this, but I can't find any direct examples.
http://www.sqlite.org/faq.html#q18 says one can override the NOCASE collation, and the like, lower, and upper functions. I've done so, in a Django testcase, but in my test none of them are actually called.
from django.test import TestCase
from django.contrib.sites.models import Site
from basic.blog.models import Post, Settings
class CaseInsenstiveTest(TestCase):
def setUp(self):
self.site = Site.objects.create()
self.settings = Settings.objects.create(site=self.site)
Settings.get_current = classmethod(lambda cls: self.settings)
def testLike(self):
from django.db import connection
Post.objects.all() # Sets up the connection
def like(x, y, z=None):
"""Y LIKE X [ESCAPE Z]"""
assert x.startswith('%') and x.endswith('%')
like.called = True
print "like(%r, %r, %r)" % (x, y, z)
return x[1:-1].lower() in y.lower()
like.called = False
def lower(s):
print "lower(%r)" % (s,)
return s.lower()
def upper(s):
print "upper(%r)" % (s,)
return s.upper()
connection.connection.create_function('lower', 1, lower)
connection.connection.create_function('upper', 1, upper)
connection.connection.create_function('like', 3, like)
def NOCASE(a, b):
print "NOCASE(%r, %r)" % (a, b)
return cmp(a.lower(), b.lower())
connection.connection.create_collation('NOCASE', NOCASE)
Post.objects.create(slug='foo', title='Foo')
Post.objects.filter(title__icontains='foo')
it seems not a single of the registered functions or the collation are actually called. Can anyone point out what is wrong?
NOTE: I know the like function is not correct, yet. I'm just trying to figure out when what is called so I know what I need to override and how.
A:
It seems to work fine outside django:
So maybe you have a django problem? Are you sure the table fields were created using the NOCASE collation?
import sqlite3
def NOCASE(a, b):
print 'comparing %r with %r...' % (a, b)
return cmp(a.lower(), b.lower())
con = sqlite3.connect('')
cur = con.cursor()
cur.execute('CREATE TABLE foo (id INTEGER, text VARCHAR collate NOCASE)')
cur.executemany('INSERT INTO foo (id, text) VALUES (?, ?)', [
(1, u'test'), (2, u'TEST'), (3, u'uest'), (4, u'UEST')])
con.commit()
con.create_collation('NOCASE', NOCASE)
cur = con.cursor()
cur.execute('SELECT * FROM foo ORDER BY text ASC')
print cur.fetchall()
Output:
comparing 'test' with 'TEST'...
comparing 'test' with 'uest'...
comparing 'TEST' with 'uest'...
comparing 'TEST' with 'UEST'...
comparing 'uest' with 'UEST'...
[(1, u'test'), (2, u'TEST'), (3, u'uest'), (4, u'UEST')]
Similarly, using a defined function works fine (same dataset)
def my_lower(text):
print "I'm lowering %r myself" % (text,)
return text.lower()
con.create_function('lower', 1, my_lower)
cur.execute('SELECT lower(text) FROM foo')
The output:
I'm lowering u'test' myself
I'm lowering u'TEST' myself
I'm lowering u'uest' myself
I'm lowering u'UEST' myself
[(u'test',), (u'test',), (u'uest',), (u'uest',)]
Similarly, for LIKE operations, you have to register the function in its 2-arguments form (X LIKE Y) and in its 3-arguments form (X LIKE Y ESCAPE Z) if you plan to support both forms:
def my_like(a, b, escape=None):
print 'checking if %r matches %r' % (a, b)
return b.lower().startswith(a[0].lower())
con.create_function('like', 2, my_like) # X LIKE Y
con.create_function('like', 3, my_like) # X LIKE Y ESCAPE Z
cur.execute('SELECT * FROM foo WHERE text LIKE ?', (u't%',))
yields the output:
checking if u't%' matches u'test'
checking if u't%' matches u'TEST'
checking if u't%' matches u'uest'
checking if u't%' matches u'UEST'
[(1, u'test'), (2, u'TEST')]
| How do I get case-insensitive queries on non-ASCII with python and sqlite3? | There are some obvious tips and resources about this, but I can't find any direct examples.
http://www.sqlite.org/faq.html#q18 says one can override the NOCASE collation, and the like, lower, and upper functions. I've done so, in a Django testcase, but in my test none of them are actually called.
from django.test import TestCase
from django.contrib.sites.models import Site
from basic.blog.models import Post, Settings
class CaseInsenstiveTest(TestCase):
def setUp(self):
self.site = Site.objects.create()
self.settings = Settings.objects.create(site=self.site)
Settings.get_current = classmethod(lambda cls: self.settings)
def testLike(self):
from django.db import connection
Post.objects.all() # Sets up the connection
def like(x, y, z=None):
"""Y LIKE X [ESCAPE Z]"""
assert x.startswith('%') and x.endswith('%')
like.called = True
print "like(%r, %r, %r)" % (x, y, z)
return x[1:-1].lower() in y.lower()
like.called = False
def lower(s):
print "lower(%r)" % (s,)
return s.lower()
def upper(s):
print "upper(%r)" % (s,)
return s.upper()
connection.connection.create_function('lower', 1, lower)
connection.connection.create_function('upper', 1, upper)
connection.connection.create_function('like', 3, like)
def NOCASE(a, b):
print "NOCASE(%r, %r)" % (a, b)
return cmp(a.lower(), b.lower())
connection.connection.create_collation('NOCASE', NOCASE)
Post.objects.create(slug='foo', title='Foo')
Post.objects.filter(title__icontains='foo')
it seems not a single of the registered functions or the collation are actually called. Can anyone point out what is wrong?
NOTE: I know the like function is not correct, yet. I'm just trying to figure out when what is called so I know what I need to override and how.
| [
"It seems to work fine outside django:\nSo maybe you have a django problem? Are you sure the table fields were created using the NOCASE collation?\nimport sqlite3\n\ndef NOCASE(a, b):\n print 'comparing %r with %r...' % (a, b)\n return cmp(a.lower(), b.lower())\n\ncon = sqlite3.connect('')\n\ncur = con.cursor... | [
2
] | [] | [] | [
"django",
"python",
"sqlite",
"unicode"
] | stackoverflow_0004124557_django_python_sqlite_unicode.txt |
Q:
python getpass encoding
Imagine I have the following code:
# -*- coding: utf-8 -*-
from getpass import getpass
#print u'Введите пароль!'.encode('cp866')
passwd = getpass (u'Введите пароль!'.encode('cp866'))
This is for asking user to enter his password in Windows console (thus encoding is 'cp866'). The user sees the following prompt: "???¤?a? ? aR?i!"
But if you uncomment the line with print, you will see the correct text.
I already have a workaround, first make a print statement, then issue getpass with empty prompt, but I just want to know what exactly is wrong with my code and why do I get this result?
One hint if it make it clearer: getpass uses msvcrt.putch (char) to put characters on the console.
A:
putch() might be doing its own translation from your ANSI codepage (cp1251) to your OEM codepage (cp866). Try encoding with cp1251 instead.
A:
The state of unicode is really embarassing in Python in my experience. From time to time I encounter these type of problems in several libraries suffering from UTF myopia. As in kichik's answer, most of the time changing the encoding to an archaic one is the only solution. See http://bugs.python.org/issue1436203 for your particular bug.
However this might not be applicable in a site-wide scheme that uses unicode exclusively. If this is the case, your only option would be duplicating the functionality of the so called 'protable' getpass using raw_input, sys.stdin or the likes.
| python getpass encoding | Imagine I have the following code:
# -*- coding: utf-8 -*-
from getpass import getpass
#print u'Введите пароль!'.encode('cp866')
passwd = getpass (u'Введите пароль!'.encode('cp866'))
This is for asking user to enter his password in Windows console (thus encoding is 'cp866'). The user sees the following prompt: "???¤?a? ? aR?i!"
But if you uncomment the line with print, you will see the correct text.
I already have a workaround, first make a print statement, then issue getpass with empty prompt, but I just want to know what exactly is wrong with my code and why do I get this result?
One hint if it make it clearer: getpass uses msvcrt.putch (char) to put characters on the console.
| [
"putch() might be doing its own translation from your ANSI codepage (cp1251) to your OEM codepage (cp866). Try encoding with cp1251 instead.\n",
"The state of unicode is really embarassing in Python in my experience. From time to time I encounter these type of problems in several libraries suffering from UTF myop... | [
1,
0
] | [] | [] | [
"encoding",
"python",
"windows"
] | stackoverflow_0004124711_encoding_python_windows.txt |
Q:
How do I check if a module/class/methods has changed and log the changes?
I am trying to compare two modules/classes/method and to find out if the class/method has have changed. We allow users to change classes/methods, and after processing, we make those changes persistent, without overwriting the older classes/methods. However, before we commit the new classes, we need to establish if the code has changed and also if the functionally of the methods has changed e.g output differ and performance also defer on the same input data. I am ok with performance change, but my problem is changes in code and how to log - what has changed. i wrote something like below
class TestIfClassHasChanged(unittest.TestCase):
def setUp(self):
self.old = old_class()
self.new = new_class()
def test_if_code_has_changed(self):
# simple case for one method
old_codeobject = self.old.area.func_code.co_code
new_codeobject = self.new.area.func_code.co_code
self.assertEqual(old_codeobject, new_codeobject)
where area() is a method in both classes.. However, if I have many methods, what i see here is looping over all methods. Possible to do this at class or module level?
Secondly if I find that the code objects are not equal, I would like to log the changes. I used inspect.getsource(self.old.area) and inspect.getsource(self.new.area) compared the two to get the difference, could there be a better way of doing this?
A:
You should be using a version control program to help manage development. This is one of the specific d=features you get from vc program is the ability to track changes. You can do diffs between current source code and previous check-ins to test if there were any changes.
A:
if i have many methods, what i see
here is looping over all methods.
Possible to do this at class or module
level?
i will not ask why you want to do such thing ? but yes you can here is an example
import inspect
import collections
# Here i will loop over all the function in a module
module = __import__('inspect') # this is fun !!!
# Get all function in the module.
list_functions = inspect.getmembers(module, inspect.isfunction)
# Get classes and methods correspond .
list_class = inspect.getmembers(module, inspect.isclass)
class_method = collections.defaultdict(list)
for class_name, class_obj in list_class:
for method in inspect.getmembers(class_obj, inspect.ismethod):
class_method[class_name].append(method)
| How do I check if a module/class/methods has changed and log the changes? | I am trying to compare two modules/classes/method and to find out if the class/method has have changed. We allow users to change classes/methods, and after processing, we make those changes persistent, without overwriting the older classes/methods. However, before we commit the new classes, we need to establish if the code has changed and also if the functionally of the methods has changed e.g output differ and performance also defer on the same input data. I am ok with performance change, but my problem is changes in code and how to log - what has changed. i wrote something like below
class TestIfClassHasChanged(unittest.TestCase):
def setUp(self):
self.old = old_class()
self.new = new_class()
def test_if_code_has_changed(self):
# simple case for one method
old_codeobject = self.old.area.func_code.co_code
new_codeobject = self.new.area.func_code.co_code
self.assertEqual(old_codeobject, new_codeobject)
where area() is a method in both classes.. However, if I have many methods, what i see here is looping over all methods. Possible to do this at class or module level?
Secondly if I find that the code objects are not equal, I would like to log the changes. I used inspect.getsource(self.old.area) and inspect.getsource(self.new.area) compared the two to get the difference, could there be a better way of doing this?
| [
"You should be using a version control program to help manage development. This is one of the specific d=features you get from vc program is the ability to track changes. You can do diffs between current source code and previous check-ins to test if there were any changes.\n",
"\nif i have many methods, what i ... | [
1,
0
] | [] | [] | [
"code_analysis",
"comparison",
"python",
"unit_testing"
] | stackoverflow_0004125282_code_analysis_comparison_python_unit_testing.txt |
Q:
Python: Permission issue when installing an egg
Tried installing South sitewide with easy_install. However I'm having permission issues:
drwxr-x--- 2 root root 4096 Nov 8 10:23 South-0.7.2-py2.6.egg-info
I then tried installing it with pip but received the same results.
I am assuming I could fix this by just changing the permissions. However, am I doing something wrong during installation? Or is there something wrong with the package?
Answers to comments
iddqd: Please send output. sudo pip install -e hg+http : //bitbucket.org/andrewgodwin/south/
Here is the results:
$ sudo pip-python install -e hg+http://bitbucket.org/andrewgodwin/south/
--editable=hg+http://bitbucket.org/andrewgodwin/south/ is not the right format; it must have #egg=Package
A:
It could be your user and/or root have a specific umask which creates files with those permissions such as 0027.
% umask
027
% sudo touch /tmp/foo
% ls -l /tmp/foo
-rw-r----- 1 root wheel 0 Nov 8 08:19 /tmp/foo
% umask 002
% touch /tmp/bar
% ls -al /tmp/bar
-rw-r--r-- 1 root wheel 0 Nov 8 08:23 /tmp/bar
| Python: Permission issue when installing an egg | Tried installing South sitewide with easy_install. However I'm having permission issues:
drwxr-x--- 2 root root 4096 Nov 8 10:23 South-0.7.2-py2.6.egg-info
I then tried installing it with pip but received the same results.
I am assuming I could fix this by just changing the permissions. However, am I doing something wrong during installation? Or is there something wrong with the package?
Answers to comments
iddqd: Please send output. sudo pip install -e hg+http : //bitbucket.org/andrewgodwin/south/
Here is the results:
$ sudo pip-python install -e hg+http://bitbucket.org/andrewgodwin/south/
--editable=hg+http://bitbucket.org/andrewgodwin/south/ is not the right format; it must have #egg=Package
| [
"It could be your user and/or root have a specific umask which creates files with those permissions such as 0027.\n% umask\n027\n% sudo touch /tmp/foo\n% ls -l /tmp/foo\n-rw-r----- 1 root wheel 0 Nov 8 08:19 /tmp/foo\n% umask 002\n% touch /tmp/bar\n% ls -al /tmp/bar\n-rw-r--r-- 1 root wheel 0 Nov 8 08:23 /t... | [
6
] | [] | [] | [
"distribute",
"egg",
"python",
"setuptools"
] | stackoverflow_0004125237_distribute_egg_python_setuptools.txt |
Q:
Django template instructions leave space
Instructions like {% block %} and {% load %} leave empty newline after themselves. How can one turn off this feature ?
A:
Spaceless works. It doesn't remove space inside HTML tags within it (but that's a feature, so it doesn't remove all spaces in say a paragraph of text). Do you have a new line before spaceless? Can you give a failing example, tell us your django version (not that it should be relevant?)
E.g., I have code like:
<link rel="stylesheet" type="text/css" href="/media/css/dashboard.css" />
<!--[if lte IE 7]><link rel="stylesheet" type="text/css" href="/media/css/ie.css" /><![endif]-->{% spaceless %}
{% block extrahead %}
{% endblock %}
{% endspaceless %}
<meta name="robots" content="NONE,NOARCHIVE" />
</head>
and when I look at the html-source is rendered like:
<link rel="stylesheet" type="text/css" href="/referring_md/media/css/dashboard.css" />
<!--[if lte IE 7]><link rel="stylesheet" type="text/css" href="/media/css/ie.css" /><![endif]-->
<meta name="robots" content="NONE,NOARCHIVE" />
</head>
A:
There is a "spaceless" tag, see http://docs.djangoproject.com/en/1.2/ref/templates/builtins/
A:
There is a "spaceless" tag, see http://docs.djangoproject.com/en/1.2/ref/templates/builtins/
or you just dont make a newline in/after a block/load tag.
| Django template instructions leave space | Instructions like {% block %} and {% load %} leave empty newline after themselves. How can one turn off this feature ?
| [
"Spaceless works. It doesn't remove space inside HTML tags within it (but that's a feature, so it doesn't remove all spaces in say a paragraph of text). Do you have a new line before spaceless? Can you give a failing example, tell us your django version (not that it should be relevant?) \nE.g., I have code like... | [
4,
2,
2
] | [] | [] | [
"django",
"python",
"templates"
] | stackoverflow_0004122718_django_python_templates.txt |
Q:
Appending tuples to lists
What's the proper syntax for adding a recomposed tuple to a list?
For example, if I had two lists:
>>> a = [(1,2,3),(4,5,6)]
>>> b = [(0,0)]
Then I would expect the following to work:
>>> b.append((a[0][0],a[0,2]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
Furthermore, when it informs me that indices must be integers, how come this works?
>>> b.append((7,7))
>>> b
[(0, 0), (7, 7)]
A:
you have try to do this:
(a[0][0],a[0,2])
^^^
this is like doing:
(a[0][0],a[(0,2)])
which like the error said : list indices must be integers, not tuple
if i'm not mistaken, i think you wanted to do:
b.append((a[0][0],a[0][2]))
A:
Your problem is this:
b.append((a[0][0],a[0,2]))
^
You try to use the nonexistent tuple index [0, 2] when you mean [0][2]
A:
The indices must be integers. It's just a typo where you have a[0,2] instead of a[0][2]. The [0,2] is an attempt to index by tuple.
A:
a[0,2] is your problem.
It's not complaining about the append, it's telling you that [0,2] cannot be used as an index for the list a.
| Appending tuples to lists | What's the proper syntax for adding a recomposed tuple to a list?
For example, if I had two lists:
>>> a = [(1,2,3),(4,5,6)]
>>> b = [(0,0)]
Then I would expect the following to work:
>>> b.append((a[0][0],a[0,2]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
Furthermore, when it informs me that indices must be integers, how come this works?
>>> b.append((7,7))
>>> b
[(0, 0), (7, 7)]
| [
"you have try to do this: \n(a[0][0],a[0,2])\n ^^^\n\nthis is like doing:\n(a[0][0],a[(0,2)])\n\nwhich like the error said : list indices must be integers, not tuple\nif i'm not mistaken, i think you wanted to do:\nb.append((a[0][0],a[0][2]))\n\n",
"Your problem is this:\nb.append((a[0][0],a[0,2]))\n... | [
4,
1,
1,
0
] | [] | [] | [
"list",
"python",
"tuples"
] | stackoverflow_0004126227_list_python_tuples.txt |
Q:
Regular expression in python
How i can write a regular expression for validate a "right Human Name":
My definition of human name (in this case):
I need validate Hispanic names: Something like Maria, John, jon, Andrés will be valid, but something like 'NNNNNatalia' doesn't
I mean this is valid:
Diego
Diego A.
Diego A. Sanabria
This is not valid:
Diego 3
Diiiiiiiego
#$%ego
A:
This is way beyond the scope of regular expressions. You'll need a Dictionary of names, and possibly an algorithm to check for things which aren't in your dictionary but are names (do some research into Markov Chains for a start). You'll then need some Natural Language Processing algorithms to parse the syntax for valid names.
In short: Take a degree in Computer Science, and this might be a potential Dissertation project.
A:
I'm sure someone else has a better expression, but ([A-Za-z.]+) ?([A-Z]\.?)? ?([A-Za-z]+) will match your input text. It will also match lots of other things.
It won't match Mário or François or 優恵. It won't match names containing more than 3 words, or hyphenated last names, etc. It won't match "Bobby Tables" ...
Assuming you're working with names written in latin characters, you may be able to match words against a list of first names. When you find a first name (assuming that first names come first in your data), then inspect the next couple of words to see if they could also be names.
It's generally better to let humans enter their own names.
| Regular expression in python | How i can write a regular expression for validate a "right Human Name":
My definition of human name (in this case):
I need validate Hispanic names: Something like Maria, John, jon, Andrés will be valid, but something like 'NNNNNatalia' doesn't
I mean this is valid:
Diego
Diego A.
Diego A. Sanabria
This is not valid:
Diego 3
Diiiiiiiego
#$%ego
| [
"This is way beyond the scope of regular expressions. You'll need a Dictionary of names, and possibly an algorithm to check for things which aren't in your dictionary but are names (do some research into Markov Chains for a start). You'll then need some Natural Language Processing algorithms to parse the syntax for... | [
6,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004126249_python_regex.txt |
Q:
Scheduling Tasks
I run MAC OS X.
So I have completed a python script that essentially parses a few sites online, and uploads a particular file to an online server. Essentially, I wish to run this script automatically from my computer about 20 times a day. Is there a solution to schedule this script to run at fixed time points everyday? Does this require compiling the python code into a .exe file?
Thanks a lot!
A:
The OS provides a tool called 'cron' that's for exactly this purpose. You shouldn't need to modify your script at all to make use of it.
At a terminal command prompt, type man cron for more info.
A:
You can check also launchd, it's the OS X replacement of cron (you can still use cron but it's kind of deprecated on OS X).
Docs: Getting Started with launchd
I can also recommand you Lingo app to help you working with launchd.
| Scheduling Tasks | I run MAC OS X.
So I have completed a python script that essentially parses a few sites online, and uploads a particular file to an online server. Essentially, I wish to run this script automatically from my computer about 20 times a day. Is there a solution to schedule this script to run at fixed time points everyday? Does this require compiling the python code into a .exe file?
Thanks a lot!
| [
"The OS provides a tool called 'cron' that's for exactly this purpose. You shouldn't need to modify your script at all to make use of it. \nAt a terminal command prompt, type man cron for more info.\n",
"You can check also launchd, it's the OS X replacement of cron (you can still use cron but it's kind of depreca... | [
4,
1
] | [] | [] | [
"python",
"scheduled_tasks"
] | stackoverflow_0004126041_python_scheduled_tasks.txt |
Q:
python 2.7 __init__ behavior on self
I have a python question that I'm sure is pretty simple - please feel free to disabuse me of any sort of bad practice while you're at it. I have the following code:
class User(dict,BaseDBI):
def __init__(self,uid=None,username=None):
self['uid']=str(uuid())
if uid == None and username is not None:
uid_struct = self.Get('data/username.kch',username)
if uid_struct is not None:
self = self.Get('data/user.kch',uid_struct['uid'])
As you can tell this User is simply an extended dict object. It also accesses a few simple Get and Set methods on a couple of Kyoto Cabinet db files. I put in some print statements to trace through what's going on and everything is being set properly, but when I create a User object (e.g.):
user = User(username='someusername')
and then print user I only have a new dict object that has the brand new uid generated by the first line under __init__
Thanks for any wisdom!
A:
python variables are references. when you assign to self, you are replacing that reference but not altering the object which is returned by __init__.
The easiest thing may be to simply use the dict.update method to copy all key/value pairs into self. This should 'just work' since you're already inheriting from dict.
Inheritance is only appropriate for a relationship like A is a B. You indicate that a User is a dict, that's fine, but I doubt that a User is a BaseDBI. It's more likely that you want a User to have a database, in which case composition is more appropriate. This probably seems nit-picky, but will prevent you from making bizarre and obscene systems.
A:
You need to call the inherited constructors. Something like:
def __init__(self,uid=None,username=None):
dict.__init__(self)
BaseDBI.__init__(self)
Also assigning to self will just replace the value in the local variable self. It will not have any effect on the object.
A:
If you need to return an already existing instance or your class, you need to define a __new__ method
By the time __init__ is called, a fresh instance has already been created
| python 2.7 __init__ behavior on self | I have a python question that I'm sure is pretty simple - please feel free to disabuse me of any sort of bad practice while you're at it. I have the following code:
class User(dict,BaseDBI):
def __init__(self,uid=None,username=None):
self['uid']=str(uuid())
if uid == None and username is not None:
uid_struct = self.Get('data/username.kch',username)
if uid_struct is not None:
self = self.Get('data/user.kch',uid_struct['uid'])
As you can tell this User is simply an extended dict object. It also accesses a few simple Get and Set methods on a couple of Kyoto Cabinet db files. I put in some print statements to trace through what's going on and everything is being set properly, but when I create a User object (e.g.):
user = User(username='someusername')
and then print user I only have a new dict object that has the brand new uid generated by the first line under __init__
Thanks for any wisdom!
| [
"python variables are references. when you assign to self, you are replacing that reference but not altering the object which is returned by __init__.\nThe easiest thing may be to simply use the dict.update method to copy all key/value pairs into self. This should 'just work' since you're already inheriting from di... | [
2,
0,
0
] | [] | [] | [
"initialization",
"python"
] | stackoverflow_0004126517_initialization_python.txt |
Q:
How to upload zope site on my ftp?
Hey, I'd like to know how to upload my zope site on my ftp. I have a domain, and I like to upload it, like a upload normal files on my ftp.
Thanks.
A:
You can upload zope the same way you would upload anything else, but it's not suitable for deploying on many shared webhosts as many of them would not like you running the zope process due to the ammount of resources it can consume
You are best off trying to find a webhost that supports zope or to use a VPS
| How to upload zope site on my ftp? | Hey, I'd like to know how to upload my zope site on my ftp. I have a domain, and I like to upload it, like a upload normal files on my ftp.
Thanks.
| [
"You can upload zope the same way you would upload anything else, but it's not suitable for deploying on many shared webhosts as many of them would not like you running the zope process due to the ammount of resources it can consume\nYou are best off trying to find a webhost that supports zope or to use a VPS\n"
] | [
2
] | [] | [] | [
"frameworks",
"python",
"zope",
"zope.interface"
] | stackoverflow_0004126247_frameworks_python_zope_zope.interface.txt |
Q:
Multiplying transformation matrix to a vector
I have done a series of transformations using glMultMatrix. How do I multiply a vector (nX, nY, nZ, 1) to the matrix I have from the transformation? How do I get that matrix to multiply with a vector?
pyglet.gl.lib.GLException: invalid operation
I am getting above error if I use glMultMatrix. I need to call this multiplication between glBegin and glEnd.
A:
If I'm reading your question right, you want something that returns the result of a Matrix-vector product between the current ModelView/Projection matrix and a vector you specify.
In that case, OpenGL can't do the multiplication for you. Instead, you need to extract the current matrix and do the multiplication yourself:
import numpy as np
someVector = np.array([2,3,4,5])
glMatrixMode(GL_MODELVIEW)
glMultMatrix(...)
modelViewMatrix = glGetDoublev(GL_MODELVIEW_MATRIX)
result = np.dot(modelViewMatrix, someVector)
Depending on what you're trying to do, you might need to get both the ModelView and Projection matrices and multiply them first.
| Multiplying transformation matrix to a vector | I have done a series of transformations using glMultMatrix. How do I multiply a vector (nX, nY, nZ, 1) to the matrix I have from the transformation? How do I get that matrix to multiply with a vector?
pyglet.gl.lib.GLException: invalid operation
I am getting above error if I use glMultMatrix. I need to call this multiplication between glBegin and glEnd.
| [
"If I'm reading your question right, you want something that returns the result of a Matrix-vector product between the current ModelView/Projection matrix and a vector you specify.\nIn that case, OpenGL can't do the multiplication for you. Instead, you need to extract the current matrix and do the multiplication yo... | [
0
] | [] | [] | [
"opengl",
"python"
] | stackoverflow_0004102872_opengl_python.txt |
Q:
Simple python re lookahead help
I have three sample twiki names:
names = [ "JohnDoe", "JaneMcAdams", "BillyBobThorton" ]
I want to get the following back:
* John Doe
* Jane McAdams
* BillyBob Thorton
Now I have this which busts them apart on the cap (That's a good thing).
re.findall('[A-Z][^A-Z]*', name)
How do I ignore "Mc" as a split?
Thanks!!
A:
I would recommend against using a regex here. I doubt Mc is the only name particle you need to match. Did you think about Mac, O, Van, Von, De?
I suggest to break them as you say you currently do and build the first name and last name manually.
Bonus. Regex:
re.findall('(?:Mc|Mac|O|Van|Von|De)?[A-Z][^A-Z]*', name)
But Van, Von, De should be separated with a space.
Note: If you say you only want to match McSomething use the a short version (?:Mc)?[A-Z][^A-Z]*.
| Simple python re lookahead help | I have three sample twiki names:
names = [ "JohnDoe", "JaneMcAdams", "BillyBobThorton" ]
I want to get the following back:
* John Doe
* Jane McAdams
* BillyBob Thorton
Now I have this which busts them apart on the cap (That's a good thing).
re.findall('[A-Z][^A-Z]*', name)
How do I ignore "Mc" as a split?
Thanks!!
| [
"I would recommend against using a regex here. I doubt Mc is the only name particle you need to match. Did you think about Mac, O, Van, Von, De? \nI suggest to break them as you say you currently do and build the first name and last name manually.\nBonus. Regex:\nre.findall('(?:Mc|Mac|O|Van|Von|De)?[A-Z][^A-Z]*', ... | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004126729_python_regex.txt |
Q:
Creating a list from a CSV file using Python
I have a Python script so far that does what I it to... Opens the CSV Defined by the user, splits the file into different Predefined "pools" and remakes them again into their own files, with proper headers. My only problem is I want to change the Pool list from a static to a variable; and having some issues.
The pool list is in the CSV it self, in column 2. and can be duplicated. Right now with this setup the system can create "Dead" Files with no data aside from the header.
A few notes: Yes I know spelling is not perfect and yes I know what some of my comments are a bit off
import csv
#used to read ane make CSV's
import time
#used to timestamp files
import tkFileDialog
#used to allow user input
filename = tkFileDialog.askopenfilename(defaultextension = ".csv")
#Only user imput to locate the file it self
csvfile = []
#Declairs csvfile as a empty list
pools = ["1","2","4","6","9","A","B","D","E","F","I","K","L","M","N","O","P","W","Y"]
#declairs hte pools list for known pools
for i in pools:
#uses the Pools List and makes a large number of variables
exec("pool"+i+"=[]")
reader = csv.reader(open(filename, "rb"), delimiter = ',')
#Opens the CSV for the reader to use
for row in reader:
csvfile.append(row)
#dumps the CSV into a varilable
headers=[]
#declairs headers as empty list
headers.append(csvfile[0])
#appends the first row to the header variable
for row in csvfile:
pool = str(row[1]).capitalize()
#Checks to make sure all pools in the main data are capitalized
if pool in pools:
exec("pool"+pool+".append(row)")
#finds the pool list and appends the new item into the variable list
else:
pass
for i in pools:
exec("wp=csv.writer(open('pool "+i+" "+time.strftime("%Y%m%d")+".csv','wb'),)")
wp.writerows(headers)
#Adds the header row
exec("wp.writerows(pool"+i+")")
#Created the CSV with a timestamp useing the pool list
#-----Needs Headers writen in on each file -----
EDIT:
As there have been some questions
Reason for the code: I have Daily reports that are being generated, Part of these reports that require a manual process is splitting these reports into different Pool Reports. I was creating this script so that I could quickly select the file it self and quickly split these out into their own files.
The main CSV can be from 50 to 100 items long, it has a total of 25 Columns and the Pool Is always going to be listed on the second column. Not all Pools will be listed all the time, and pools will show up more then once.
I have tried a few different loops so far; one is as follows
pools = []
for line in file(open(filename,'rb')):
line = line.split()
x = line[1]
pools.append(x)
But I get a List error with this.
A example of the CSV:
Ticket Pool Date Column 4 Column 5
1 A 11/8/2010 etc etc
2 A 11/8/2010 etc etc
3 1 11/8/2010 etc etc
4 6 11/8/2010 etc etc
5 B 11/8/2010 etc etc
6 A 11/8/2010 etc etc
7 1 11/8/2010 etc etc
8 2 11/8/2010 etc etc
9 2 11/8/2010 etc etc
10 1 11/8/2010 etc etc
A:
If I am understanding correctly what you want to achieve here this could be as solution:
import csv
import time
import tkFileDialog
filename = tkFileDialog.askopenfilename(defaultextension = ".csv")
reader = csv.reader(open(filename, "rb"), delimiter = ',')
headders = reader.next()
pool_dict = {}
for row in reader:
if not pool_dict.has_key(row[1]):
pool_dict[row[1]] = []
pool_dict[row[1]].append(row)
for key, val in pool_dict.items():
wp = csv.writer(open('pool ' +key+ ' '+time.strftime("%Y%m%d")+'.csv','wb'),)
wp.writerow(headders)
wp.writerows(val)
EDIT: misunderstood the headers and pools thing in the first place and tried to correct the issue.
EDIT 2: corrected the pool to be dynamically created from values found in file.
If not, please provide more details of your Problem…
A:
Can you describe your CSV file a little bit?
One suggestion is to change
for i in pools:
#uses the Pools List and makes a large number of variables
exec("pool"+i+"=[]")
to the more pythonic form:
pool_dict = {}
for i in pools:
pool_dict[i] = []
In general its bad to using eval/exec and much easier to say loop through a dictionary. E.g., access variables by pool_dict['A'], pool_dict['1'] or loop through all of them like
for key,val in pool_dict.items():
val.append(...)
EDIT: Now seeing the CSV data, try something like this:
for row in reader:
if row[0] == 'Ticket':
header = row
else:
cur_pool = row[1].capitalize()
if not pool_dict.has_key(cur_pool):
pool_dict[cur_pool] = [row,]
else:
pool_dict[cur_pool].append(row)
for p, pool_vals in pool_dict.items:
with open('pool'+p+'_'+time.strftime("%Y%m%d")+'.csv','wb'),) as fp:
wp = csv.writer(fp)
wp.writerow(header)
wp.writerows(pool_vals)
A:
You code would be a lot easier to read without all those execs. It seems like you used them to declare all of your variables, when in fact you could declare a list of pools like this:
pool_lists = [[] for p in pools]
This is my best guess for what you mean by "I want to change the Pool list from a static to a variable." When you do this, you will have a list of lists, of the same length as pools.
| Creating a list from a CSV file using Python | I have a Python script so far that does what I it to... Opens the CSV Defined by the user, splits the file into different Predefined "pools" and remakes them again into their own files, with proper headers. My only problem is I want to change the Pool list from a static to a variable; and having some issues.
The pool list is in the CSV it self, in column 2. and can be duplicated. Right now with this setup the system can create "Dead" Files with no data aside from the header.
A few notes: Yes I know spelling is not perfect and yes I know what some of my comments are a bit off
import csv
#used to read ane make CSV's
import time
#used to timestamp files
import tkFileDialog
#used to allow user input
filename = tkFileDialog.askopenfilename(defaultextension = ".csv")
#Only user imput to locate the file it self
csvfile = []
#Declairs csvfile as a empty list
pools = ["1","2","4","6","9","A","B","D","E","F","I","K","L","M","N","O","P","W","Y"]
#declairs hte pools list for known pools
for i in pools:
#uses the Pools List and makes a large number of variables
exec("pool"+i+"=[]")
reader = csv.reader(open(filename, "rb"), delimiter = ',')
#Opens the CSV for the reader to use
for row in reader:
csvfile.append(row)
#dumps the CSV into a varilable
headers=[]
#declairs headers as empty list
headers.append(csvfile[0])
#appends the first row to the header variable
for row in csvfile:
pool = str(row[1]).capitalize()
#Checks to make sure all pools in the main data are capitalized
if pool in pools:
exec("pool"+pool+".append(row)")
#finds the pool list and appends the new item into the variable list
else:
pass
for i in pools:
exec("wp=csv.writer(open('pool "+i+" "+time.strftime("%Y%m%d")+".csv','wb'),)")
wp.writerows(headers)
#Adds the header row
exec("wp.writerows(pool"+i+")")
#Created the CSV with a timestamp useing the pool list
#-----Needs Headers writen in on each file -----
EDIT:
As there have been some questions
Reason for the code: I have Daily reports that are being generated, Part of these reports that require a manual process is splitting these reports into different Pool Reports. I was creating this script so that I could quickly select the file it self and quickly split these out into their own files.
The main CSV can be from 50 to 100 items long, it has a total of 25 Columns and the Pool Is always going to be listed on the second column. Not all Pools will be listed all the time, and pools will show up more then once.
I have tried a few different loops so far; one is as follows
pools = []
for line in file(open(filename,'rb')):
line = line.split()
x = line[1]
pools.append(x)
But I get a List error with this.
A example of the CSV:
Ticket Pool Date Column 4 Column 5
1 A 11/8/2010 etc etc
2 A 11/8/2010 etc etc
3 1 11/8/2010 etc etc
4 6 11/8/2010 etc etc
5 B 11/8/2010 etc etc
6 A 11/8/2010 etc etc
7 1 11/8/2010 etc etc
8 2 11/8/2010 etc etc
9 2 11/8/2010 etc etc
10 1 11/8/2010 etc etc
| [
"If I am understanding correctly what you want to achieve here this could be as solution:\nimport csv\nimport time\nimport tkFileDialog\n\nfilename = tkFileDialog.askopenfilename(defaultextension = \".csv\")\n\nreader = csv.reader(open(filename, \"rb\"), delimiter = ',')\n\nheadders = reader.next()\n\npool_dict = {... | [
4,
2,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0004126423_csv_python.txt |
Q:
(Python) gaierror: [Errno 11004] getaddrinfo failed
from Tkinter import *
import tkMessageBox, socket
root = Tk()
root.title("pynet v1.0")
root.config(bg='black')
root.resizable(0,0)
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.config(bg="white", fg="red")
text1.pack()
def Info():
targetip = socket.gethostbyname_ex(text1.get("1.0", END))
text.insert(END, targetip)
b = Button(root, text="Enter", width=10, height=2, command=Info)
b.config(fg="black", bg="red")
b.pack(side=TOP, padx=5)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=25, height=5, bg="white", fg="red")
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
I'm trying to retrieve the IP Address of a website, but I keep getting this error, "gaierror: [Errno 11004] getaddrinfo failed" in line 18, your help will be appreciated, Thanks.
The Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Rabia\Desktop\gethostinfo.py", line 18, in Info
targetip = socket.gethostbyname_ex(text1.get("1.0", END))
gaierror: [Errno 11004] getaddrinfo failed
A:
My guess is because you are using a hostname that has a trailing newline. At the time I write this answer, your code shows:
def Info():
targetip = socket.gethostbyname_ex(text1.get("1.0", END))
text.insert(END, targetip)
When you use the index END you get the extra newline that is added by the text widget. You need to strip that off or use the index "end-1c".
A:
Why are you adding CRLF (\r\n) to the hostname before looking it up?
If removing that doesn't fix it, print out the exact text you're passing to gethostbyname to make sure it's a valid hostname.
| (Python) gaierror: [Errno 11004] getaddrinfo failed | from Tkinter import *
import tkMessageBox, socket
root = Tk()
root.title("pynet v1.0")
root.config(bg='black')
root.resizable(0,0)
text = Text()
text1 = Text()
text1.config(width=15, height=1)
text1.config(bg="white", fg="red")
text1.pack()
def Info():
targetip = socket.gethostbyname_ex(text1.get("1.0", END))
text.insert(END, targetip)
b = Button(root, text="Enter", width=10, height=2, command=Info)
b.config(fg="black", bg="red")
b.pack(side=TOP, padx=5)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=25, height=5, bg="white", fg="red")
text.pack(side=LEFT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
root.mainloop()
I'm trying to retrieve the IP Address of a website, but I keep getting this error, "gaierror: [Errno 11004] getaddrinfo failed" in line 18, your help will be appreciated, Thanks.
The Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python26\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Rabia\Desktop\gethostinfo.py", line 18, in Info
targetip = socket.gethostbyname_ex(text1.get("1.0", END))
gaierror: [Errno 11004] getaddrinfo failed
| [
"My guess is because you are using a hostname that has a trailing newline. At the time I write this answer, your code shows:\ndef Info():\n targetip = socket.gethostbyname_ex(text1.get(\"1.0\", END))\n text.insert(END, targetip)\n\nWhen you use the index END you get the extra newline that is added by the text... | [
2,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0004126023_python_tkinter.txt |
Q:
Ambiguous tab completion not working in iPython on Windows
I am running IPython on Windows 7 x64 with pyreadline installed. If I start a new session and type:
import numpy
nu<TAB>
Then nu autocompletes to numpy. However, if I start a new session and try this:
import numpy
n<TAB>
Then nothing happens. I would expect it to cycle through all of the possible completions. I'm currently using out of the box config, do I need to change a setting to enable ambiguous tab completion or am I just out of luck?
EDIT:
To address the comment from ma3204, here is another example (start with fresh ipython session):
[In 1]: value1 = 5
[In 2]: value2 = 6
[In 3]: va<TAB> ... nothing happens
[In 3]: va<Ctrl + l>
vars value2 value1
[In 3]: val<TAB> ... completes to 'value'
[In 3]: value
[In 3]: value<Ctrl + l>
value2 value1
[In 3]: value
When I type va<TAB> above I would expect each tab press to cycle through value1, value2, vars, value1, value2, etc.
A:
You have to copy config file for pyreadline to your HOME folder (C:\Users\< username >).
Open Command line and execute that:
copy "C:\Program Files (x86)\Python26\Lib\site-packages\pyreadline\configuration\pyreadlineconfig.ini" %HOMEPATH%
A:
Just installed python 2.6 and numpy, ipython and so on. I am also annoyed of this. On my other computers with older installations it works. I use the completions list very much to see what commands are available so I feel frustrated when it doesn't work.
EDIT: Found that you can get it with CTRL-l. Looked in ipythonrc and it should work like I am used to but not. The CTRL-l work though. Will see if it kicks back on. Seem to remember that I had similar trouble before but it worked after some time.
| Ambiguous tab completion not working in iPython on Windows | I am running IPython on Windows 7 x64 with pyreadline installed. If I start a new session and type:
import numpy
nu<TAB>
Then nu autocompletes to numpy. However, if I start a new session and try this:
import numpy
n<TAB>
Then nothing happens. I would expect it to cycle through all of the possible completions. I'm currently using out of the box config, do I need to change a setting to enable ambiguous tab completion or am I just out of luck?
EDIT:
To address the comment from ma3204, here is another example (start with fresh ipython session):
[In 1]: value1 = 5
[In 2]: value2 = 6
[In 3]: va<TAB> ... nothing happens
[In 3]: va<Ctrl + l>
vars value2 value1
[In 3]: val<TAB> ... completes to 'value'
[In 3]: value
[In 3]: value<Ctrl + l>
value2 value1
[In 3]: value
When I type va<TAB> above I would expect each tab press to cycle through value1, value2, vars, value1, value2, etc.
| [
"You have to copy config file for pyreadline to your HOME folder (C:\\Users\\< username >).\nOpen Command line and execute that:\ncopy \"C:\\Program Files (x86)\\Python26\\Lib\\site-packages\\pyreadline\\configuration\\pyreadlineconfig.ini\" %HOMEPATH%\n\n",
"Just installed python 2.6 and numpy, ipython and so on... | [
9,
6
] | [] | [] | [
"ipython",
"python",
"tab_completion"
] | stackoverflow_0003771837_ipython_python_tab_completion.txt |
Q:
[Python]How to deal with a string ending with one backslash?
I'm getting some content from Twitter API, and I have a little problem, indeed I sometimes get a tweet ending with only one backslash.
More precisely, I'm using simplejson to parse Twitter stream.
How can I escape this backslash ?
From what I have read, such raw string shouldn't exist ...
Even if I add one backslash (with two in fact) I still get an error as I suspected (since I have a odd number of backslashes)
Any idea ?
I can just forget about these tweets too, but I'm still curious about that.
Thanks : )
A:
Prepending the string with r (stands for "raw") will escape all characters inside the string. For example:
print r'\b\n\\'
will output
\b\n\\
Have I understood the question correctly?
A:
I guess you are looking a method similar to stripslashes in PHP. So, here you go:
Python version of PHP's stripslashes
A:
You can try using raw strings by prepending an r (so nothing has to be escaped) to the string or re.escape().
I'm not really sure what you need considering I haven't seen the text of the response. If none of the methods you come up with on your own or get from here work, you may have to forget about those tweets.
A:
Unless you update your question and come back with a real problem, I'm asserting that you don't have an issue except confusion.
You get the string from the Tweeter API, ergo the string does not show up in your code. “Raw strings” exist only in your code, and it is “raw strings” in code that can't end in a backslash.
Consider this:
def some_obscure_api():
"This exists in a library, so you don't know what it does"
return r"hello" + "\\" # addition just for fun
my_string = some_obscure_api()
print(my_string)
See? my_string happily ends in a backslash and your code couldn't care less.
| [Python]How to deal with a string ending with one backslash? | I'm getting some content from Twitter API, and I have a little problem, indeed I sometimes get a tweet ending with only one backslash.
More precisely, I'm using simplejson to parse Twitter stream.
How can I escape this backslash ?
From what I have read, such raw string shouldn't exist ...
Even if I add one backslash (with two in fact) I still get an error as I suspected (since I have a odd number of backslashes)
Any idea ?
I can just forget about these tweets too, but I'm still curious about that.
Thanks : )
| [
"Prepending the string with r (stands for \"raw\") will escape all characters inside the string. For example:\nprint r'\\b\\n\\\\'\nwill output\n\\b\\n\\\\\nHave I understood the question correctly?\n",
"I guess you are looking a method similar to stripslashes in PHP. So, here you go:\nPython version of PHP's str... | [
1,
1,
1,
0
] | [] | [] | [
"backslash",
"escaping",
"python",
"string"
] | stackoverflow_0004121751_backslash_escaping_python_string.txt |
Q:
Solving statistics question using Python
I'm really lost. How can I approach this problem?
Beginning with $1 of capital, you choose a fixed proportion p of your capital to bet on a fair coin tossed repeatedly for 1000 times. Your returns is doubled if the toss lands head and you lose your it lands tail. For example, if p=0.25 and for the first toss your bet $0.25, and if heads appears you win $0.5, and so you have $1.50. You continue to bet $0.375 on the second attempt and if the second toss lands tail, you have $1.125 left.
Suppose p is chosen to maximise the chance of having at least a billion dollar after 1000 flips, what is the chance that you become a billionaire?
How can you use Python to code out this scenario and come out with an answer?
A:
Do you have any experience with python? If not, read the tutorial.
To solve your problem, you should first write down some kind of pseudo-code. Your first attempt can be very general, and then you should go into more detail about specific operations, until in the end you actually go and implement it. Think about details such as, what pre-conditions do you have and what post-condition do you need?
A:
Here are some tips. The order of the wins and losses doesn't affect the total amount of money in the end because multiplications commute. Therefore, the total amount of money after all of the tosses (when starting with $1) is equal to 1 * (1+2*p)^(W) * (1-p)^(1000-W) where W is the number of total wins out of 1000 tosses (and therefore 1000 - W is the number of losses). This will allow you to determine if, for a given number of wins, W, you obtain more than a billion dollars. However, there are many more ways to win 500/lose 500 than to win 1000/lose 0. You can find the number of ways to have W wins out of 1000 tosses by using the binomial coefficient.
If you put these ideas to proper use then you can find a p that maximizes the probability. However, you should note that there is actually a range of p that all give an equal chance of going over a billion dollars. They do not all yield the same amount of money though.
A:
The obvious place to start is to write some code that will simulate performing 1000 coin tosses and give you a value for capital at the end. This is basically trivial:
def _mc(p):
capital = 1.0
for _ in xrange(1000):
if random.random() < 0.5:
capital *= 1 + p
else:
capital *= 1 - p
return capital
Notice that capital will probably end up being tiny. That's fine.
Now this is obviously heavily dependent on what the random flips are, which is bad. So you should work out its expected value by performing lots of 1000-coin-flip-chains and doing some sort of statistics on what you think it should be.
Finally, you want do to all of this for a range of values of p, probably between 0 and 0.2. You could use matplotlib to plot a graph of p against expected outcome to get an idea of what p should be best.
Note that Python is probably not the best language for this sort of thing; C would be much faster and you don't really need the flexibility of Python anyway.
| Solving statistics question using Python | I'm really lost. How can I approach this problem?
Beginning with $1 of capital, you choose a fixed proportion p of your capital to bet on a fair coin tossed repeatedly for 1000 times. Your returns is doubled if the toss lands head and you lose your it lands tail. For example, if p=0.25 and for the first toss your bet $0.25, and if heads appears you win $0.5, and so you have $1.50. You continue to bet $0.375 on the second attempt and if the second toss lands tail, you have $1.125 left.
Suppose p is chosen to maximise the chance of having at least a billion dollar after 1000 flips, what is the chance that you become a billionaire?
How can you use Python to code out this scenario and come out with an answer?
| [
"Do you have any experience with python? If not, read the tutorial.\nTo solve your problem, you should first write down some kind of pseudo-code. Your first attempt can be very general, and then you should go into more detail about specific operations, until in the end you actually go and implement it. Think about ... | [
1,
1,
0
] | [] | [] | [
"python",
"statistics"
] | stackoverflow_0004124568_python_statistics.txt |
Q:
Sandboxed AND stackless python?
I need a scripting language for describing very complicated workflows.
These workflows need to be paused
whenever user input is required, and
resumed after it is given (could be
months later). Seems like serializable continuations from Stackless would be a good fit.
Users also need to be able to edit
the workflows themselves. I'm not sure how serialized continuations would handle underlying code changes. I think I might need to save the Git version hash along with the continuation, and only 'upgrade' a continuation at checkpoints where no state is needed.
I prefer the Python syntax since
readability is a very high priority,
and dynamic features are key. I'm open to suggestions, though.
Eventually I'll probably write a visual flow-chart editor that maniupulates the underlying code.
I've looked in depth at Stackless and PyPy. Stackless doesn't seem to offer any promises of sandboxing, while PyPy seems to offer both stackless and sandboxed, but I can't find any mention of having both at the same time.
Any solutions? If there's an expert out there who can get me going with a good solution, I've got a paypal account and I'm willing to use it.
A:
Your serialization requirement will be difficult in most languages with native co-routine libraries. You might need to implement co-routines in another way to allow for object graph serialization.
Lua has the Pluto library, which CAN persist threads (co-routines): http://lua-users.org/wiki/PlutoLibrary
As far as "safe" execution in a sandbox, Lua is a first choice. You can have multiple lua states in a single application with zero issues, and it supports co-routines in the language. It also has the benefit of being quite fast in its VM form, and with luajit is competitive with Java JIT in many cases.
| Sandboxed AND stackless python? | I need a scripting language for describing very complicated workflows.
These workflows need to be paused
whenever user input is required, and
resumed after it is given (could be
months later). Seems like serializable continuations from Stackless would be a good fit.
Users also need to be able to edit
the workflows themselves. I'm not sure how serialized continuations would handle underlying code changes. I think I might need to save the Git version hash along with the continuation, and only 'upgrade' a continuation at checkpoints where no state is needed.
I prefer the Python syntax since
readability is a very high priority,
and dynamic features are key. I'm open to suggestions, though.
Eventually I'll probably write a visual flow-chart editor that maniupulates the underlying code.
I've looked in depth at Stackless and PyPy. Stackless doesn't seem to offer any promises of sandboxing, while PyPy seems to offer both stackless and sandboxed, but I can't find any mention of having both at the same time.
Any solutions? If there's an expert out there who can get me going with a good solution, I've got a paypal account and I'm willing to use it.
| [
"Your serialization requirement will be difficult in most languages with native co-routine libraries. You might need to implement co-routines in another way to allow for object graph serialization. \nLua has the Pluto library, which CAN persist threads (co-routines): http://lua-users.org/wiki/PlutoLibrary\nAs far a... | [
2
] | [] | [] | [
"continuations",
"jit",
"pypy",
"python",
"python_stackless"
] | stackoverflow_0004126863_continuations_jit_pypy_python_python_stackless.txt |
Q:
WTforms: Error "field not present"
Hi I have a form class which looks like below:-
class UserCreateForm(wtf.Form):
name=wtf.TextField('Name',validators=[validators.Required(),username_check])
email=wtf.TextField('Email')
userimage=wtf.FileField(u'Upload Image',validators=[checkfile])
The custom validator function " checkfile" looks like this:-
def checkfile(form,field):
if field.data:
filename=field.data.lower()
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
if not ('.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS):
raise ValidationError('Wrong Filetype, you can upload only png,jpg,jpeg,gif files')
else:
raise ValidationError('field not Present') # I added this justfor some debugging.
However I find that even though I browse a file in the template and
click submit , it always raises the error "field not present". I am a
little confused here . Is field.data not the right way to check for
the presence of filenames
A:
Solved this finally , had to replace field.data in the validator with field.file and then access its attributes using field.file.filename.
| WTforms: Error "field not present" | Hi I have a form class which looks like below:-
class UserCreateForm(wtf.Form):
name=wtf.TextField('Name',validators=[validators.Required(),username_check])
email=wtf.TextField('Email')
userimage=wtf.FileField(u'Upload Image',validators=[checkfile])
The custom validator function " checkfile" looks like this:-
def checkfile(form,field):
if field.data:
filename=field.data.lower()
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
if not ('.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS):
raise ValidationError('Wrong Filetype, you can upload only png,jpg,jpeg,gif files')
else:
raise ValidationError('field not Present') # I added this justfor some debugging.
However I find that even though I browse a file in the template and
click submit , it always raises the error "field not present". I am a
little confused here . Is field.data not the right way to check for
the presence of filenames
| [
"Solved this finally , had to replace field.data in the validator with field.file and then access its attributes using field.file.filename.\n"
] | [
7
] | [] | [] | [
"flask",
"flask_wtforms",
"forms",
"python",
"wtforms"
] | stackoverflow_0004058308_flask_flask_wtforms_forms_python_wtforms.txt |
Q:
Python import module results in NameError
I'm having a module import issue.
using python 2.6 on ubuntu 10.10
I have a class that subclasses the daemon at http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ . I created a python package with a module containing code that imports some models from a django project. The code works when used from a class, not subclassing the daemon. The structure looks something like:
my_module
__init__.py
- bin
- cfg
- core
__init__.py
collection.py
daemon.py
The ItemRepository code:
class ItemRepository(object):
"""This class provides an implementation to retrieve configuration data
from the monocle database
"""
def __init__(self, project_path):
if project_path is not None:
sys.path.append(project_path)
try:
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.someapp.models import ItemConfiguration
except ImportError:
print "Could not import models from web app. Please ensure the\
PYTHONPATH is configured properly"
def get_scheduled_collectors(self):
"""This method finds and returns all ItemConfiguration objects
that are scheduled to run
"""
logging.info('At the error path: %s' % sys.path)
# query ItemConfigs from database
items = ItemConfiguration.objects.filter(disabled=False) #ERROR OCCURS AT THIS LINE
return [item for item in items if item.scheduled]
The daemon code (in /usr/local/bin/testdaemon.py):
import sys
from my_module.core.daemon import Daemon
from my_module.core.collection import ItemRepository
import logging
import time
class TestDaemon(Daemon):
default_conf = '/etc/echodaemon.conf'
section = 'echo'
def run(self):
while True:
logging.info('The echo daemon says hello')
ir = ItemRepository(project_path=self.project_path)
items = ir.get_scheduled_collectors() #TRIGGERS ERROR
logging.info('there are %d scheduled items' % len(items))
time.sleep(1)
if __name__ == '__main__':
TestDaemon().main()
The error I get is "NameError: global name 'my_module' is not defined" It get's past the import but then fails when trying to call a method on the object. I'm assuming it has to do with sys.path / PYTHONPATH, but I know my django project is on the path, as I've printed it out. Nothing so far in the python docs or Learning Python has helped yet. Does anyone have any insights or know of a good reference to module imports?
UPDATE:
Now I've attempted to simplify the problem to make it easier to understand. Now I have a directory structure that looks like:
/home
/username
/django
/someproj
/web
models.py
/my_module
daemon.py
I have set the $PYTHONPATH variable in /etc/bash.bashrc to '/home/username/django'.
Inside the testdaemon.py file the imports look like:
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration
But now I get an ImportError: No module named 'someproj'. So then I appended the path.
import sys
sys.path.append('/home/username/django')
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration
And now the ImportError says: No module named 'web'. Here's the traceback:
Traceback (most recent call last):
File "testdaemon.py", line 77, in <module>
TestDaemon('/tmp/testdaemon.pid').run()
File "testdaemon.py", line 47, in run
scheduled_items = [item for item in ItemConfiguration.objects.filter(disabled=False) if collector.scheduled]
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 141, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1128, in add_q
can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1026, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1179, in setup_joins
field, model, direct, m2m = opts.get_field_by_name(name)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 291, in get_field_by_name
cache = self.init_name_map()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 321, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 396, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 410, in _fill_related_many_to_many_cache
for klass in get_models():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 167, in get_models
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 76, in load_app
app_module = import_module(app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named web
So going from the earlier comments I tried adding:
import sys
sys.path.append('/home/username/django')
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj import web
from someproj.web import models
from someproj.web.models import ItemConfiguration
But that didn't help. So I created a very simple file:
#!/usr/bin/python
import logging
import time
import sys
sys.path.append('/home/username/django')
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration
if __name__ == '__main__':
print sys.path
items = ItemConfiguration.objects.all()
for item in items:
print item
And this works! Which really only further confuses me. So now I'm thinking maybe it has to do with the daemon. It uses os.fork() and I'm not sure if the path is still set. This is why I set the $PYTHONPATH variable in the /etc/bash.bashrc file.
Any more insights? I really need the daemon, I don't have much of a choice as I need a long running process.
A:
With from my_module.core.daemon import Daemon you do not actually bind the loaded module my_module to a variable. Use import my_module
just before or after your other imports to do that.
Explained in code:
>>> from xml import dom
>>> xml
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'xml' is not defined
>>> import xml
>>> xml
<module 'xml' from '/usr/lib/python2.6/xml/__init__.pyc'>
A:
you get me confused what do you mean "your Django project" is your module "my_module" is part of an higher package? something like this
django_project
|
|my_module
__init__.py
- bin
- cfg
- core
__init__.py
collection.py
daemon.py
if so , and if like you said django_project is in PYTHONPATH , so you should just import my_module like this:
from django_project.my_module.core.daemon import Daemon
by the way it's preferable to import module no class neither function like this:
from django_project.my_module.core import daemon
and use it like this:
daemon.Daemon()
A:
It ended up being that I needed to reference the fully qualified name of my app in my Django project's settings.py file in the INSTALLED_APPS setting. "someproj.web" instead of just "web". Using the shorter version works fine within a Django project, just not so well from the outside.
| Python import module results in NameError | I'm having a module import issue.
using python 2.6 on ubuntu 10.10
I have a class that subclasses the daemon at http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ . I created a python package with a module containing code that imports some models from a django project. The code works when used from a class, not subclassing the daemon. The structure looks something like:
my_module
__init__.py
- bin
- cfg
- core
__init__.py
collection.py
daemon.py
The ItemRepository code:
class ItemRepository(object):
"""This class provides an implementation to retrieve configuration data
from the monocle database
"""
def __init__(self, project_path):
if project_path is not None:
sys.path.append(project_path)
try:
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.someapp.models import ItemConfiguration
except ImportError:
print "Could not import models from web app. Please ensure the\
PYTHONPATH is configured properly"
def get_scheduled_collectors(self):
"""This method finds and returns all ItemConfiguration objects
that are scheduled to run
"""
logging.info('At the error path: %s' % sys.path)
# query ItemConfigs from database
items = ItemConfiguration.objects.filter(disabled=False) #ERROR OCCURS AT THIS LINE
return [item for item in items if item.scheduled]
The daemon code (in /usr/local/bin/testdaemon.py):
import sys
from my_module.core.daemon import Daemon
from my_module.core.collection import ItemRepository
import logging
import time
class TestDaemon(Daemon):
default_conf = '/etc/echodaemon.conf'
section = 'echo'
def run(self):
while True:
logging.info('The echo daemon says hello')
ir = ItemRepository(project_path=self.project_path)
items = ir.get_scheduled_collectors() #TRIGGERS ERROR
logging.info('there are %d scheduled items' % len(items))
time.sleep(1)
if __name__ == '__main__':
TestDaemon().main()
The error I get is "NameError: global name 'my_module' is not defined" It get's past the import but then fails when trying to call a method on the object. I'm assuming it has to do with sys.path / PYTHONPATH, but I know my django project is on the path, as I've printed it out. Nothing so far in the python docs or Learning Python has helped yet. Does anyone have any insights or know of a good reference to module imports?
UPDATE:
Now I've attempted to simplify the problem to make it easier to understand. Now I have a directory structure that looks like:
/home
/username
/django
/someproj
/web
models.py
/my_module
daemon.py
I have set the $PYTHONPATH variable in /etc/bash.bashrc to '/home/username/django'.
Inside the testdaemon.py file the imports look like:
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration
But now I get an ImportError: No module named 'someproj'. So then I appended the path.
import sys
sys.path.append('/home/username/django')
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration
And now the ImportError says: No module named 'web'. Here's the traceback:
Traceback (most recent call last):
File "testdaemon.py", line 77, in <module>
TestDaemon('/tmp/testdaemon.pid').run()
File "testdaemon.py", line 47, in run
scheduled_items = [item for item in ItemConfiguration.objects.filter(disabled=False) if collector.scheduled]
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 141, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1128, in add_q
can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1026, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1179, in setup_joins
field, model, direct, m2m = opts.get_field_by_name(name)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 291, in get_field_by_name
cache = self.init_name_map()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 321, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 396, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 410, in _fill_related_many_to_many_cache
for klass in get_models():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 167, in get_models
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 76, in load_app
app_module = import_module(app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named web
So going from the earlier comments I tried adding:
import sys
sys.path.append('/home/username/django')
import logging
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj import web
from someproj.web import models
from someproj.web.models import ItemConfiguration
But that didn't help. So I created a very simple file:
#!/usr/bin/python
import logging
import time
import sys
sys.path.append('/home/username/django')
from django.core.management import setup_environ
from someproj import settings
setup_environ(settings)
from someproj.web.models import ItemConfiguration
if __name__ == '__main__':
print sys.path
items = ItemConfiguration.objects.all()
for item in items:
print item
And this works! Which really only further confuses me. So now I'm thinking maybe it has to do with the daemon. It uses os.fork() and I'm not sure if the path is still set. This is why I set the $PYTHONPATH variable in the /etc/bash.bashrc file.
Any more insights? I really need the daemon, I don't have much of a choice as I need a long running process.
| [
"With from my_module.core.daemon import Daemon you do not actually bind the loaded module my_module to a variable. Use import my_module\njust before or after your other imports to do that.\nExplained in code:\n>>> from xml import dom\n>>> xml\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <modu... | [
0,
0,
0
] | [] | [] | [
"django",
"import",
"module",
"nameerror",
"python"
] | stackoverflow_0003992175_django_import_module_nameerror_python.txt |
Q:
Transforming the string representation of a dictionary into a real dictionary
I am working on an image processing script. I need to let the user specify how to remap some classes in an image via a text file. The syntax in this file should be simple and self-evident. What I thought of doing is to get the user to write the string version of a dictionary:
125:126, 126:126, 127:128, 128:128
and then transform it into a real dictionary (this is the missing link):
a = {125:126, 126:126, 127:128, 128:128}
The remapping of the classes of the image would then be done like this:
u, indices = numpy.unique(image, return_inverse=True)
for i in range(0, len(u)):
u[i] = a[u[i]]
updatedimage = u[indices]
updatedimage = numpy.resize(updatedimage, (height, width)) #Resize to original dims
Is there a simple way to do this transformation from the "string version" to a real dictionary? Can you think of an easier/alternative one-line syntax that the user could use?
A:
You can use ast.literal_eval:
>>> import ast
>>> ast.literal_eval('{' + s + '}')
{128: 128, 125: 126, 126: 126, 127: 128}
Note that this requires Python 2.6 or newer.
An alternative is to split the string on ',' and then split each piece on ':' and construct a dict from that:
>>> dict(map(int, x.split(':')) for x in s.split(','))
{128: 128, 125: 126, 126: 126, 127: 128}
Both examples assume that your initial string is in a variable called s:
>>> s = '125:126, 126:126, 127:128, 128:128'
| Transforming the string representation of a dictionary into a real dictionary | I am working on an image processing script. I need to let the user specify how to remap some classes in an image via a text file. The syntax in this file should be simple and self-evident. What I thought of doing is to get the user to write the string version of a dictionary:
125:126, 126:126, 127:128, 128:128
and then transform it into a real dictionary (this is the missing link):
a = {125:126, 126:126, 127:128, 128:128}
The remapping of the classes of the image would then be done like this:
u, indices = numpy.unique(image, return_inverse=True)
for i in range(0, len(u)):
u[i] = a[u[i]]
updatedimage = u[indices]
updatedimage = numpy.resize(updatedimage, (height, width)) #Resize to original dims
Is there a simple way to do this transformation from the "string version" to a real dictionary? Can you think of an easier/alternative one-line syntax that the user could use?
| [
"You can use ast.literal_eval:\n>>> import ast\n>>> ast.literal_eval('{' + s + '}')\n{128: 128, 125: 126, 126: 126, 127: 128}\n\nNote that this requires Python 2.6 or newer.\nAn alternative is to split the string on ',' and then split each piece on ':' and construct a dict from that:\n>>> dict(map(int, x.split(':')... | [
11
] | [] | [] | [
"dictionary",
"numpy",
"python",
"string"
] | stackoverflow_0004127344_dictionary_numpy_python_string.txt |
Q:
Gtk IconView select multiple without Ctrl?
Is it possible to make Gtk IconView (in pygtk) allow selection of multiple icons without the Ctrl key being pressed?
I basically want the behaviour of Ctrl being held down even when it is not held down.
A:
Overriding this kind of behaviour might confuse users. But if you really want to, there are two possibilities that I can see:
Either make the IconView believe Ctrl is always pressed:
def force_ctrl(iv, ev): ev.state |= gtk.gdk.CONTROL_MASK
iconview.connect('key-press-event', force_ctrl)
iconview.connect('button-press-event', force_ctrl)
Or you could try implementing the selection behaviour yourself, something like:
def clicked(iv, ev):
p = iv.get_path_at_pos(int(ev.x), int(ev.y))
if not p is None:
if iv.path_is_selected(p):
iv.unselect_path(p)
else:
iv.select_path(p)
return True # make the IconView ignore this click
iconview.connect('button-press-event', clicked)
| Gtk IconView select multiple without Ctrl? | Is it possible to make Gtk IconView (in pygtk) allow selection of multiple icons without the Ctrl key being pressed?
I basically want the behaviour of Ctrl being held down even when it is not held down.
| [
"Overriding this kind of behaviour might confuse users. But if you really want to, there are two possibilities that I can see:\nEither make the IconView believe Ctrl is always pressed:\ndef force_ctrl(iv, ev): ev.state |= gtk.gdk.CONTROL_MASK\niconview.connect('key-press-event', force_ctrl)\niconview.connect('butto... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0004120097_gtk_pygtk_python.txt |
Q:
How do I get Cyrillic in the output, Python?
how do I get Cyrillic instead of u'...
the code is like this
def openfile(filename):
with codecs.open(filename, encoding="utf-8") as F:
raw = F.read()
do stuff...
print some_text
prints
>>>[u'.', u',', u':', u'\u0432', u'<', u'>', u'(', u')', u'\u0437', u'\u0456']
A:
It looks like some_text is a list of unicode objects. When you print such a list, it prints the reprs of the elements inside the list. So instead try:
print(u''.join(some_text))
The join method concatenates the elements of some_text, with an empty space, u'', in between the elements. The result is one unicode object.
A:
It's not clear to me where some_text comes from (you cut out that bit of your code), so I have no idea why it prints as a list of characters rather than a string.
But you should be aware that by default, Python tries to encode strings as ASCII when you print them to the terminal. If you want them to be encoded in some other coding system, you can do that explicitly:
>>> text = u'\u0410\u0430\u0411\u0431'
>>> print text
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3:
ordinal not in range(128)
>>> print text.encode('utf8')
АаБб
A:
u'\uNNNN' is the ASCII-safe version of the string literal u'з':
>>> print u'\u0437'
з
However this will only display right for you if your console supports the character you are trying to print. Trying the above on the console on a Western European Windows install fails:
>>> print u'\u0437'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\encodings\cp437.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u0437' in position 0: character maps to <undefined>
Because getting the Windows console to output Unicode is tricky, Python 2's repr function always opts for the ASCII-safe literal version.
Your print statement is outputting the repr version and not printing characters directly because you've got them inside a list of characters instead of a string. If you did print on each of the members of the list, you'd get the characters output directly and not represented as u'...' string literals.
| How do I get Cyrillic in the output, Python? | how do I get Cyrillic instead of u'...
the code is like this
def openfile(filename):
with codecs.open(filename, encoding="utf-8") as F:
raw = F.read()
do stuff...
print some_text
prints
>>>[u'.', u',', u':', u'\u0432', u'<', u'>', u'(', u')', u'\u0437', u'\u0456']
| [
"It looks like some_text is a list of unicode objects. When you print such a list, it prints the reprs of the elements inside the list. So instead try:\nprint(u''.join(some_text))\n\nThe join method concatenates the elements of some_text, with an empty space, u'', in between the elements. The result is one unicode ... | [
4,
3,
0
] | [] | [] | [
"encode",
"python",
"utf_8"
] | stackoverflow_0004127496_encode_python_utf_8.txt |
Q:
Genshi: if/else
How do I do a simple if/else in the Genshi templating language?
I've found this ticket, which seems to suggest that Genshi doesn't support if/else, but it doesn't really explain what it supports instead.
I basically just want something like this:
<py:if test="c.row.currency">
${c.row.currency.upper()}
<py:else>
${c.row.dataset_.currency.upper()}
</py:if>
But I get 'Bad Directive: else'. Should I be using py:choose instead? I can't really get my head around how to use it for an if/else condition.
A:
Currently, you can not if do else constructs in Genshi, and as far as I'm aware, there are no plans to add it. Instead, like you mentioned, use py:choose. The following is how you use py:choose as a type of if/else construct:
<py:choose ...>
<py:when test="...">
${c.row.currency.upper()}
</py:when>
<py:otherwise>
${c.row.currency.upper()}
</py:otherwise>
</py:choose>
| Genshi: if/else | How do I do a simple if/else in the Genshi templating language?
I've found this ticket, which seems to suggest that Genshi doesn't support if/else, but it doesn't really explain what it supports instead.
I basically just want something like this:
<py:if test="c.row.currency">
${c.row.currency.upper()}
<py:else>
${c.row.dataset_.currency.upper()}
</py:if>
But I get 'Bad Directive: else'. Should I be using py:choose instead? I can't really get my head around how to use it for an if/else condition.
| [
"Currently, you can not if do else constructs in Genshi, and as far as I'm aware, there are no plans to add it. Instead, like you mentioned, use py:choose. The following is how you use py:choose as a type of if/else construct:\n<py:choose ...>\n <py:when test=\"...\">\n ${c.row.currency.upper()}\n </py:when>\n... | [
8
] | [] | [] | [
"genshi",
"pylons",
"python"
] | stackoverflow_0004127626_genshi_pylons_python.txt |
Q:
Is there any possible point to reloading a Python module immediately?
Is there any conceivable point to reloading these modules immediately after importing them? This is the code that I was reviewing which made me wonder:
import time
import sys
import os
import string
import pp
import numpy
import nrrd
reload(nrrd)
import smooth as sm
reload(sm)
import TensorEval2C as tensPP
reload(tensPP)
import TrackFiber4C as trackPP
reload(trackPP)
import cmpV
reload(cmpV)
import vectors as vects
reload(vects)
Edit: I suggested that this might make the creation of .pyc files more likely, but several people pointed out that this happens this first time, every time.
A:
It is possible that this does cause something to happen; the obvious example is side-effects that happen on import. For instance, a module could log to a file the time and date of every time it is imported.
There is probably no good reason for this, however.
A:
I note that the standard modules are just imported: it's the other modules that are reloaded. I expect whoever wrote this code wanted to be able to easily reload the whole package (so as to get their latest edits). After putting in all these redundant reload calls, the programmer only had to write
>>> reload(package)
to bring things up to date in the interpreter, instead of having to type
>>> reload(package.nrrd)
>>> reload(package.sm)
>>> reload(package.tensPP)
etc. So please ignore the suggestion that you commit violence against the programmer who wrote this: they are far from the only programmer who's had trouble with reloading of dependencies. Just encourage them to move the reloads to a convenience function.
A:
The .pyc files would be created on the first import, so even that's not a very good reason for this.
A:
What's the execution environment for this code? There exists at least one Python web framework that makes different reload decisions than standard python does, which leads to frustration and confusion when you make a change that doesn't 'take'.
| Is there any possible point to reloading a Python module immediately? | Is there any conceivable point to reloading these modules immediately after importing them? This is the code that I was reviewing which made me wonder:
import time
import sys
import os
import string
import pp
import numpy
import nrrd
reload(nrrd)
import smooth as sm
reload(sm)
import TensorEval2C as tensPP
reload(tensPP)
import TrackFiber4C as trackPP
reload(trackPP)
import cmpV
reload(cmpV)
import vectors as vects
reload(vects)
Edit: I suggested that this might make the creation of .pyc files more likely, but several people pointed out that this happens this first time, every time.
| [
"It is possible that this does cause something to happen; the obvious example is side-effects that happen on import. For instance, a module could log to a file the time and date of every time it is imported.\nThere is probably no good reason for this, however.\n",
"I note that the standard modules are just import... | [
6,
6,
1,
0
] | [] | [] | [
"import",
"python",
"reload"
] | stackoverflow_0004127647_import_python_reload.txt |
Q:
How do I exclude files from a search that may be in use or being copied to in python?
I'm new to python so this might end up having a simple solution.
At my house, I have 3 computers that are relevant to this situation:
- File Server (linux)
- My main PC (windows)
- Girlfriend's MacBook Pro
My file server is running ubuntu and samba. I've installed python 3.1 and I've written my code in 3.1.
I've created a daemon that determines when certain files exist in the uploads directory that follow a given pattern. Upon finding such file, it renames it and moves it to a different location on a different drive. It also re-writes the owner, group, and permissions. All of this works great. It runs this process every minute.
If I copy files from my main pc (running a flavor of windows), the process always works. (I believe windows locks the file until its done copying-- I could be wrong.)
If my girlfriend copies a file, it picks up the file before the copy is complete and things get messy. (underscored versions of the files with improper permissions are created and occasionally, the file will go into the correct place)
I am guessing here that her mac book does not lock the file when copying. I could also be wrong there.
What I need is a way to exclude files that are either in use or, failing that, are being created.
For reference, the method I've created to find the files is:
# _GetFileListing(filter)
# Description: Gets a list of relevant files based on the filter
#
# Parameters: filter - a compiled regex query
# Retruns:
# Nothing. It populates self.fileList
def _GetFileListing(self, filter):
self.fileList = []
for file in os.listdir(self.dir):
filterMatch = filter.search(file)
filepath = os.path.join(self.dir, file)
if os.path.isfile(filepath) and filterMatch != None:
self.fileList.append(filepath)
Note, this is all in a class.
The method I've created to manipulate the files is:
# _ArchiveFile(filepath, outpath)
# Description: Renames/Moves the file to outpath and re-writes the file permissions to the permissions used for
# the output directory. self.mask, self.group, and self.owner for the actual values.
#
# Parameters: filepath - path to the file
# outpath - path to the file to output
def _ArchiveFile(self, filepath, outpath):
dir,filename,filetype = self._SplitDirectoryAndFile(outpath)
try:
os.makedirs(dir, self.mask)
except OSError:
#Do Nothing!
dir = dir
uid = pwd.getpwnam(self.owner)[2]
gid = grp.getgrnam(self.group)[2]
#os.rename(filepath, outpath)
shutil.move(filepath, outpath)
os.chmod(outpath, self.mask)
os.chown(outpath, uid, gid)
I've stopped using os.rename because it seems to have stopped working when I started moving files to different drives.
Short Version:
How do I prevent myself from picking up files in my search that are currently being transferred?
Thank you in advance for any help you might be able to provide.
A:
You can try taking an exclusive write lock on the file before moving it. This can be done with the fcntl module:
http://docs.python.org/library/fcntl.html
Barring that, you can us the lsof utility to see files which the system has open. That requires more drudgery.
Note that os.rename() will work on the same filesystem, and would actually be immune to this issue (the inode gets moved, no data gets moved). Using shutil will do as mv does, which is either relink the file if its the same filesystem, or copy + delete if the filesystems are different.
A:
Turns out the write lock approach didn't work. I guess I didn't properly test it before updating here.
What I've decided to do for now is:
Reduce the time between checks to 30s
Keep a list of files found in the
previous iteration and their
respective file sizes
Check the new list of files against the old list
If the new list contains the same file with the same file size as the old list, put it in a list to be transferred. The remaining files in the new list become the old list and the process continues.
I'm sure the lsof method will work but I'm not sure how to use it in python. Also this method should work quite well for my situation since I am mostly concerned with not moving the files while they're in transit.
I would also have to exclude all files that start with "._" since the mac creates those and I'm not sure if they increase in size over time.
Alternatively, I have the option to handle just cases where it's being transferred by her mac. I know that when the mac is transferring the file, it creates:
filename.ext
._filename.ext
I could check the list for all instances of filename where it is preceded with ._ and exclude files that way.
I'll probably try the second option first. It's a little dirty but hopefully it will work.
A:
The ._ files from the mac contain resource forks. More information can be found here: http://support.apple.com/kb/TA20578
I don't have enough rep to make a comment, hence the answer.
For the most part you can safely ignore them, as no other OS can probably do anything with them anyway. More info on them here:
http://en.wikipedia.org/wiki/Resource_fork
| How do I exclude files from a search that may be in use or being copied to in python? | I'm new to python so this might end up having a simple solution.
At my house, I have 3 computers that are relevant to this situation:
- File Server (linux)
- My main PC (windows)
- Girlfriend's MacBook Pro
My file server is running ubuntu and samba. I've installed python 3.1 and I've written my code in 3.1.
I've created a daemon that determines when certain files exist in the uploads directory that follow a given pattern. Upon finding such file, it renames it and moves it to a different location on a different drive. It also re-writes the owner, group, and permissions. All of this works great. It runs this process every minute.
If I copy files from my main pc (running a flavor of windows), the process always works. (I believe windows locks the file until its done copying-- I could be wrong.)
If my girlfriend copies a file, it picks up the file before the copy is complete and things get messy. (underscored versions of the files with improper permissions are created and occasionally, the file will go into the correct place)
I am guessing here that her mac book does not lock the file when copying. I could also be wrong there.
What I need is a way to exclude files that are either in use or, failing that, are being created.
For reference, the method I've created to find the files is:
# _GetFileListing(filter)
# Description: Gets a list of relevant files based on the filter
#
# Parameters: filter - a compiled regex query
# Retruns:
# Nothing. It populates self.fileList
def _GetFileListing(self, filter):
self.fileList = []
for file in os.listdir(self.dir):
filterMatch = filter.search(file)
filepath = os.path.join(self.dir, file)
if os.path.isfile(filepath) and filterMatch != None:
self.fileList.append(filepath)
Note, this is all in a class.
The method I've created to manipulate the files is:
# _ArchiveFile(filepath, outpath)
# Description: Renames/Moves the file to outpath and re-writes the file permissions to the permissions used for
# the output directory. self.mask, self.group, and self.owner for the actual values.
#
# Parameters: filepath - path to the file
# outpath - path to the file to output
def _ArchiveFile(self, filepath, outpath):
dir,filename,filetype = self._SplitDirectoryAndFile(outpath)
try:
os.makedirs(dir, self.mask)
except OSError:
#Do Nothing!
dir = dir
uid = pwd.getpwnam(self.owner)[2]
gid = grp.getgrnam(self.group)[2]
#os.rename(filepath, outpath)
shutil.move(filepath, outpath)
os.chmod(outpath, self.mask)
os.chown(outpath, uid, gid)
I've stopped using os.rename because it seems to have stopped working when I started moving files to different drives.
Short Version:
How do I prevent myself from picking up files in my search that are currently being transferred?
Thank you in advance for any help you might be able to provide.
| [
"You can try taking an exclusive write lock on the file before moving it. This can be done with the fcntl module:\nhttp://docs.python.org/library/fcntl.html\nBarring that, you can us the lsof utility to see files which the system has open. That requires more drudgery. \nNote that os.rename() will work on the same f... | [
0,
0,
0
] | [] | [] | [
"linux",
"macos",
"python",
"samba",
"windows"
] | stackoverflow_0004110666_linux_macos_python_samba_windows.txt |
Q:
re.findall() - additional criteria
I have a part number like this:
part_number = '18-TX25-37 DMDFC PS'
When I do
>>> re.findall(r'\w+', part_number)
... ['18', 'TX25', '37', 'DMDFC', 'PS']
Some part numbers may have a dot such as '18-TX25-37.25 DMDFC PS' and my regex returns '37', '25' etc. How can I make it not to split at the dot and return '37.25' along with all other values?
A:
\w is a character class, which is a shortcut for [a-zA-Z0-9_] (that is: letters, digits, and underscores). In other words, your regular expression is searching for all groups of one or more (letters, digits, or underscores). Naturally then, when the regex engine sees . in the string it doesn't include it as part of the previous match.
If you want to include . as a valid character, you need to do so explicitly:
>>> import re
>>> part_number = '18-TX25-37.25 DMDFC PS'
>>> re.findall(r"[\w.]+", part_number)
['18', 'TX25', '37.25', 'DMDFC', 'PS']
This says to "match all groups of one or more (letters, digits, underscores, or dots)".
A subtlety: the . is a special character in regex, matching any one character. You don't need to escape it here because it is inside a character class (between []) but if you were to use it outside of such a class you would need to precede it with a backslash.
| re.findall() - additional criteria | I have a part number like this:
part_number = '18-TX25-37 DMDFC PS'
When I do
>>> re.findall(r'\w+', part_number)
... ['18', 'TX25', '37', 'DMDFC', 'PS']
Some part numbers may have a dot such as '18-TX25-37.25 DMDFC PS' and my regex returns '37', '25' etc. How can I make it not to split at the dot and return '37.25' along with all other values?
| [
"\\w is a character class, which is a shortcut for [a-zA-Z0-9_] (that is: letters, digits, and underscores). In other words, your regular expression is searching for all groups of one or more (letters, digits, or underscores). Naturally then, when the regex engine sees . in the string it doesn't include it as part ... | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004128332_python_regex.txt |
Q:
Most efficient way to print strings in Python?
So according to the optimization tips at http://wiki.python.org/moin/PythonSpeed/PerformanceTips , joining strings should be done with
out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
and not
out = "<html>" + head + prologue + query + tail + "</html>"
My question is, is this the same for if I wanted to print, instead of store the value? Also, would putting consecutive print statements all on one line be faster? Like would it be better to use
print "Some word"
print "Another line"
print "something else"
or
print '''Some word
Another line
something else'''
Thanks in advance!
A:
String concatenation has been improved for the (fairly common) case where there is only one reference to the string. See PyString_ConcatAndDel in stringobject.c
So usually concatenation in a loop is linear since there is only ever one reference of the string
Here is a simple experiment to demonstrate the behaviour. When there is no room to extend the string the id() changes
>>> s = ""
>>> prev_id = None
>>> for i in range(1000):
... s += "*"
... if prev_id != id(s):
... print id(s), len(s)
... prev_id = id(s)
...
3077352864 1
3077437728 2
3077434328 9
3077428384 17
3077379928 25
3077291808 33
3077712448 41
3077358800 49
3077394728 57
3077667680 65
3077515120 73
3077354176 81
3077576488 89
3077559200 97
3077414248 105
3077670336 113
3077612160 121
3077707040 129
3077526040 137
3077571472 145
3077694944 153
3077595936 161
3077661904 169
3077552608 177
3077715680 185
3077583776 193
3077244304 201
3077604560 209
3077510392 217
3077334304 225
144468768 233
144787416 245
144890104 389
A:
Your question isn't really about the most efficient way to print strings, it's about formatting them for output, for which you should use format in any case because it does more than simple concatenation. However, here are some notes on concatenation.
Edit: rewritten to include some details
The printing is irrelevant. The important point is that due to the way that some languages handle string concatenation, joining lots of strings may be of quadratic order. The (very naive and basic) reasoning is that to concatenate two strings you have to walk down all the characters of the first string and then append all the characters of the second. So if you are concatenating ten strings, you first walk the first and append the second, then you walk the first+second and append the third, then you walk the first+second+third and append the fourth, and so on.
A naive implementation of concatenation will thus cause you to do much more work than you need to. Indeed, in early versions of Python this was an issue. However, @gnibbler has pointed out in the comments, later versions now generally optimise this, thus mooting the point entirely.
The Python idiom to join strings is "".join(...). This completely bypasses any possible issue and is the standard idiom anyway. If you want the ability to construct a string by appending, have a look at a StringIO:
>>> from io import StringIO
>>> foo = StringIO()
>>> for letter in map(chr, range(128)):
... foo.write(letter)
...
>>> foo.seek(0)
0
>>> foo.read()
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC
DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f'
A:
For printing there is no need to concatenate:
print "<html>", head, prologue, query, tail, "</html>"
This works the same (comma at the end prevents \n):
print "<html>",
print head,
...
print "</html>"
I think the answer is NO, do not concatenate just for printing, it will make things slower. But you really should not take my word for it, just write a few tests and profile with timeit.
| Most efficient way to print strings in Python? | So according to the optimization tips at http://wiki.python.org/moin/PythonSpeed/PerformanceTips , joining strings should be done with
out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
and not
out = "<html>" + head + prologue + query + tail + "</html>"
My question is, is this the same for if I wanted to print, instead of store the value? Also, would putting consecutive print statements all on one line be faster? Like would it be better to use
print "Some word"
print "Another line"
print "something else"
or
print '''Some word
Another line
something else'''
Thanks in advance!
| [
"String concatenation has been improved for the (fairly common) case where there is only one reference to the string. See PyString_ConcatAndDel in stringobject.c\nSo usually concatenation in a loop is linear since there is only ever one reference of the string\nHere is a simple experiment to demonstrate the behavio... | [
6,
5,
2
] | [] | [] | [
"performance",
"printing",
"profiling",
"python",
"string"
] | stackoverflow_0004128392_performance_printing_profiling_python_string.txt |
Q:
Google Protocol Buffers, HDF5, NumPy comparison (transferring data)
I need help to make decision. I have a need to transfer some data in my application and have to make a choice between these 3 technologies.
I've read about all technologies a little bit (tutorials, documentation) but still can't decide...
How do they compare?
I need support of metadata (capability to receive file and read it without any additional information/files), fast read/write operations, capability to store dynamic data will be a plus (like Python objects)
Things I already know:
NumPy is pretty fast but can't store dynamic data (like Python objects). (What about metadata?)
HDF5 is very fast, supports custom attributes, is easy to use, but can't store Python objects.
Also HDF5 serializes NumPy data natively, so, IMHO, NumPy has no advantages over HDF5
Google Protocol Buffers support self-describing too, are pretty fast (but Python support is poor at present time, slow and buggy). CAN store dynamic data. Minuses - self-describing don't work from Python and messages that are >= 1 MB are serializing/deserializing not very fast (read "slow").
PS: data I need to transfer is "result of work" of NumPy/SciPy (arrays, arrays of complicated structs, etc.)
UPD: cross-language access required (C/C++/Python)
A:
There does seem to be a slight contradiction in your question - you want to be able to store Python objects, but you also want C/C++ access. I think that regardless of which choice you go with, you will need to convert your fancy Python data structures into more static structures such as arrays.
If you need cross-language access, I would suggest using HDF5 as it is a file format which is specifically designed to be independent of language, operating system, system architecture (e.g. on loading it can convert between big-endian and little-endian automatically) and is specifically aimed at users doing scientific/numerical computing. I don't know much about Google Protocol Buffers, so I can't really comment too much on that.
If you decide to go with HDF5, I would also recommend that you use h5py instead of pytables. This is because pytables creates HDF5 files with a whole lot of extra pythonic metadata which makes reading the data in C/C++ a bit more of a pain, whereas h5py doesn't create any of these extras. You can find a comparison here, and they also give a link to the pytables FAQ for their view on the matter so you can decide which suits your needs best.
Another format which is very similar to HDF5 is NetCDF. This also has Python bindings, however I have no experience in using this format so I cannot really comment beyond pointing out that it exists and is also widely used in scientific computing.
A:
I don't know about HDF5, but you can store Python objects in NumPy arrays, you just lose all the important functionality by disallowing C-level operations to be performed on the array.
In [17]: x = np.zeros(10, dtype=np.object)
In [18]: x[3] = {'pants', 10}
In [19]: x
Out[19]: array([0, 0, 0, set([10, 'pants']), 0, 0, 0, 0, 0, 0], dtype=object)
| Google Protocol Buffers, HDF5, NumPy comparison (transferring data) | I need help to make decision. I have a need to transfer some data in my application and have to make a choice between these 3 technologies.
I've read about all technologies a little bit (tutorials, documentation) but still can't decide...
How do they compare?
I need support of metadata (capability to receive file and read it without any additional information/files), fast read/write operations, capability to store dynamic data will be a plus (like Python objects)
Things I already know:
NumPy is pretty fast but can't store dynamic data (like Python objects). (What about metadata?)
HDF5 is very fast, supports custom attributes, is easy to use, but can't store Python objects.
Also HDF5 serializes NumPy data natively, so, IMHO, NumPy has no advantages over HDF5
Google Protocol Buffers support self-describing too, are pretty fast (but Python support is poor at present time, slow and buggy). CAN store dynamic data. Minuses - self-describing don't work from Python and messages that are >= 1 MB are serializing/deserializing not very fast (read "slow").
PS: data I need to transfer is "result of work" of NumPy/SciPy (arrays, arrays of complicated structs, etc.)
UPD: cross-language access required (C/C++/Python)
| [
"There does seem to be a slight contradiction in your question - you want to be able to store Python objects, but you also want C/C++ access. I think that regardless of which choice you go with, you will need to convert your fancy Python data structures into more static structures such as arrays.\nIf you need cros... | [
13,
4
] | [] | [] | [
"hdf5",
"numpy",
"python"
] | stackoverflow_0004125855_hdf5_numpy_python.txt |
Q:
python izip which cycles through all iterables until the longest finishes
This turned out not to be a trivial task for me and I couldn't find any receipt so maybe you can point me to one or you have a ready, proper and well-tuned solution for that? Proper meaning works also for iterators that do not know own length (without __len__) and works for exhaustible iterators (e.g. chained iterators); well-tuned meaning fast.
Note: in place solution is not possible due to necessity to cache iterators outputs to re-iterate them (Glenn Maynard pointed that out).
Example usage:
>>> list(izip_cycle(range(2), range(5), range(3)))
[(0, 0, 0), (1, 1, 1), (0, 2, 2), (1, 3, 0), (0, 4, 1)]
>>> from itertools import islice, cycle, chain
>>> list(islice(izip_cycle(cycle(range(1)), chain(range(1), range(2))), 6))
[(0, 0), (0, 0), (0, 1), (0, 0), (0, 0), (0, 1)]
A:
A simple approach which might work for you, depending on your requirement is:
import itertools
def izip_cycle(*colls):
maxlen = max(len(c) if hasattr(c,'__len__') else 0 for c in colls)
g = itertools.izip(*[itertools.cycle(c) for c in colls])
for _ in range(maxlen):
yield g.next()
The first thing this does it find the length of longest sequence so it knows how many times to repeat. Sequences without __len__ are counted as having 0 length; this might bewhat you want - if you have an unending sequence you probably want to repeat over the finite sequences. Although this doesn't handle finite iterators with no length.
Never we use itertools.cycle to create a cycling version of each iterator and then use itertools.zip to zip them together.
Finally we yield each entry from our zip until we've given our desired number of results.
If you want this to work for finite iterator with no len we need to do more of the work ourselves:
def izip_cycle(*colls):
iters = [iter(c) for c in colls]
count = len(colls)
saved = [[] for i in range(count)]
exhausted = [False] * count
while True:
r = []
for i in range(count):
if not exhausted[i]:
try:
n = iters[i].next()
saved[i].append(n)
r.append(n)
except StopIteration:
exhausted[i] = True
if all(exhausted):
return
saved[i] = itertools.cycle(saved[i])
if exhausted[i]:
r.append(saved[i].next())
yield r
This is basically an extension of the Python implementation of itertools.cycle in the documentation to run over multiple sequences. We savd up items we've seen in saved to repeat and track which sequences have run out in exhausted.
As this version waits for all the sequences to run out, if you pass in something infinite the cycling will run on forever.
A:
Here is something inspired by itertools.tee and itertools.cycle. It works for any kind of iterable:
class izip_cycle(object):
def __init__(self, *iterables ):
self.remains = len(iterables)
self.items = izip(*[self._gen(it) for it in iterables])
def __iter__(self):
return self.items
def _gen(self, src):
q = []
for item in src:
yield item
q.append(item)
# done with this src
self.remains -=1
# if there are any other sources then cycle this one
# the last souce remaining stops here and thus stops the izip
if self.remains:
while True:
for item in q:
yield item
A:
def izip_cycle_inplace(*iterables):
def wrap(it):
empty = True
for x in it: empty = yield x
if empty: return
next(counter)
while True:
empty = True
for x in it: empty = yield x
if empty: raise ValueError('cannot cycle iterator in-place')
iterators = [wrap(i) for i in iterables]
counter = iter(iterators)
next(counter)
while True:
yield [next(i) for i in iterators]
def izip_cycle(*iterables):
def wrap(it):
elements = []
for x in it:
yield x
elements.append(x)
if not elements: return
next(counter)
while True:
for x in elements: yield x
iterators = [wrap(i) for i in iterables]
counter = iter(iterators)
next(counter)
while True:
yield [next(i) for i in iterators]
| python izip which cycles through all iterables until the longest finishes | This turned out not to be a trivial task for me and I couldn't find any receipt so maybe you can point me to one or you have a ready, proper and well-tuned solution for that? Proper meaning works also for iterators that do not know own length (without __len__) and works for exhaustible iterators (e.g. chained iterators); well-tuned meaning fast.
Note: in place solution is not possible due to necessity to cache iterators outputs to re-iterate them (Glenn Maynard pointed that out).
Example usage:
>>> list(izip_cycle(range(2), range(5), range(3)))
[(0, 0, 0), (1, 1, 1), (0, 2, 2), (1, 3, 0), (0, 4, 1)]
>>> from itertools import islice, cycle, chain
>>> list(islice(izip_cycle(cycle(range(1)), chain(range(1), range(2))), 6))
[(0, 0), (0, 0), (0, 1), (0, 0), (0, 0), (0, 1)]
| [
"A simple approach which might work for you, depending on your requirement is:\nimport itertools\n\ndef izip_cycle(*colls):\n maxlen = max(len(c) if hasattr(c,'__len__') else 0 for c in colls)\n g = itertools.izip(*[itertools.cycle(c) for c in colls])\n\n for _ in range(maxlen):\n yield g.next()\n\n... | [
1,
1,
0
] | [] | [] | [
"iterator",
"python"
] | stackoverflow_0004125825_iterator_python.txt |
Q:
Sqlite statement syntax error
What's wrong with this SQL statement? I'm getting a SQLError: near "?": syntax error.
'select all counts from table as table where offset in ?'
The ? has a binding of numbers with a list in it: (1,2,4).
A:
Just guessing that the language you're using is Python...
No matter the language the principle is the same:
You need to dynamically create the appropriate number of placeholders.
>>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute('create table test (id int)')
<sqlite3.Cursor object at 0x011A96A0>
>>> c.executemany('insert into test values (?)', [(1,),(2,),(4,)])
<sqlite3.Cursor object at 0x011A96A0>
>>> ids = (1,2,4)
>>> query = 'select * from test where id in (%s)' % ','.join('?'*len(ids))
>>> query
'select * from test where id in (?,?,?)'
>>> c.execute(query, ids).fetchall()
[(1,), (2,), (4,)]
A:
i think you want 'select count(*) from table where offset in ?'
A:
Can you bind an in-list to a single parameter placeholder like that? You might consider this alternative: create a temporary table, insert the in-list values into the temp table, and then do an inner join between your table and the temp table on the relevant column. Overall, cleaner and more maintainable than building the query statement string with the (?,?,?,?) substring having the requisite number of question marks.
| Sqlite statement syntax error | What's wrong with this SQL statement? I'm getting a SQLError: near "?": syntax error.
'select all counts from table as table where offset in ?'
The ? has a binding of numbers with a list in it: (1,2,4).
| [
"Just guessing that the language you're using is Python...\nNo matter the language the principle is the same:\nYou need to dynamically create the appropriate number of placeholders.\n>>> import sqlite3\n>>> conn = sqlite3.connect(':memory:')\n>>> c = conn.cursor()\n>>> c.execute('create table test (id int)')\n<sqli... | [
1,
1,
0
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0004127993_python_sqlite.txt |
Q:
User-defined text fields in django admin
Django (and database) newbie here.
I'm trying to figure out a way to enable the creation of n custom text fields for a table (let's call it Book) using the admin interface. I would like a way for the user to define new text fields through the admin interface (instead of defining fields like CustomField1, CustomField2, etc, through a model followed by running manage.py syncdb).
Ultimately, I would want to create a separate table called CustomFields. The django admin user (who is not a programmer), would go and enter the custom text fields in this table (e.g. pubdate, isbn, country). Then, when doing data entry for a Book, they would hit "+" for every custom field they wanted, have them available in a dropdown, and add accompanying text for the custom field. The text entered for each field is specific to the parent Book.
Any suggestions? I have a feeling there's a simple solution that I'm somehow not grasping here.
A:
Where you might run into problems is because Django will not recreate tables or columns based on changing model declarations. This means you're unable to add fields to a table at run-time without running the generated sql on your database manually. What you'll need, instead, is a way of defining custom fields, and linking them to your model.
What I'd suggest is the following:
class CustomField(models.Model):
name = models.CharField(max_length=32)
class Book(models.Model):
... fields
class CustomValue(models.Model):
field = models.ForeignKey(CustomField)
value = models.CharField(max_length=255)
book = models.ForeignKey(Book)
The validation on the above is fairly non-existant, and this doesn't allow you to define required custom fields for each model, but you should be able to come up with that part if you need it later on.
# taken and modified from django online tutorial
class CustomValueInline(admin.StackedInline):
model = CustomValue
extra = 3
class BookAdmin(admin.ModelAdmin):
fieldsets = [
# your fields in here
]
inlines = [CustomValueInline]
admin.site.register(Book, BookAdmin)
This will allow users to select up to 3 custom fields and values directly, with the option to add more if they wish.
Edit: Changed the answer to reflect further information in comments.
A:
For the beginning you can create one model for the book and one for the text field, both connected through a foreign key relation. You can easily administrate this then through django's inline admins, which will enable you to add more text fields!
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
class TextField(models.Model):
text = models.TextField
book = models.ForeignKey(Book)
# admin.py
from django.contrib import admin
from models import TextField, Book
class TextAdmin(admin.TabularInline):
model = TextField
class BookAdmin(admin.ModelAdmin):
inlines = [TextAdmin]
admin.site.register(Book, BookAdmin)
| User-defined text fields in django admin | Django (and database) newbie here.
I'm trying to figure out a way to enable the creation of n custom text fields for a table (let's call it Book) using the admin interface. I would like a way for the user to define new text fields through the admin interface (instead of defining fields like CustomField1, CustomField2, etc, through a model followed by running manage.py syncdb).
Ultimately, I would want to create a separate table called CustomFields. The django admin user (who is not a programmer), would go and enter the custom text fields in this table (e.g. pubdate, isbn, country). Then, when doing data entry for a Book, they would hit "+" for every custom field they wanted, have them available in a dropdown, and add accompanying text for the custom field. The text entered for each field is specific to the parent Book.
Any suggestions? I have a feeling there's a simple solution that I'm somehow not grasping here.
| [
"Where you might run into problems is because Django will not recreate tables or columns based on changing model declarations. This means you're unable to add fields to a table at run-time without running the generated sql on your database manually. What you'll need, instead, is a way of defining custom fields, and... | [
2,
0
] | [] | [] | [
"database",
"database_design",
"django",
"python",
"relational_database"
] | stackoverflow_0004128454_database_database_design_django_python_relational_database.txt |
Q:
Python: Adding excel file to an access database
I am using pyodbc to access an access (accdb) file. I want to add an excel workbook into the access database programatically, but cannot find an API to do so. Here is my current code:
import pyodbc
DBFile = r'C:\Documents and Settings\IA.accdb'
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBFile)
exFile = r'C:\Documents and Settings\IA_2006.xls'
conn1 = pyodbc.connect('DRIVER={Microsoft Excel Driver \
(*.xls)};DBQ='+exFile,autocommit=True)
cursor = conn.cursor()
####IA_1 is a table within IA.accdb
cursor.execute('select * from IA_1')
row = cursor.fetchone()
####For debugging, print a line
if row:
print row
How should I import the data from the excel file (IA_2006.xls) into the IA.accdb?
A:
It seems like you got to a certain point and gave up.
Don't give up! :-)
You've made the connection to the Excel spreadsheet, now you need to read it*.
curs1 = conn1.cursor()
# the following returns list of tuples
excel_results = curs1.execute('select [a_column]
from [Sheet1$]').fetchall()
Then you can insert to your MS Access db, e.g.:
curs.executemany('insert into mytable (mycolumn) values (?)', excel_results)
conn.commit()
*If in doubt, Excel sheet names can be found by running the following:
for row in curs1.tables():
print row.table_name
| Python: Adding excel file to an access database | I am using pyodbc to access an access (accdb) file. I want to add an excel workbook into the access database programatically, but cannot find an API to do so. Here is my current code:
import pyodbc
DBFile = r'C:\Documents and Settings\IA.accdb'
conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBFile)
exFile = r'C:\Documents and Settings\IA_2006.xls'
conn1 = pyodbc.connect('DRIVER={Microsoft Excel Driver \
(*.xls)};DBQ='+exFile,autocommit=True)
cursor = conn.cursor()
####IA_1 is a table within IA.accdb
cursor.execute('select * from IA_1')
row = cursor.fetchone()
####For debugging, print a line
if row:
print row
How should I import the data from the excel file (IA_2006.xls) into the IA.accdb?
| [
"It seems like you got to a certain point and gave up.\nDon't give up! :-)\nYou've made the connection to the Excel spreadsheet, now you need to read it*.\ncurs1 = conn1.cursor()\n# the following returns list of tuples\nexcel_results = curs1.execute('select [a_column]\n from [Sheet1$]'... | [
3
] | [] | [] | [
"excel",
"ms_access",
"pyodbc",
"python"
] | stackoverflow_0004128334_excel_ms_access_pyodbc_python.txt |
Q:
Difficulties with distribute -
am new to Python packaging and am trying to work out which flags I need to get something uploaded properly into PyPi. distribute seems to building things them deleting them straight away. How do I stop that from happening?
Here is the traceback:
tim@falcon:~/Code/slate$ python setup.py sdist
running sdist
running egg_info
writing requirements to src/slate.egg-info/requires.txt
writing src/slate.egg-info/PKG-INFO
writing top-level names to src/slate.egg-info/top_level.txt
writing dependency_links to src/slate.egg-info/dependency_links.txt
writing manifest file 'src/slate.egg-info/SOURCES.txt'
creating slate-0.2.3
creating slate-0.2.3/src
creating slate-0.2.3/src/slate
creating slate-0.2.3/src/slate.egg-info
making hard links in slate-0.2.3...
hard linking .gitignore -> slate-0.2.3
hard linking LICENSE -> slate-0.2.3
hard linking README -> slate-0.2.3
hard linking setup.py -> slate-0.2.3
hard linking src/slate/__init__.py -> slate-0.2.3/src/slate
hard linking src/slate/slate.py -> slate-0.2.3/src/slate
hard linking src/slate.egg-info/PKG-INFO -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/SOURCES.txt -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/dependency_links.txt -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/requires.txt -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/top_level.txt -> slate-0.2.3/src/slate.egg-info
Writing slate-0.2.3/setup.cfg
tar -cf dist/slate-0.2.3.tar slate-0.2.3
gzip -f9 dist/slate-0.2.3.tar
removing 'slate-0.2.3' (and everything under it)
A:
This message seems to indicate that the script removed a temporary directory created to do your package... The .tar.gz file is not removed. Check your dist directory for it.
To upload you can probably use distutils-documented way:
python setup.py sdist upload
Some good reads:
Distutils -- Official documentation on how to distribute python packages
The hitchhiker's guide to python packaging
| Difficulties with distribute - | am new to Python packaging and am trying to work out which flags I need to get something uploaded properly into PyPi. distribute seems to building things them deleting them straight away. How do I stop that from happening?
Here is the traceback:
tim@falcon:~/Code/slate$ python setup.py sdist
running sdist
running egg_info
writing requirements to src/slate.egg-info/requires.txt
writing src/slate.egg-info/PKG-INFO
writing top-level names to src/slate.egg-info/top_level.txt
writing dependency_links to src/slate.egg-info/dependency_links.txt
writing manifest file 'src/slate.egg-info/SOURCES.txt'
creating slate-0.2.3
creating slate-0.2.3/src
creating slate-0.2.3/src/slate
creating slate-0.2.3/src/slate.egg-info
making hard links in slate-0.2.3...
hard linking .gitignore -> slate-0.2.3
hard linking LICENSE -> slate-0.2.3
hard linking README -> slate-0.2.3
hard linking setup.py -> slate-0.2.3
hard linking src/slate/__init__.py -> slate-0.2.3/src/slate
hard linking src/slate/slate.py -> slate-0.2.3/src/slate
hard linking src/slate.egg-info/PKG-INFO -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/SOURCES.txt -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/dependency_links.txt -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/requires.txt -> slate-0.2.3/src/slate.egg-info
hard linking src/slate.egg-info/top_level.txt -> slate-0.2.3/src/slate.egg-info
Writing slate-0.2.3/setup.cfg
tar -cf dist/slate-0.2.3.tar slate-0.2.3
gzip -f9 dist/slate-0.2.3.tar
removing 'slate-0.2.3' (and everything under it)
| [
"This message seems to indicate that the script removed a temporary directory created to do your package... The .tar.gz file is not removed. Check your dist directory for it.\nTo upload you can probably use distutils-documented way:\npython setup.py sdist upload\n\nSome good reads:\n\nDistutils -- Official document... | [
2
] | [] | [] | [
"distutils",
"python"
] | stackoverflow_0004128914_distutils_python.txt |
Q:
How to build/compile C++, Java and Python projects?
Let's say I have a bunch of small targets in different programming languages (C++, Java, Python, etc), with inter programming language dependencies (Java project depends on a C++, Python depends on C++). How can one build/compile them?
I tried scons and more recently gyp. I don't remember what issues I had with scons. Gyp has a very ugly language definition plus I had to hack ant scripts in order to build my java targets.
A:
I would pick one of the more configurable build tools like ant or maven, as a starting point.
Ant is highly configurable, and worst case you can use it to exec another build process (like, make, or whatever you normally use for C++).
Maven also has a number of plugins natively supported for other languages besides java. A quick search of the plugins page shows that maven has native support to build C and C++ code, a google search also hinted at 3rd party plugins that will build your python project as well.
While ant is powerful and configurable, I agree that you sometimes have to hack ant to get it to do what you want, which is neither clean nor desirable. Having worked on my project with maven over the past year, I highly recommend it. We use it to build our java code base, action script front end, run unit and integration tests, and run our database scripts. Moreover, it has great hooks to our continuous integration tools so the builds we run can be automated. With a large number of plugins available, we haven't found much that maven can't do for us.
A:
I once checked out CMake (for C++), I liked it very much. It's easy to use yet powerful and quite similar to Make syntax. It also has Java support.
| How to build/compile C++, Java and Python projects? | Let's say I have a bunch of small targets in different programming languages (C++, Java, Python, etc), with inter programming language dependencies (Java project depends on a C++, Python depends on C++). How can one build/compile them?
I tried scons and more recently gyp. I don't remember what issues I had with scons. Gyp has a very ugly language definition plus I had to hack ant scripts in order to build my java targets.
| [
"I would pick one of the more configurable build tools like ant or maven, as a starting point.\nAnt is highly configurable, and worst case you can use it to exec another build process (like, make, or whatever you normally use for C++).\nMaven also has a number of plugins natively supported for other languages besid... | [
2,
0
] | [] | [] | [
"build",
"c++",
"java",
"python",
"scons"
] | stackoverflow_0004128555_build_c++_java_python_scons.txt |
Q:
Finding which array contributes the maximum value for classification
Given 2 2x2 Numpy arrays, each element having a value between 0 and 1, I would like to find the one array of the 2 that has the maximum value, and do that comparison element-wise. For example, given:
A = [[.6 .2] [.3 .4]] and B = [[.4 .5] [.7 .1]], I would like something like: [[A B] [A B]] back. Ideally, the output will be some number, [[1 2] [1 2]], where 1 represents A, and 2 represents B. That way, if I compare, say, 10 arrays, the output will have an integer between 1 and 10 as each element, which can easily be plotted in a pcolor plot.
If I simply combine those arrays into one 2x2x2 and do np.amax(combined_array, axis=0), I get the maximum value, but don't know which array it comes from.
The purpose of all this is that each array represents a category and contains probabilities of that category occurring. I would like to know for each element position [0][0], [0][1], [1][0], and [1][1], which category is the most probable one occurring at that position.
A:
If you have a combined array of 10 of your 2x2 matrices like the one randomly generated by
a = numpy.random.randn(10, 2, 2)
you can get the desired indices by
a.argmax(axis=0)
| Finding which array contributes the maximum value for classification | Given 2 2x2 Numpy arrays, each element having a value between 0 and 1, I would like to find the one array of the 2 that has the maximum value, and do that comparison element-wise. For example, given:
A = [[.6 .2] [.3 .4]] and B = [[.4 .5] [.7 .1]], I would like something like: [[A B] [A B]] back. Ideally, the output will be some number, [[1 2] [1 2]], where 1 represents A, and 2 represents B. That way, if I compare, say, 10 arrays, the output will have an integer between 1 and 10 as each element, which can easily be plotted in a pcolor plot.
If I simply combine those arrays into one 2x2x2 and do np.amax(combined_array, axis=0), I get the maximum value, but don't know which array it comes from.
The purpose of all this is that each array represents a category and contains probabilities of that category occurring. I would like to know for each element position [0][0], [0][1], [1][0], and [1][1], which category is the most probable one occurring at that position.
| [
"If you have a combined array of 10 of your 2x2 matrices like the one randomly generated by\na = numpy.random.randn(10, 2, 2)\n\nyou can get the desired indices by\na.argmax(axis=0)\n\n"
] | [
3
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0004129149_numpy_python.txt |
Q:
Is there a Django App/Plugin that will do notifications for me?
Such as Twitter's drop down notifications whenever something happens.
Whenever a user finishes registration, the notification will drop down and say, "Thank you"
A:
Would django flash message be sufficient for you?
A:
Why not use django.contrib.messages if you're using Django >= 1.2?
Read this Django Advent article on django.contrib.messages. It seems like it should do what you want.
| Is there a Django App/Plugin that will do notifications for me? | Such as Twitter's drop down notifications whenever something happens.
Whenever a user finishes registration, the notification will drop down and say, "Thank you"
| [
"Would django flash message be sufficient for you?\n",
"Why not use django.contrib.messages if you're using Django >= 1.2?\nRead this Django Advent article on django.contrib.messages. It seems like it should do what you want.\n"
] | [
1,
0
] | [] | [] | [
"django",
"javascript",
"plugins",
"python"
] | stackoverflow_0004129104_django_javascript_plugins_python.txt |
Q:
How to create a raw socket(customised TCP header) using dpkt?
i m writing a code for port scanner so i need to send a raw packet.
i searched and found out that using dpkt library would be better but i didnt find any documentation that would help. So please anyone could help may explaining how to create a packet with customized TCP header i.e set the flags of tcp header as required.
Thank You
A:
Well, this is a bit old but I'll answer anyway since I've been looking to do the same. The dpkt documentation is basically non-existant. The only thing they give you is some samples and Jon Oberheide, the co-developer, wrote some tutorials for it. So if you want to use dpkt it isn't difficult you can figure it out from one of these tutorials:
http://jon.oberheide.org/blog/2008/08/25/dpkt-tutorial-1-icmp-echo/
http://jon.oberheide.org/blog/2008/12/20/dpkt-tutorial-3-dns-spoofing/
Or, http://www.bases-hacking.org/sources/Reseau/IP%20Spoofing/rst_hijack.py as some example code I found helpful, it's well documented. There's lots more code around if you just google it.
If you want an easier API, I've used both of these:
The same guy that wrote dpkt wrote libdnet, which is used by the beastly security scanner Nmap and has python wrappings: http://libdnet.sourceforge.net/. It's got some pretty basic TCP and IP creation functions but the documentation is much better.
Or use this python wrapper for libnet, http://pylibnet.sourceforge.net/. This is very robust and the documentation is great but I couldn't get injection working on OS X. Also every release so far is still beta.
| How to create a raw socket(customised TCP header) using dpkt? | i m writing a code for port scanner so i need to send a raw packet.
i searched and found out that using dpkt library would be better but i didnt find any documentation that would help. So please anyone could help may explaining how to create a packet with customized TCP header i.e set the flags of tcp header as required.
Thank You
| [
"Well, this is a bit old but I'll answer anyway since I've been looking to do the same. The dpkt documentation is basically non-existant. The only thing they give you is some samples and Jon Oberheide, the co-developer, wrote some tutorials for it. So if you want to use dpkt it isn't difficult you can figure it ... | [
1
] | [] | [] | [
"packet",
"python"
] | stackoverflow_0004033776_packet_python.txt |
Q:
How can I remote debug a Python script running on Linux from Windows using PyScripter?
I have a Python script (running Python v2.6 or v2.7) that runs on Linux and also AIX.
I'd like to be able to debug this script from Windows. I'd like to use PyScripter if possible.
If it is not possible to use PyScripter, what other combination of IDE + debugger would you recommend? I would prefer something easy to set up and get running quickly without a huge amount of tinkering.
A:
Currently it is not possible to debug a script on a remote machine from PyScripter. This is a planned feature thought. You may be able to use winpdb.
Update: PyScripter 3.5 supports running/debugging scripts running remotely at Linux and Windows machines. Please have a look at this blog post for details. Have a look also at this blog post.
| How can I remote debug a Python script running on Linux from Windows using PyScripter? | I have a Python script (running Python v2.6 or v2.7) that runs on Linux and also AIX.
I'd like to be able to debug this script from Windows. I'd like to use PyScripter if possible.
If it is not possible to use PyScripter, what other combination of IDE + debugger would you recommend? I would prefer something easy to set up and get running quickly without a huge amount of tinkering.
| [
"Currently it is not possible to debug a script on a remote machine from PyScripter. This is a planned feature thought. You may be able to use winpdb. \nUpdate: PyScripter 3.5 supports running/debugging scripts running remotely at Linux and Windows machines. Please have a look at this blog post for details. Ha... | [
1
] | [] | [] | [
"debugging",
"pyscripter",
"python",
"remote_debugging"
] | stackoverflow_0004127790_debugging_pyscripter_python_remote_debugging.txt |
Q:
PyScripter - cannot termiate Run with KeyboardInterrupt
I write alot of small apps where I use
try:
print "always does this until I Ctrl+C"
Except KeyboardInterrupt:
print "finish program"
I've just began to move away from using IDLE and booted up PyScripter. However CTRL+C no longer works. Is it possible to still send in a KeyboardInterrupt while using the built-in interpreter?
A:
In PyScripter if you just want to terminate a running program you can always re-initialize the remote engine:
Application Run Menu > Python Engine > Reinitialize Python Engine or
Interpreter context menu > Python Engine > Reinitialize Python Engine or
Keyboard shortcut CTRL-F2
Source, Psyscripter Author
A:
I keep answering my own questions, but I believe they are valid..
The PyScripter google group has one implementation where they import a progress bar and kill it, simulating an interrupt. however, this is not the same as a keyboard interrupt. Looks like i'm out of luck until a new implementation.
Having Said That, can anyone suggest another novel way to terminate programs at a user's discretion (without using threads :p)?
| PyScripter - cannot termiate Run with KeyboardInterrupt | I write alot of small apps where I use
try:
print "always does this until I Ctrl+C"
Except KeyboardInterrupt:
print "finish program"
I've just began to move away from using IDLE and booted up PyScripter. However CTRL+C no longer works. Is it possible to still send in a KeyboardInterrupt while using the built-in interpreter?
| [
"In PyScripter if you just want to terminate a running program you can always re-initialize the remote engine:\n\nApplication Run Menu > Python Engine > Reinitialize Python Engine or \nInterpreter context menu > Python Engine > Reinitialize Python Engine or\nKeyboard shortcut CTRL-F2\n\nSource, Psyscripter Author\n... | [
6,
0
] | [] | [] | [
"keyboardinterrupt",
"pyscripter",
"python"
] | stackoverflow_0002246885_keyboardinterrupt_pyscripter_python.txt |
Q:
Store user's name on Google App Engine, without calling get_current_user every time?
I have a Google App Engine site, with multiple pages that are rendered using templates. I'd like to have a hello, user!-type greeting on the header of every page. I can call users.get_current_user().nickname()(or something like) on every handler and add that to the template values dictionary, but I was wondering if there was a cleaner way to do it - perhaps call it directly from the template?
A:
I don't know of a built-in way to access that from a template, but I agree with you that I certainly wouldn't want to have to re-type the code in every handler.
If all your views are children of one main handler then you can stick the code in that main handler and be done with it, e.g.:
class BaseHandler(webapp.RequestHandler):
def __init__(self):
pass
def render(self, template_filename, template_args):
nick = users.get_current_user().nickname()
template_args['nick'] = nick
self.response.out.write(
template.render(
self.template_path(template_filename), template_args))
Source code for a full example.
| Store user's name on Google App Engine, without calling get_current_user every time? | I have a Google App Engine site, with multiple pages that are rendered using templates. I'd like to have a hello, user!-type greeting on the header of every page. I can call users.get_current_user().nickname()(or something like) on every handler and add that to the template values dictionary, but I was wondering if there was a cleaner way to do it - perhaps call it directly from the template?
| [
"I don't know of a built-in way to access that from a template, but I agree with you that I certainly wouldn't want to have to re-type the code in every handler.\nIf all your views are children of one main handler then you can stick the code in that main handler and be done with it, e.g.:\nclass BaseHandler(webapp.... | [
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004129475_google_app_engine_python.txt |
Q:
Writing a "table" from Python3
How does one write both multiple strings and multiple variable outputs on one line in a file to output?
I know that write() only accepts one argument, though ideally this is what I'm trying to achieve:
write('Temperature is', X , 'and pressure is', Y)
The result would be a table.
Can you help?
A:
write('Temperature is {0} and pressure is {1})'.format(X,Y))
If you want more control over the output you can do something like this:
X = 12.3
Y = 1.23
write('Temperature is {0:.1f} and pressure is {1:.2f})'.format(X,Y))
# writes 'Temperature is 12.3 and pressure is 1.2'
Documentation and examples here: http://docs.python.org/py3k/library/string.html
A:
f = open("somefile.txt", "w")
print('Temperature is', X , 'and pressure is', Y, file=f)
| Writing a "table" from Python3 | How does one write both multiple strings and multiple variable outputs on one line in a file to output?
I know that write() only accepts one argument, though ideally this is what I'm trying to achieve:
write('Temperature is', X , 'and pressure is', Y)
The result would be a table.
Can you help?
| [
"write('Temperature is {0} and pressure is {1})'.format(X,Y))\n\nIf you want more control over the output you can do something like this:\nX = 12.3\nY = 1.23\nwrite('Temperature is {0:.1f} and pressure is {1:.2f})'.format(X,Y))\n# writes 'Temperature is 12.3 and pressure is 1.2'\n\nDocumentation and examples here: ... | [
2,
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0004129624_python_python_3.x.txt |
Q:
Is this the correct way of doing/handling url rewrite in App Engine/ Python?
I'm not sure if this is effective or not. It works, but sometimes i feel...weird about it. Can you please tell me if this is a good way or not?
I threw the code on pastebin, because i think it's a bit too much to put here: http://pastebin.com/662TiQLq
EDIT
I edited the title to make it more objective.
A:
I'm just guessing that the questioner is asking about creating a dictionary of functions in the __ init __ function of the handlers, and then using this dict in the "get" function to look up specific functions. If this is the question, then IMHO a clearer approach would be to set up separate handlers for each different function. For example
class QuotesView(webapp.RequestHandler):
"""Super class for quotes that can accommodate common functionality"""
pass
class QuotesViewSingle(QuotesView):
def get(self):
...
class QuotesViewRandom(QuotesView):
def get(self):
...
class QuotesViewAll(QuotesView):
def get(self):
...
def main():
application = webapp.WSGIApplication([('/quote/new',NewQuote),
(r'/quotes/single',QuotesViewSingle),
(r'/quotes/all',QuotesViewAll),
(r'/quotes/random',QuotesViewRandom),
...
('/', MainHandler)],
debug=True)
BTW. A lot of people use the regex in the WSGIApplication calls to parse out arguments for the get functions. There's nothing particularly wrong with it. I'm not a big fan of that feature, and prefer to parse the arguments in the get functions. But that's just me.
For completeness here's the original code:
class Quote(db.Model):
author = db.StringProperty()
string = db.StringProperty()
class MainHandler(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
quotes = Quote.all()
path = os.path.join(os.path.dirname(__file__),'quotery.html')
template_values = {'quotes':quotes,'user':user,'login_url':users.create_login_url('/')}
self.response.out.write(template.render(path, template_values))
class QuoteHandler(webapp.RequestHandler):
def __init__(self):
self.actions = {'fetch':self.fetch, 'random':self.fetch_random}
#Memcache the number of quotes in the datastore, to minimize datastore calls
self.quote_count = memcache.get('quote_count')
if not self.quote_count:
self.quote_count = self.cache_quote_count()
def cache_quote_count(self):
count = Quote.all().count()
memcache.add(key='quote_count', value=count, time=3600)
return count
def get(self, key):
if key in self.actions:
action = self.actions[key]
action()
def fetch(self):
for quote in Quote.all():
print 'Quote!'
print 'Author: ',quote.author
print 'String: ',quote.string
print
def fetch_random(self):
max_offset = self.quote_count-1
random_offset = random.randint(0,max_offset)
'''self.response.out.write(max_offset)
self.response.out.write('\n<br/>')
self.response.out.write(random_offset)'''
try:
query = db.GqlQuery("SELECT * FROM Quote")
quotes = query.fetch(1,random_offset)
return quotes
'''for quote in quotes:
self.response.out.write(quote.author)
self.response.out.write('\n')
self.response.out.write(quote.string)'''
except BaseException:
raise
class NewQuote(webapp.RequestHandler):
def post(self):
author = self.request.get('quote_author')
string = self.request.get('quote_string')
if not author or not string:
return False
quote = Quote()
quote.author = author
quote.string = string
quote.put()
QuoteHandler().cache_quote_count()
self.redirect("/")
#return True
class QuotesView(webapp.RequestHandler):
def __init__(self):
self.actions = {'all':self.view_all,'random':self.view_random,'get':self.view_single}
def get(self, key):
if not key or key not in self.actions:
self.view_all()
if key in self.actions:
action = self.actions[key]
action()
def view_all(self):
print 'view all'
def view_random(self):
quotes = QuoteHandler().fetch_random()
template_data = {}
for quote in quotes:
template_data['quote'] = quote
template_path = os.path.join(os.path.dirname(__file__),'base_view.html')
self.response.out.write(template.render(template_path, template_data))
def view_single(self):
print 'view single'
def main():
application = webapp.WSGIApplication([('/quote/new',NewQuote),(r'/quotes/(.*)',QuotesView),(r'/quote/(.*)',QuoteHandler),('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
| Is this the correct way of doing/handling url rewrite in App Engine/ Python? | I'm not sure if this is effective or not. It works, but sometimes i feel...weird about it. Can you please tell me if this is a good way or not?
I threw the code on pastebin, because i think it's a bit too much to put here: http://pastebin.com/662TiQLq
EDIT
I edited the title to make it more objective.
| [
"I'm just guessing that the questioner is asking about creating a dictionary of functions in the __ init __ function of the handlers, and then using this dict in the \"get\" function to look up specific functions. If this is the question, then IMHO a clearer approach would be to set up separate handlers for each d... | [
2
] | [] | [] | [
"google_app_engine",
"python",
"url_rewriting"
] | stackoverflow_0004117051_google_app_engine_python_url_rewriting.txt |
Q:
Is there a DotNetOpenAuth equivalent that runs on a LAMP stack?
I really love the way the StackExchange family of sites allow someone to log in using their OpenID or OAuth provider, which has been open-sourced as DotNetOpenAuth. This is absolutely wonderful, but I am unable to use it on a *AMP stack.
Is there anything analogous that runs in PHP, Perl, Python or Ruby?
A:
For Perl there's Net::OAuth, and there looks to be an as-yet-unreleased Catalyst::Controller::OAuth, but what the status of that last one is is unknown (other than the OAuth code page says they're "working on" it).
A:
Try Catalyst::Plugin::Authentication::Credential::OpenID - OpenID credential for Catalyst::Auth framework
A:
For Perl you want Net::OpenID::Consumer. Development is getting started on it again so in the next few weeks you should see new versions with some of the major bugs fixed and new docs explaining how to use them properly (it can be hard to figure out right now). See the openid-perl group for more details.
| Is there a DotNetOpenAuth equivalent that runs on a LAMP stack? | I really love the way the StackExchange family of sites allow someone to log in using their OpenID or OAuth provider, which has been open-sourced as DotNetOpenAuth. This is absolutely wonderful, but I am unable to use it on a *AMP stack.
Is there anything analogous that runs in PHP, Perl, Python or Ruby?
| [
"For Perl there's Net::OAuth, and there looks to be an as-yet-unreleased Catalyst::Controller::OAuth, but what the status of that last one is is unknown (other than the OAuth code page says they're \"working on\" it).\n",
"Try Catalyst::Plugin::Authentication::Credential::OpenID - OpenID credential for Catalyst::... | [
1,
0,
0
] | [] | [] | [
"dotnetopenauth",
"perl",
"php",
"python",
"ruby"
] | stackoverflow_0003865286_dotnetopenauth_perl_php_python_ruby.txt |
Q:
Configuring up and down arrows to scroll history in Python shell
I installed Python 2.7 on my mac from source. Before, I could use the arrow keys to scroll through my history. Now, I get this:
>>> print 'stupid'
'stupid'
>>> ^[[A # This is my feeble attempt at scrolling up.
Scrolling still works if I use Python 2.6
Is there a config file for this or is this something that I have to set at compile time?
A:
You forgot to install readline or libedit before building.
| Configuring up and down arrows to scroll history in Python shell | I installed Python 2.7 on my mac from source. Before, I could use the arrow keys to scroll through my history. Now, I get this:
>>> print 'stupid'
'stupid'
>>> ^[[A # This is my feeble attempt at scrolling up.
Scrolling still works if I use Python 2.6
Is there a config file for this or is this something that I have to set at compile time?
| [
"You forgot to install readline or libedit before building.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004129955_python.txt |
Q:
Why aren't anonymous (C)Python objects deallocated immediately?
I noticed something about CPython's object deallocation which piqued my curiosity. Let's say I define a type that prints a message from its tp_dealloc function:
static void pyfoo_Bar_dealloc(pyfoo_Bar* self)
{
PySys_WriteStdout("Bar freed\n");
self->ob_type->tp_free((PyObject*)self);
}
I've also done the right thing with the allocator:
PyMODINIT_FUNC initpyfoo(void)
{
PyObject* m;
pyfoo_BarType.tp_new = PyType_GenericNew;
/* ... */
}
I compile it and run a Python 2.6 interpreter in the directory with pyfoo.so:
>>> import pyfoo
>>> a = pyfoo.Bar()
>>> a = None
Bar freed
>>> quit()
This is what I'd expect... the reference count drops to zero and the Bar object is collected. But now if I do:
>>> import pyfoo
>>> pyfoo.Bar()
<pyfoo.Bar object at 0x7f7c6d8f2080>
>>> quit()
Bar freed
... the Bar object is not collected until the interpreter exits. But surely the reference count on the Bar object created anonymously is zero, just like the one explicitly assigned. So why is it not deallocated immediately after creation?
(I'm doing this on Debian Squeeze with Python 2.6.6 compiled with GCC 4.4.5. I know it's not a "bug", I know Python-the-language doesn't place any particular constraints on Python interpreters this... I just want to know what is going on under the hood that makes it ignore anonymous objects like this.)
A:
Because after you called pyfoo.Bar() the object is still accessible using the special object _
This works with pure Python, by the way:
class X:
def __del__(self):
print 'deleted'
And later:
>>>a = X()
>>>a = None
deleted
>>>X()
<__main__.X instance at 0x7f391bb066c8>
>>> _
<__main__.X instance at 0x7f391bb066c8>
>>> 3 # causes _ to be reassigned
deleted
3
Notice how reassigning _ implicitly deleted the X object?
A:
Because you're using the REPL, which stores the last result in _. So it isn't really anonymous after all.
| Why aren't anonymous (C)Python objects deallocated immediately? | I noticed something about CPython's object deallocation which piqued my curiosity. Let's say I define a type that prints a message from its tp_dealloc function:
static void pyfoo_Bar_dealloc(pyfoo_Bar* self)
{
PySys_WriteStdout("Bar freed\n");
self->ob_type->tp_free((PyObject*)self);
}
I've also done the right thing with the allocator:
PyMODINIT_FUNC initpyfoo(void)
{
PyObject* m;
pyfoo_BarType.tp_new = PyType_GenericNew;
/* ... */
}
I compile it and run a Python 2.6 interpreter in the directory with pyfoo.so:
>>> import pyfoo
>>> a = pyfoo.Bar()
>>> a = None
Bar freed
>>> quit()
This is what I'd expect... the reference count drops to zero and the Bar object is collected. But now if I do:
>>> import pyfoo
>>> pyfoo.Bar()
<pyfoo.Bar object at 0x7f7c6d8f2080>
>>> quit()
Bar freed
... the Bar object is not collected until the interpreter exits. But surely the reference count on the Bar object created anonymously is zero, just like the one explicitly assigned. So why is it not deallocated immediately after creation?
(I'm doing this on Debian Squeeze with Python 2.6.6 compiled with GCC 4.4.5. I know it's not a "bug", I know Python-the-language doesn't place any particular constraints on Python interpreters this... I just want to know what is going on under the hood that makes it ignore anonymous objects like this.)
| [
"Because after you called pyfoo.Bar() the object is still accessible using the special object _\nThis works with pure Python, by the way:\nclass X:\n def __del__(self):\n print 'deleted'\n\nAnd later:\n >>>a = X()\n >>>a = None\n deleted\n >>>X()\n <__main__.X instance at 0x7f391bb066c8> \n >>> _\n <__mai... | [
9,
3
] | [] | [] | [
"garbage_collection",
"python"
] | stackoverflow_0004129950_garbage_collection_python.txt |
Q:
How do I queue FTP commands in Twisted?
I'm writing an FTP client using Twisted that downloads a lot of files and I'm trying to do it pretty intelligently. However, I've been having the problem that I'll download several files very quickly (sometimes ~20 per batch, sometimes ~250) and then the downloading will hang, only to eventually have connections time out and then the download and hang start all over again. I'm using a DeferredSemaphore to only download 3 files at a time, but I now suspect that this is probably not the right way to avoid throttling the server.
Here is the code in question:
def downloadFiles(self, result, directory):
# make download directory if it doesn't already exist
if not os.path.exists(directory['filename']):
os.makedirs(directory['filename'])
log.msg("Downloading files in %r..." % directory['filename'])
files = filterFiles(None, self.fileListProtocol)
# from http://stackoverflow.com/questions/2861858/queue-remote-calls-to-a-python-twisted-perspective-broker/2862440#2862440
# use a DeferredSemaphore to limit the number of files downloaded simultaneously from the directory to 3
sem = DeferredSemaphore(3)
jobs = [sem.run(self.downloadFile, f, directory) for f in files]
d = gatherResults(jobs)
return d
def downloadFile(self, f, directory):
filename = os.path.join(directory['filename'], f['filename']).encode('ascii')
log.msg('Downloading %r...' % filename)
d = self.ftpClient.retrieveFile(filename, FTPFile(filename))
return d
You'll noticed that I'm reusing an FTP connection (active, by the way) and using my own FTPFile instance to make sure the local file object gets closed when the file download connection is 'lost' (ie completed). Looking at FTPClient I wonder if I should be using queueCommand directly. To be honest, I got lost following the retrieveFile command to _openDataConnection and beyond, so maybe it's already being used.
Any suggestions? Thanks!
A:
I would suggest using queueCommand, as you suggested I'd suspect the semaphore you're using is probably causing you issues. I believe using queueCommand will limit your FTPClient to a single active connection (though I'm just speculating), so you may want to think about creating a few FTPClient instances and passing download jobs to them if you want to do things quickly. If you use queueStringCommand, you get a Deferred that you can use to determine where each client is up to, and even add another job to the queue for that client in the callback.
| How do I queue FTP commands in Twisted? | I'm writing an FTP client using Twisted that downloads a lot of files and I'm trying to do it pretty intelligently. However, I've been having the problem that I'll download several files very quickly (sometimes ~20 per batch, sometimes ~250) and then the downloading will hang, only to eventually have connections time out and then the download and hang start all over again. I'm using a DeferredSemaphore to only download 3 files at a time, but I now suspect that this is probably not the right way to avoid throttling the server.
Here is the code in question:
def downloadFiles(self, result, directory):
# make download directory if it doesn't already exist
if not os.path.exists(directory['filename']):
os.makedirs(directory['filename'])
log.msg("Downloading files in %r..." % directory['filename'])
files = filterFiles(None, self.fileListProtocol)
# from http://stackoverflow.com/questions/2861858/queue-remote-calls-to-a-python-twisted-perspective-broker/2862440#2862440
# use a DeferredSemaphore to limit the number of files downloaded simultaneously from the directory to 3
sem = DeferredSemaphore(3)
jobs = [sem.run(self.downloadFile, f, directory) for f in files]
d = gatherResults(jobs)
return d
def downloadFile(self, f, directory):
filename = os.path.join(directory['filename'], f['filename']).encode('ascii')
log.msg('Downloading %r...' % filename)
d = self.ftpClient.retrieveFile(filename, FTPFile(filename))
return d
You'll noticed that I'm reusing an FTP connection (active, by the way) and using my own FTPFile instance to make sure the local file object gets closed when the file download connection is 'lost' (ie completed). Looking at FTPClient I wonder if I should be using queueCommand directly. To be honest, I got lost following the retrieveFile command to _openDataConnection and beyond, so maybe it's already being used.
Any suggestions? Thanks!
| [
"I would suggest using queueCommand, as you suggested I'd suspect the semaphore you're using is probably causing you issues. I believe using queueCommand will limit your FTPClient to a single active connection (though I'm just speculating), so you may want to think about creating a few FTPClient instances and passi... | [
1
] | [] | [] | [
"ftp",
"ftp_client",
"python",
"twisted"
] | stackoverflow_0004129291_ftp_ftp_client_python_twisted.txt |
Q:
python -regex matching a word list
I have a python script which has probably 100 or so regex lines each line matching certain words.
The script obviously consumes up to 100% cpu each time it is run (I basically pass a sentence to it and it will return any matched words found).
I want to combine these into around 4 or 5 different "compiled" regex parsers such as:
>>> words = ('hello', 'good\-bye', 'red', 'blue')
>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)
How many words can I safely have in this and would it make a difference? Right now if I run a loop on a thousand random sentences it processes maybe 10 a second, looking to drastically increase this speed so it does like 500 a second (if possible).
Also, is it possible to a list like this?
>>> words = ('\d{4,4}\.\d{2,2}\.\d{2,2}', '\d{2,2}\s\d{2,2}\s\d{4,4}\.')
>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)
>>> print pattern.findall("Today is 2010 11 08)
A:
Your algorithm here is basically O(N*M*L) (where N is the length of the sentence, M is the number of words you're looking for, and L is the longest word you're looking for) for each sentence. Using a regex won't speed this up any more than just using find. The only thing it does give you is the ability to match patterns like your second example.
If you want to just find words, a Trie would be a much better approach. The implementation is really easy, too:
TERMINAL = 'TERMINAL' # Marks the end of a word
def build(*words, trie={}):
for word in words:
pointer = trie
for ch in word:
pt = pt.setdefault(ch, {TERMINAL:False})
pt[TERMINAL] = True
return trie
def find(input, trie):
results = []
for i in range(len(input)):
pt = trie
for j in range(i, len(input)+1):
if pt[TERMINAL]:
results.append(input[i:j])
if j >= len(input) or input[j] not in pt:
break
pt = pt[input[j]]
return results
This returns all words in your sentence that are in the trie. Running time is O(N*L), meaning that you can add as many words as you want without slowing down the algorithm.
| python -regex matching a word list | I have a python script which has probably 100 or so regex lines each line matching certain words.
The script obviously consumes up to 100% cpu each time it is run (I basically pass a sentence to it and it will return any matched words found).
I want to combine these into around 4 or 5 different "compiled" regex parsers such as:
>>> words = ('hello', 'good\-bye', 'red', 'blue')
>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)
How many words can I safely have in this and would it make a difference? Right now if I run a loop on a thousand random sentences it processes maybe 10 a second, looking to drastically increase this speed so it does like 500 a second (if possible).
Also, is it possible to a list like this?
>>> words = ('\d{4,4}\.\d{2,2}\.\d{2,2}', '\d{2,2}\s\d{2,2}\s\d{4,4}\.')
>>> pattern = re.compile('(' + '|'.join(words) + ')', re.IGNORECASE)
>>> print pattern.findall("Today is 2010 11 08)
| [
"Your algorithm here is basically O(N*M*L) (where N is the length of the sentence, M is the number of words you're looking for, and L is the longest word you're looking for) for each sentence. Using a regex won't speed this up any more than just using find. The only thing it does give you is the ability to match pa... | [
4
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004130134_python_regex.txt |
Q:
Python threading flow control in concise way
I want to upload a file to two ftp sites. After both finishing, I need to delete the file.
In case not to block the main function running, both ftp and deletion functions will be implemented by threading, which means there will be 3 threads running in background simultaneously. An easy problem becomes complicated because of threading.
Following are possible solutions:
Use a queue and put all three threads in order
Use mutex
Both work, but I don't think they are the best way to do that. Can anyone share his/her idea?
A:
Use a semaphore.
In your parent handler create a semaphore of 0 and hand it off to the threads.
import threading
sem = threading.Semaphore(0)
hostThread = threading.Thread(target=uploadToHost, args=(sem,))
backupThread = threading.Thread(target=uploadToBackup, args=(sem,))
sem.acquire() # Wait for one of them to finish
sem.acquire() # Wait for the other to finish
In your children, you'll just have to call sem.release once the upload is finished.
| Python threading flow control in concise way | I want to upload a file to two ftp sites. After both finishing, I need to delete the file.
In case not to block the main function running, both ftp and deletion functions will be implemented by threading, which means there will be 3 threads running in background simultaneously. An easy problem becomes complicated because of threading.
Following are possible solutions:
Use a queue and put all three threads in order
Use mutex
Both work, but I don't think they are the best way to do that. Can anyone share his/her idea?
| [
"Use a semaphore.\nIn your parent handler create a semaphore of 0 and hand it off to the threads.\nimport threading\n\nsem = threading.Semaphore(0)\n\nhostThread = threading.Thread(target=uploadToHost, args=(sem,))\nbackupThread = threading.Thread(target=uploadToBackup, args=(sem,))\n\nsem.acquire() # Wait for one ... | [
0
] | [] | [] | [
"multithreading",
"mutex",
"python"
] | stackoverflow_0004130475_multithreading_mutex_python.txt |
Q:
App Engine _ah login page not working locally
Whenever i click on the link created by users.create_login_url(), i get an error (shown below). When deployed, the thing works, but doesn't work locally.
What is wrong?
Here's the code:
import random
import os
from google.appengine.api import users
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
url = users.create_login_url('/quote')
link = '<a href="%s">Login</a>' % url
self.response.out.write(link)
class QuoteHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("Quote Handler!")
def new(self):
self.response.out.write("New quote")
def main():
application = webapp.WSGIApplication([(r'/quote/(.*)',QuoteHandler),('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
And here's the error it gives me:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3211, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3154, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 527, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2452, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2404, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2441, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2312, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "C:\Python27\lib\pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "C:\Python27\lib\pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "C:\Python27\lib\pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "C:\Python27\lib\pprint.py", line 230, in _repr
self._depth, level)
File "C:\Python27\lib\pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "C:\Python27\lib\pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "C:\Python27\lib\pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "C:\Python27\lib\warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
EDIT
SDK Version: 1.3.8
Python: 2.7
A:
You are using Python 2.7 that is not supported by Google App Engine (issue here).
You need to downgrade to Python 2.5 to make it work.
A:
I fixed this problem on Fedora 14 w/ Python 2.7 by commenting out the following:
# logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
on line 2312 of dev_appserver.py located at google_appengine_sdk_dir/google/appengine/tools
Here's the stack trace, where you can see line 2312 was causing the exception to be thrown:
Traceback (most recent call last):
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 3211, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 3154, in _Dispatch
base_env_dict=env_dict)
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 527, in Dispatch
base_env_dict=base_env_dict)
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 2452, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 2404, in Dispatch
self._module_dict)
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 2441, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "/google_app_sdk/google/appengine/tools/dev_appserver.py", line 2312, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "/usr/lib64/python2.7/pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "/usr/lib64/python2.7/pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "/usr/lib64/python2.7/pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "/usr/lib64/python2.7/pprint.py", line 230, in _repr
self._depth, level)
File "/usr/lib64/python2.7/pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "/usr/lib64/python2.7/pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "/usr/lib64/python2.7/pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "/usr/lib64/python2.7/warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
Commenting out that one line seems to make everything work just fine, no other errors and I don't have to downgrade to Python 2.5.
A:
I've seen this problem -- you're running the wrong version of Python locally.
Install Python 2.5 and ths problem should go away -- it did for me.
http://www.python.org/download/releases/2.5.5/
| App Engine _ah login page not working locally | Whenever i click on the link created by users.create_login_url(), i get an error (shown below). When deployed, the thing works, but doesn't work locally.
What is wrong?
Here's the code:
import random
import os
from google.appengine.api import users
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app
class MainHandler(webapp.RequestHandler):
def get(self):
url = users.create_login_url('/quote')
link = '<a href="%s">Login</a>' % url
self.response.out.write(link)
class QuoteHandler(webapp.RequestHandler):
def get(self):
self.response.out.write("Quote Handler!")
def new(self):
self.response.out.write("New quote")
def main():
application = webapp.WSGIApplication([(r'/quote/(.*)',QuoteHandler),('/', MainHandler)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
And here's the error it gives me:
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3211, in _HandleRequest
self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3154, in _Dispatch
base_env_dict=env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 527, in Dispatch
base_env_dict=base_env_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2452, in Dispatch
CGIDispatcher.Dispatch(self, *args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2404, in Dispatch
self._module_dict)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2441, in curried_exec_cgi
return ExecuteCGI(*args, **kwargs)
File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2312, in ExecuteCGI
logging.debug('Executing CGI with env:\n%s', pprint.pformat(env))
File "C:\Python27\lib\pprint.py", line 60, in pformat
return PrettyPrinter(indent=indent, width=width, depth=depth).pformat(object)
File "C:\Python27\lib\pprint.py", line 119, in pformat
self._format(object, sio, 0, 0, {}, 0)
File "C:\Python27\lib\pprint.py", line 137, in _format
rep = self._repr(object, context, level - 1)
File "C:\Python27\lib\pprint.py", line 230, in _repr
self._depth, level)
File "C:\Python27\lib\pprint.py", line 242, in format
return _safe_repr(object, context, maxlevels, level)
File "C:\Python27\lib\pprint.py", line 284, in _safe_repr
for k, v in _sorted(object.items()):
File "C:\Python27\lib\pprint.py", line 75, in _sorted
with warnings.catch_warnings():
File "C:\Python27\lib\warnings.py", line 327, in __init__
self._module = sys.modules['warnings'] if module is None else module
KeyError: 'warnings'
EDIT
SDK Version: 1.3.8
Python: 2.7
| [
"You are using Python 2.7 that is not supported by Google App Engine (issue here).\nYou need to downgrade to Python 2.5 to make it work.\n",
"I fixed this problem on Fedora 14 w/ Python 2.7 by commenting out the following:\n# logging.debug('Executing CGI with env:\\n%s', pprint.pformat(env))\n\non line 2312 of de... | [
1,
1,
0
] | [] | [] | [
"authentication",
"google_app_engine",
"python"
] | stackoverflow_0004115374_authentication_google_app_engine_python.txt |
Q:
self.response.out.write() - how to use it properly?
I have a class that doesn't extend webapp.RequestHandler, and I can't use self.response.out.write(), I get:
AttributeError: Fetcher instance has no attribute 'response'
If I extend webapp.RequestHandler (I thought it would work), I get:
AttributeError: 'Fetcher' object has no attribute 'response'
How can I use that method properly? Sometimes print doesn't work either; I just get a blank screen.
EDIT:
app.yaml:
application: fbapp-lotsofquotes
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: main.py
source (the problematic line is marked with #<- HERE):
import random
import os
from google.appengine.api import users, memcache
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app
import facebook
class Quote(db.Model):
author = db.StringProperty()
string = db.StringProperty()
categories = db.StringListProperty()
#rating = db.RatingProperty()
class Fetcher(webapp.RequestHandler):
'''
Memcache keys: all_quotes
'''
def is_cached(self, key):
self.fetched = memcache.get(key)
if self.fetched:
print 'ok'#return True
else:
print 'not ok'#return False
#TODO: Use filters!
def fetch_quotes(self):
quotes = memcache.get('all_quotes')
if not quotes:
#Fetch and cache it, since it's not in the memcache.
quotes = Quote.all()
memcache.set('all_quotes',quotes,3600)
return quotes
def fetch_quote_by_id(self, id):
self.response.out.write(id) #<---------- HERE
class MainHandler(webapp.RequestHandler):
def get(self):
quotes = Fetcher().fetch_quotes()
template_data = {'quotes':quotes}
template_path = 'many.html'
self.response.out.write(template.render(template_path, template_data))
class ViewQuoteHandler(webapp.RequestHandler):
def get(self, obj):
self.response.out.write('viewing quote<br/>\n')
if obj == 'all':
quotes = Fetcher().fetch_quotes()
self.render('view_many.html',quotes=quotes)
else:
quotes = Fetcher().fetch_quote_by_id(obj)
'''for quote in quotes:
print quote.author
print quote.'''
def render(self, type, **kwargs):
if type == 'single':
template_values = {'quote':kwargs['quote']}
template_path = 'single_quote.html'
elif type == 'many':
print 'many'
self.response.out.write(template.render(template_path, template_values))
'''
CREATORS
'''
class NewQuoteHandler(webapp.RequestHandler):
def get(self, action):
if action == 'compose':
self.composer()
elif action == 'do':
print 'hi'
def composer(self):
template_path = 'quote_composer.html'
template_values = ''
self.response.out.write(template.render(template_path,template_values))
def post(self, action):
author = self.request.get('quote_author')
string = self.request.get('quote_string')
print author, string
if not author or not string:
print 'REDIRECT'
quote = Quote()
quote.author = author
quote.string = string
quote.categories = []
quote.put()
def main():
application = webapp.WSGIApplication([('/', MainHandler),
(r'/view/quote/(.*)',ViewQuoteHandler),
(r'/new/quote/(.*)',NewQuoteHandler) ],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
A:
You're not routing to Fetcher when you initialize a WSGIApplication. Rather, you create an instance manually in other handlers. Thus, App Engine will not initialize your request and response properties. You can manually do so in from the handlers you route to, such as MainHandler and ViewQuoteHandler. E.g.:
fetcher = Fetcher()
fetcher.initialize(self.request, self.response)
quotes = fetcher.fetch_quotes()
Note that fetcher really doesn't have to be a RequestHandler. It could be a separate class or function. Once you have request and response objects, you can pass them around as you choose.
| self.response.out.write() - how to use it properly? | I have a class that doesn't extend webapp.RequestHandler, and I can't use self.response.out.write(), I get:
AttributeError: Fetcher instance has no attribute 'response'
If I extend webapp.RequestHandler (I thought it would work), I get:
AttributeError: 'Fetcher' object has no attribute 'response'
How can I use that method properly? Sometimes print doesn't work either; I just get a blank screen.
EDIT:
app.yaml:
application: fbapp-lotsofquotes
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: main.py
source (the problematic line is marked with #<- HERE):
import random
import os
from google.appengine.api import users, memcache
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import util, template
from google.appengine.ext.webapp.util import run_wsgi_app
import facebook
class Quote(db.Model):
author = db.StringProperty()
string = db.StringProperty()
categories = db.StringListProperty()
#rating = db.RatingProperty()
class Fetcher(webapp.RequestHandler):
'''
Memcache keys: all_quotes
'''
def is_cached(self, key):
self.fetched = memcache.get(key)
if self.fetched:
print 'ok'#return True
else:
print 'not ok'#return False
#TODO: Use filters!
def fetch_quotes(self):
quotes = memcache.get('all_quotes')
if not quotes:
#Fetch and cache it, since it's not in the memcache.
quotes = Quote.all()
memcache.set('all_quotes',quotes,3600)
return quotes
def fetch_quote_by_id(self, id):
self.response.out.write(id) #<---------- HERE
class MainHandler(webapp.RequestHandler):
def get(self):
quotes = Fetcher().fetch_quotes()
template_data = {'quotes':quotes}
template_path = 'many.html'
self.response.out.write(template.render(template_path, template_data))
class ViewQuoteHandler(webapp.RequestHandler):
def get(self, obj):
self.response.out.write('viewing quote<br/>\n')
if obj == 'all':
quotes = Fetcher().fetch_quotes()
self.render('view_many.html',quotes=quotes)
else:
quotes = Fetcher().fetch_quote_by_id(obj)
'''for quote in quotes:
print quote.author
print quote.'''
def render(self, type, **kwargs):
if type == 'single':
template_values = {'quote':kwargs['quote']}
template_path = 'single_quote.html'
elif type == 'many':
print 'many'
self.response.out.write(template.render(template_path, template_values))
'''
CREATORS
'''
class NewQuoteHandler(webapp.RequestHandler):
def get(self, action):
if action == 'compose':
self.composer()
elif action == 'do':
print 'hi'
def composer(self):
template_path = 'quote_composer.html'
template_values = ''
self.response.out.write(template.render(template_path,template_values))
def post(self, action):
author = self.request.get('quote_author')
string = self.request.get('quote_string')
print author, string
if not author or not string:
print 'REDIRECT'
quote = Quote()
quote.author = author
quote.string = string
quote.categories = []
quote.put()
def main():
application = webapp.WSGIApplication([('/', MainHandler),
(r'/view/quote/(.*)',ViewQuoteHandler),
(r'/new/quote/(.*)',NewQuoteHandler) ],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
"You're not routing to Fetcher when you initialize a WSGIApplication. Rather, you create an instance manually in other handlers. Thus, App Engine will not initialize your request and response properties. You can manually do so in from the handlers you route to, such as MainHandler and ViewQuoteHandler. E.g.:\nf... | [
2
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004131013_google_app_engine_python.txt |
Q:
setting ftp service via web with python
sorry if my english bad...
anyone can tell me how to setting ftp service via web using python...
i want my site can control the ftp service like sinology diskstation..
like enable/disable ftp service, control how many connection, add or remove user, etc.
i use linux and python+django
or just give me where to find the article..
A:
You can try this: http://code.google.com/p/pyftpdlib/
Filezilla can be controlled by command lines. The users and other parameters can be edited in the Server XML file.
| setting ftp service via web with python | sorry if my english bad...
anyone can tell me how to setting ftp service via web using python...
i want my site can control the ftp service like sinology diskstation..
like enable/disable ftp service, control how many connection, add or remove user, etc.
i use linux and python+django
or just give me where to find the article..
| [
"You can try this: http://code.google.com/p/pyftpdlib/\nFilezilla can be controlled by command lines. The users and other parameters can be edited in the Server XML file.\n"
] | [
0
] | [] | [] | [
"ftp",
"linux",
"python"
] | stackoverflow_0004131003_ftp_linux_python.txt |
Q:
What are the best uses for the Django Admin app?
On the website, it says this:
One of the most powerful parts of
Django is the automatic admin
interface. It reads metadata in your
model to provide a powerful and
production-ready interface that
content producers can immediately use
to start adding content to the site.
In this document, we discuss how to
activate, use and customize Django’s
admin interface.admin interface.
So what? I still don't understand what the Admin interface is used for. Is it like a PHPMYADMIN? Why would I ever need this?
A:
Let's say you create a model called Entry. IE an extremely simple blog. You write a view to show all the entries on the front page. Now how do you put those entries on the webpage? How do you edit them?
Enter the admin. You register your model with the admin, create a superuser and log in to your running webapp. It's there, with a fully functional interface for creating the entries.
A:
Some of the uses I can think of -
Editing data or Adding data. If you have any sort of data entry tasks, the admin app handles it like a breeze. Django’s admin especially shines when non-technical users need to be able to enter data.
If you have understood above point, then this makes it possible for programmers to work along with designers and content producers!
Permissions - An admin interface can be used to give permissions, create groups with similar permissions, make more than one administrators etc. (i.e. if you have a login kinda site).
Inspecting data models - when I have defined a new model, I call it up in the admin and enter some dummy data.
Managing acquired data - basically what a moderator does in case of auto-generated content sites.
Block out buggy features - Also if you tweak it a little, you can create an interface wherein say some new feature you coded is buggy. You could disable it from admin interface.
Think of the power this gives in a big organization where everyone need not know programming.
| What are the best uses for the Django Admin app? | On the website, it says this:
One of the most powerful parts of
Django is the automatic admin
interface. It reads metadata in your
model to provide a powerful and
production-ready interface that
content producers can immediately use
to start adding content to the site.
In this document, we discuss how to
activate, use and customize Django’s
admin interface.admin interface.
So what? I still don't understand what the Admin interface is used for. Is it like a PHPMYADMIN? Why would I ever need this?
| [
"Let's say you create a model called Entry. IE an extremely simple blog. You write a view to show all the entries on the front page. Now how do you put those entries on the webpage? How do you edit them?\nEnter the admin. You register your model with the admin, create a superuser and log in to your running webapp. ... | [
2,
1
] | [] | [] | [
"admin",
"django",
"python"
] | stackoverflow_0004131120_admin_django_python.txt |
Q:
Handling and securing server functions in an ajax request..python
Hi I am trying to secure a server function being used for an Ajax request, so that the function is not accessed for any sort of malicious activity. I have done the following till now:-
I am checking whether a valid session is present while the function is being called.
I am using POST rather than GET
I look for specific headers by using request.is_xhr else I induce a redirect.
I have compressed the javascript using dojo shrinksafe(..i am using dojo..)
What else can and should be done here. Need your expert advice on this.
(NB-I am using Flask and Dojo)
A:
No any special secure actions required. Consider ajax request as any other client request.
| Handling and securing server functions in an ajax request..python | Hi I am trying to secure a server function being used for an Ajax request, so that the function is not accessed for any sort of malicious activity. I have done the following till now:-
I am checking whether a valid session is present while the function is being called.
I am using POST rather than GET
I look for specific headers by using request.is_xhr else I induce a redirect.
I have compressed the javascript using dojo shrinksafe(..i am using dojo..)
What else can and should be done here. Need your expert advice on this.
(NB-I am using Flask and Dojo)
| [
"No any special secure actions required. Consider ajax request as any other client request.\n"
] | [
2
] | [] | [] | [
"ajax",
"dojo",
"flask",
"python"
] | stackoverflow_0004131327_ajax_dojo_flask_python.txt |
Q:
boolean 'and' in Python
Can somebody explain the reasoning behind the following tests ??
>>> 1 and True
True
>>> {'foo': 'Foo'} and True
True
>>> {} and True
{}
>>>
A:
Python doesn't have a boolean and or boolean or. Its and and or operators are coalescing, which means that they return the first non-true or true operand, or the second operand.
A:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
For further reference read more on Boolean operations: http://docs.python.org/reference/expressions.html#boolean-operations
| boolean 'and' in Python | Can somebody explain the reasoning behind the following tests ??
>>> 1 and True
True
>>> {'foo': 'Foo'} and True
True
>>> {} and True
{}
>>>
| [
"Python doesn't have a boolean and or boolean or. Its and and or operators are coalescing, which means that they return the first non-true or true operand, or the second operand.\n",
"In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are inte... | [
8,
5
] | [] | [] | [
"boolean",
"python"
] | stackoverflow_0004131468_boolean_python.txt |
Q:
python_select with fink-installed python?
How do I use python_select with fink installed python? It won't find it and I don't want to go through the whole process of installing python using macports. I got python_select from macports though. It reports:
Available versions:
current none python26-apple
I used fink to install python in:
/sw/bin/python2.7
A:
I see the following in my machine:
Available versions:
current none python26 python26-apple
I guess it is looking up the python versions that are available in path. Since, MacPorts go to /opt; Fink goes to /sw. Is fink on your path? What is contained in $PATH.
I would suggest that you use macports. python_select works well with macports installation.
See the following discussion and the suggestion is to use macports:
https://serverfault.com/questions/12952/macports-vs-fink.
I personally use macports.
sudo port install python27
sudo port install python_select
sudo python_select python27
| python_select with fink-installed python? | How do I use python_select with fink installed python? It won't find it and I don't want to go through the whole process of installing python using macports. I got python_select from macports though. It reports:
Available versions:
current none python26-apple
I used fink to install python in:
/sw/bin/python2.7
| [
"I see the following in my machine:\nAvailable versions:\ncurrent none python26 python26-apple\n\nI guess it is looking up the python versions that are available in path. Since, MacPorts go to /opt; Fink goes to /sw. Is fink on your path? What is contained in $PATH.\n\nI would suggest that you use macports. python_... | [
1
] | [] | [] | [
"fink",
"python"
] | stackoverflow_0004131016_fink_python.txt |
Q:
What version of Python should I use if I'm a new to Python?
I am now on the road to learn Python (not the first time I wanted to get this done) now I am standing in front of a decision which I am not able to make so easily
Which Version should I use?!
I found that question was asked about a year ago and Python 2.6 was chosen (more or less) now whats the status quo now ?!
I am running my home and business environment mixed with Windows (XP, 7, 2003, 2008), Linux (Ubuntu Intel & PPC) and Mac OS X (PPC & Intel) Environments and my first approach is to learn the language by creating few scripts to help me do my job as a network administrator and server administrator.
Thanks for your help, by the way I am not new in programming.
A:
For writing admin scripts, I would recommend the current Python 3.x variant and http://diveintopython3.org. As you already know how to program, you will pick up the differences between 3.x and 2.x rather easily in case you should need a 2.x-only library.
For your purposes, the major difference between 2.x and 3.x are likely print being a function (3.x) vs. a special command (2.x) and strings that are always unicode (3.x) vs. special unicode-strings (2.x).
A:
for real projects: 2 (many libs are incompatible with 3), for small scripts and learning: 3.
A:
I'd favour 2.7 at the moment.
There are more libraries available for 2.7, and new features are still being added.
A:
It's still Python 2.x, but 2.7 should serve your needs now. Python 3 is still some way off comprehensive support from the universe of tools, libraries and frameworks.
A:
I'm new to Python as well...for what i've read, 2.7 is the one, but i had to downgrade to 2.5 to be able to use Google App Engine's SDK.
| What version of Python should I use if I'm a new to Python? | I am now on the road to learn Python (not the first time I wanted to get this done) now I am standing in front of a decision which I am not able to make so easily
Which Version should I use?!
I found that question was asked about a year ago and Python 2.6 was chosen (more or less) now whats the status quo now ?!
I am running my home and business environment mixed with Windows (XP, 7, 2003, 2008), Linux (Ubuntu Intel & PPC) and Mac OS X (PPC & Intel) Environments and my first approach is to learn the language by creating few scripts to help me do my job as a network administrator and server administrator.
Thanks for your help, by the way I am not new in programming.
| [
"For writing admin scripts, I would recommend the current Python 3.x variant and http://diveintopython3.org. As you already know how to program, you will pick up the differences between 3.x and 2.x rather easily in case you should need a 2.x-only library.\nFor your purposes, the major difference between 2.x and 3.x... | [
4,
3,
1,
0,
0
] | [] | [] | [
"linux",
"macos",
"python",
"windows"
] | stackoverflow_0004131648_linux_macos_python_windows.txt |
Q:
Persistent objects and __repr__
What would be the best way to handle the __repr__() function for an object that is made persistent? For example, one that is representing a row in a database (relational or object).
According to Python docs, __repr__() should return a string that would re-create the object with eval() such that (roughly) eval(repr(obj)) == obj, or bracket notation for inexact representations. Usually this would mean dumping all the data that can't be regenerated by the object into the string. However, for persistent objects recreating the object could be as simple as retrieving the data from the database.
So, for such objects then, all object data or just the primary key in the __repr__() string?
A:
repr should return a string that would
re-create the object with eval
That is legal for simple types like int or string or float, but not usable for multi-column DB object with say 15+ columns
For example if I had a class representing price, it would be reasonable to make the __repr__ show the main characteristics of it: amount and currency
def __repr__(self):
return '%s %s'%(self.amount,self.currency)
A:
How to get it from the database is generally uninteresting. Return the way to recreate the object from scratch, e.g. SomeModel(field1, field2, ...).
| Persistent objects and __repr__ | What would be the best way to handle the __repr__() function for an object that is made persistent? For example, one that is representing a row in a database (relational or object).
According to Python docs, __repr__() should return a string that would re-create the object with eval() such that (roughly) eval(repr(obj)) == obj, or bracket notation for inexact representations. Usually this would mean dumping all the data that can't be regenerated by the object into the string. However, for persistent objects recreating the object could be as simple as retrieving the data from the database.
So, for such objects then, all object data or just the primary key in the __repr__() string?
| [
"\nrepr should return a string that would\n re-create the object with eval\n\nThat is legal for simple types like int or string or float, but not usable for multi-column DB object with say 15+ columns\nFor example if I had a class representing price, it would be reasonable to make the __repr__ show the main charac... | [
1,
0
] | [] | [] | [
"persistence",
"python",
"repr"
] | stackoverflow_0004131768_persistence_python_repr.txt |
Q:
How upload folder by FTP using cURL?
I need to create FTP-uploader, i am using pycurl and python, but i dont know how to make folder with cURL on ftp's host. Help me please.
A:
You can use the curl option while uploading a file : --ftp-create-dirs
http://curl.haxx.se/docs/manpage.html#--ftp-create-dirs
Ex:
curl --ftp-create-dirs -T uploadfilename -u username:password ftp://sitename.com/directory/myfile
| How upload folder by FTP using cURL? | I need to create FTP-uploader, i am using pycurl and python, but i dont know how to make folder with cURL on ftp's host. Help me please.
| [
"You can use the curl option while uploading a file : --ftp-create-dirs\n\nhttp://curl.haxx.se/docs/manpage.html#--ftp-create-dirs\n\nEx: \ncurl --ftp-create-dirs -T uploadfilename -u username:password ftp://sitename.com/directory/myfile\n\n"
] | [
17
] | [] | [] | [
"curl",
"ftp",
"pycurl",
"python"
] | stackoverflow_0004131782_curl_ftp_pycurl_python.txt |
Q:
Filter models by ManyToMany relationship with Django User
Given this model:
from django.db import models
from django.contrib.auth.admin import User
# Create your models here.
class Plan(models.Model):
editors = models.ManyToManyField(User)
in which every plan can have more than one editor (User), how can I retrieve all plans for which a particular user is one of the editors?
Something like this?
Plan.objects.filter(editors__contains(request.user))
?
A:
You just use the normal equals here.
Plan.objects.filter(editors=request.user)
| Filter models by ManyToMany relationship with Django User | Given this model:
from django.db import models
from django.contrib.auth.admin import User
# Create your models here.
class Plan(models.Model):
editors = models.ManyToManyField(User)
in which every plan can have more than one editor (User), how can I retrieve all plans for which a particular user is one of the editors?
Something like this?
Plan.objects.filter(editors__contains(request.user))
?
| [
"You just use the normal equals here.\nPlan.objects.filter(editors=request.user)\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004131836_django_python.txt |
Q:
Regex to find out fields which are having non ascii character in python
i have data of thousand records which i read line by line . Each line has some fields and their value but field names contain a non ascii character, below is the example of such a record :
| | | X:720 | N°227: Done
where X and N°(non ascii character) are fieldnames and 720,227 and "Done" are field values which i have to extract.
These fields are optional which may exist or may not .
Now I have to check whether these fields exist in line or not and if it exists then what is its value(for example X field is having value 720 and N° is having value 227 and "Done")
Please let me know how to do this using regex in python ,is there any another way to do this in python?
A:
Sometimes regex is good for such thing, sometimes split() and other string method will be easier. It is up to you to chose:
#!/usr/bin/env python
# -*- coding: utf8 -*-
import re
RE_TXT = re.compile(r'\|\s*X:(\S+)\s*\|\s*N\D*(\d+):\s*(.*)$')
txt = '| | | X:720 | N°227: Done'
rx = RE_TXT.search(txt)
if rx:
print(rx.group(1))
print(rx.group(2))
print(rx.group(3))
print('-' * 20)
# other way without regex, but with more complicated logic:
arr = [s.strip() for s in txt.split('|')]
if arr[3].startswith('X:'):
print(arr[3].split(':')[1])
N, state = arr[4].split(':')
N = N[3:]
state = state.strip()
print(N)
print(state)
As for regexp:
\s* is zero or more white characters
\S+ is one or more non white character
\d is for digits
\D is for non digits
. means any character
r before string means "raw" string so you do not need to escape backslash
| Regex to find out fields which are having non ascii character in python | i have data of thousand records which i read line by line . Each line has some fields and their value but field names contain a non ascii character, below is the example of such a record :
| | | X:720 | N°227: Done
where X and N°(non ascii character) are fieldnames and 720,227 and "Done" are field values which i have to extract.
These fields are optional which may exist or may not .
Now I have to check whether these fields exist in line or not and if it exists then what is its value(for example X field is having value 720 and N° is having value 227 and "Done")
Please let me know how to do this using regex in python ,is there any another way to do this in python?
| [
"Sometimes regex is good for such thing, sometimes split() and other string method will be easier. It is up to you to chose:\n#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport re\nRE_TXT = re.compile(r'\\|\\s*X:(\\S+)\\s*\\|\\s*N\\D*(\\d+):\\s*(.*)$')\ntxt = '| | | X:720 | ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004131632_python.txt |
Q:
How to avoid a seemingly unavoidable divide by zero
Ok, so I'm doing the power method in python.
Basically, the equation revolves around multiplying a matrix A by a vector (y) like this:
for i in range(0, 100):
y = mult(matrix,y)
y = scalarMult(y, 1.0/y[0][0])
Then you multiply the vector y by 1/(the first element in y). Now, if the matrix is sparse or has a zero in just the right spot, you will get a zero for the first element in a. None of my googling skills have yielded a modification to the power method to avoid this.
For those interested, I'm trying to solve for the eigenvalues of a matrix; and my code works as long as there aren't too many zeros.
A:
Instead of dividing by first element of the vector you can divide by one of its norms.
For example if you use second norm, the length of the vector will always be 1.
norm = sum(e**2 for e in y)**0.5
Norm of the vector is only zero when vector is 0 (has all elements 0), so division by 0 should not happen.
| How to avoid a seemingly unavoidable divide by zero | Ok, so I'm doing the power method in python.
Basically, the equation revolves around multiplying a matrix A by a vector (y) like this:
for i in range(0, 100):
y = mult(matrix,y)
y = scalarMult(y, 1.0/y[0][0])
Then you multiply the vector y by 1/(the first element in y). Now, if the matrix is sparse or has a zero in just the right spot, you will get a zero for the first element in a. None of my googling skills have yielded a modification to the power method to avoid this.
For those interested, I'm trying to solve for the eigenvalues of a matrix; and my code works as long as there aren't too many zeros.
| [
"Instead of dividing by first element of the vector you can divide by one of its norms. \nFor example if you use second norm, the length of the vector will always be 1. \nnorm = sum(e**2 for e in y)**0.5\n\nNorm of the vector is only zero when vector is 0 (has all elements 0), so division by 0 should not happen. \n... | [
3
] | [] | [] | [
"math",
"python"
] | stackoverflow_0004131809_math_python.txt |
Q:
Python threading, queuing, asyncing... What does it all mean?
I've been experimenting with threading recently in Python and was curious when to use what.
For example, when should I use multithreading over multiprocessing? What would be a scenario when I should be using asynchronous IO rather than threading?
I mostly understand what each does (I think) but I can't see any benefits/downsides of using one over the other.
What should I use if I was creating a small HTTP server?
What should I use if I was creating a small HTTP client?
This baffles me...
A:
What you want talk about is not specific to python only it's about multiprocessing vs threading in general i think you can find in google lot of argument from the two side the ones that prefer threading and the others that prefer multiprocessing.
But for python multi-threading is limited (if you're using CPython) by the GIL (Global Interpreter Lock), so most python programmer prefer using the multiprocessing over the threading (it's Guido recommendation)
Nevertheless, you re right the GIL is
not as bad as you would initially
think: you just have to undo the
brainwashing you got from Windows and
Java proponents who seem to consider
threads as the only way to approach
concurrent activities, Guido van Rossum.
you can find here some more info
A:
Python multiprocessing makes sense when you have a machine with multiple cores and/or CPUs. The main difference between using threads and processes is that processes do not share an address space, and thus one process cannot easily access the data of another process. That is why the multiprocessing module provides managers and queues and stuff like that.
The issue with threading is Pythons Global Interpreter Lock, which seriously messes with multithreaded applications.
Asynchronous IO is useful when you have long running IO operations (read large file, wait for response from network) and do not want your application to block. Many operating systems offer built-in implementations of that.
So, for your server you would probably use multiprocessing or multithreading, and for your client async IO is more fitting.
| Python threading, queuing, asyncing... What does it all mean? | I've been experimenting with threading recently in Python and was curious when to use what.
For example, when should I use multithreading over multiprocessing? What would be a scenario when I should be using asynchronous IO rather than threading?
I mostly understand what each does (I think) but I can't see any benefits/downsides of using one over the other.
What should I use if I was creating a small HTTP server?
What should I use if I was creating a small HTTP client?
This baffles me...
| [
"What you want talk about is not specific to python only it's about multiprocessing vs threading in general i think you can find in google lot of argument from the two side the ones that prefer threading and the others that prefer multiprocessing.\nBut for python multi-threading is limited (if you're using CPython)... | [
2,
0
] | [] | [] | [
"asynchronous",
"multiprocessing",
"multithreading",
"python"
] | stackoverflow_0004132179_asynchronous_multiprocessing_multithreading_python.txt |
Q:
How to use thread in Django
I want to check users' subscribed dates for certain period. And send mail to users whose subscription is finishing (ex. reminds two days).
I think the best way is using thread and timer to check dates. But I have no idea how to call this function. I don't want to make a separate program or shell. I want to combine this procedure to my django code. I tried to call this function in my settings.py file. But it seems it is not a good idea. It calls the function and creates thread every time I imported settings.
A:
That's case for manage.py command called periodically from cron. Oficial doc about creating those commands. Here bit more helpful.
If you want something simpler then django-command-extensions has commands for managing django jobs.
A:
if you need more then only this one asynchronous job have a look at celery.
A:
using Django-cron is much easier and simple
EDIT: Added a tip
from django_cron import cronScheduler, Job
class sendMail(Job):
# period run every 300 seconds (5 minutes)
run_every = 300
def job(self):
# This will be executed every 5 minutes
datatuple = check_subscription_finishing()
send_mass_mail(datatuple)
//and just register it
cronScheduler.register(sendMail)
| How to use thread in Django | I want to check users' subscribed dates for certain period. And send mail to users whose subscription is finishing (ex. reminds two days).
I think the best way is using thread and timer to check dates. But I have no idea how to call this function. I don't want to make a separate program or shell. I want to combine this procedure to my django code. I tried to call this function in my settings.py file. But it seems it is not a good idea. It calls the function and creates thread every time I imported settings.
| [
"That's case for manage.py command called periodically from cron. Oficial doc about creating those commands. Here bit more helpful.\nIf you want something simpler then django-command-extensions has commands for managing django jobs.\n",
"if you need more then only this one asynchronous job have a look at celery.\... | [
3,
2,
1
] | [] | [] | [
"django",
"multithreading",
"python"
] | stackoverflow_0002583567_django_multithreading_python.txt |
Q:
Python based build tools
I've been lately looking at build systems and I can't find anything close to what I want. I consider too low end, I don't like the syntax of bjam and CMake, and I really don't like that they are only for C/C++. Ant and NAnt are also too language oriented.
I really like the idea of a build tool that uses a real programming language and Python fits in really nice. I've been looking at Scons and waf, and from these 2 I find waf as the closest one to what I want, but still I see a lot of work that has to be done to support everything planned, when I should focus on coding.
Here is what I want:
includes and libraries (for C/ C++, Java, C#, Python)
I want to use different versions of compilers and support different target OS and CPU architectures:
for C / C++: MSVC, gcc(cygwin, mingw, linux version), llvm-gcc, DragonEgg, Clang
for C#: .Net compiler, Mono (for windows and linux) - all of these for different .Net versions (like NAnt's: 'net-2.0', 'net-3.5', 'net-4.0', 'mono-2.0', 'mono-3.5' ...)
I want to use SWIG to support wrapper generation for C#, Python, Lua, Java etc.
I want more then just Debug and Release configurations - just like Visual Studio supports this really easily. Example: shared library project built MSVC for C# wrapping, and built with mingw for Python wrapping, different versions of release versions - with non-optimized, fully optimized, production, obfuscated ...
I want it to consider project tracking. Explained: if I have a shared library project using SWIG, and a different C# project that loads that SWIG wrapping, building this solution/environment/workspace would imply copying the resulting shared library, copying other shared libraries that that shared library uses in the working directory, and the C# generated wrappers to the C# project, and then build the C# project
Nice-to-have: deployment on other machines for network testing
Nice-to-have: I don't really care for IDE project file generation (e.g. like CMake does for Visual Studio), because IDEs versions and compatibily change, and there are a ton of nice IDEs out there (e.g. for C/C++ CodeBlocks, CodeLite, Eclipse CDT - all of these are portable on thumb drive, VS is not), but Nice-to-have would be makefile integration - a makefile that that simply calls this Build tool's own makefile/script - seen something similar for Scons
Looking over what I wrote I think I asked too much :), but I think this will serve more then me
edit: forgot to say, but I think it is implied from the use of Python: I want the tool to be cross-platform
edit: perhaps what I am looking for isn't implemented yet, but it might exits a waf extension to all of this, or Scons maybe
A:
I used Scons and it is good and you can really do everything with it because just Python code so what missing you write in Python - it is easy.
Some say it has problem with very big projects, I didn't have very big projects to run it so I don't know.
| Python based build tools | I've been lately looking at build systems and I can't find anything close to what I want. I consider too low end, I don't like the syntax of bjam and CMake, and I really don't like that they are only for C/C++. Ant and NAnt are also too language oriented.
I really like the idea of a build tool that uses a real programming language and Python fits in really nice. I've been looking at Scons and waf, and from these 2 I find waf as the closest one to what I want, but still I see a lot of work that has to be done to support everything planned, when I should focus on coding.
Here is what I want:
includes and libraries (for C/ C++, Java, C#, Python)
I want to use different versions of compilers and support different target OS and CPU architectures:
for C / C++: MSVC, gcc(cygwin, mingw, linux version), llvm-gcc, DragonEgg, Clang
for C#: .Net compiler, Mono (for windows and linux) - all of these for different .Net versions (like NAnt's: 'net-2.0', 'net-3.5', 'net-4.0', 'mono-2.0', 'mono-3.5' ...)
I want to use SWIG to support wrapper generation for C#, Python, Lua, Java etc.
I want more then just Debug and Release configurations - just like Visual Studio supports this really easily. Example: shared library project built MSVC for C# wrapping, and built with mingw for Python wrapping, different versions of release versions - with non-optimized, fully optimized, production, obfuscated ...
I want it to consider project tracking. Explained: if I have a shared library project using SWIG, and a different C# project that loads that SWIG wrapping, building this solution/environment/workspace would imply copying the resulting shared library, copying other shared libraries that that shared library uses in the working directory, and the C# generated wrappers to the C# project, and then build the C# project
Nice-to-have: deployment on other machines for network testing
Nice-to-have: I don't really care for IDE project file generation (e.g. like CMake does for Visual Studio), because IDEs versions and compatibily change, and there are a ton of nice IDEs out there (e.g. for C/C++ CodeBlocks, CodeLite, Eclipse CDT - all of these are portable on thumb drive, VS is not), but Nice-to-have would be makefile integration - a makefile that that simply calls this Build tool's own makefile/script - seen something similar for Scons
Looking over what I wrote I think I asked too much :), but I think this will serve more then me
edit: forgot to say, but I think it is implied from the use of Python: I want the tool to be cross-platform
edit: perhaps what I am looking for isn't implemented yet, but it might exits a waf extension to all of this, or Scons maybe
| [
"I used Scons and it is good and you can really do everything with it because just Python code so what missing you write in Python - it is easy.\nSome say it has problem with very big projects, I didn't have very big projects to run it so I don't know.\n"
] | [
3
] | [] | [] | [
"build",
"build_process",
"c++",
"makefile",
"python"
] | stackoverflow_0004132066_build_build_process_c++_makefile_python.txt |
Q:
Python: Replace function to edit files
I have a results.txt file which looks like this:
[["12 - 22 - 30 - 31 - 34 - 39 - 36"],
["13 - 21 - 28 - 37 - 39 - 45 - 6"],
["2 - 22 - 32 - 33 - 37 - 45 - 11"],
["3 - 5 - 11 - 16 - 41 - 48 - 32"],
["2 - 3 - 14 - 29 - 35 - 42 12"],
["14 - 30 - 31 - 36 - 44 - 47 26"]]
I want to replace the " - " in the results.txt file with '","' so it looks for like a python list.
I try to used the code below, but the output looks exactly like the results.txt
output = open("results2.txt", 'w')
f = open("results.txt", 'r')
read = f.readlines()
for i in read:
i.replace(" - ",'","')
output.write(i)
A:
for i in read:
# the string.replace() function don't do the change at place
# it's return a new string with the new changes.
a = i.replace(" - ",",")
output.write(a)
A:
String methods return a new string. Write that out instead.
output.write(i.replace(" - ",","))
A:
i.replace(" - ",'","') doesn't change i (remember strings are immutable) so you should use
i = i.replace(" - ",'","')
If the file isn't very big ( I am guessing - since you are reading it all into memory at once with readlines() anyway), you can just do the whole file at once
output = open("results2.txt", 'w')
f = open("results.txt", 'r')
output.write(f.read().replace(" - ".'","'))
f.close()
output.close()
| Python: Replace function to edit files | I have a results.txt file which looks like this:
[["12 - 22 - 30 - 31 - 34 - 39 - 36"],
["13 - 21 - 28 - 37 - 39 - 45 - 6"],
["2 - 22 - 32 - 33 - 37 - 45 - 11"],
["3 - 5 - 11 - 16 - 41 - 48 - 32"],
["2 - 3 - 14 - 29 - 35 - 42 12"],
["14 - 30 - 31 - 36 - 44 - 47 26"]]
I want to replace the " - " in the results.txt file with '","' so it looks for like a python list.
I try to used the code below, but the output looks exactly like the results.txt
output = open("results2.txt", 'w')
f = open("results.txt", 'r')
read = f.readlines()
for i in read:
i.replace(" - ",'","')
output.write(i)
| [
"for i in read:\n # the string.replace() function don't do the change at place\n # it's return a new string with the new changes.\n a = i.replace(\" - \",\",\") \n output.write(a)\n\n",
"String methods return a new string. Write that out instead.\noutput.write(i.replace(\" - \",\",\"))\n\n",
"i.rep... | [
6,
5,
4
] | [] | [] | [
"file",
"python",
"replace"
] | stackoverflow_0004132715_file_python_replace.txt |
Q:
Is there 64-bit version pymongo?
When i install pymongo using easy_install with 64-bit python, exception happens. But it works with 32-bit python. It seems only 32-bit python is supported.
So i want to know whether 64-bit pymongo exists?
Thanks.
--- more details ---
running install
running bdist_egg
running egg_info
writing pymongo.egg-info\PKG-INFO
writing top-level names to pymongo.egg-info\top_level.txt
writing dependency_links to pymongo.egg-info\dependency_links.txt
reading manifest file 'pymongo.egg-info\SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching '*.h' under directory 'pymongo'
writing manifest file 'pymongo.egg-info\SOURCES.txt'
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
running build_ext
building 'bson._cbson' extension
Traceback (most recent call last):
File "F:\mongodb-mongo-python-driver-7269ec4\setup.py", line 184, in <module>
"doc": doc})
File "C:\Python26\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python26\lib\distutils\dist.py", line 975, in run_commands
self.run_command(cmd)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "build\bdist.win-amd64\egg\setuptools\command\install.py", line 76, in ru
n
File "build\bdist.win-amd64\egg\setuptools\command\install.py", line 96, in do
_egg_install
File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command
self.distribution.run_command(command)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "build\bdist.win-amd64\egg\setuptools\command\bdist_egg.py", line 175, in
run
File "build\bdist.win-amd64\egg\setuptools\command\bdist_egg.py", line 161, in
call_command
File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command
self.distribution.run_command(command)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "build\bdist.win-amd64\egg\setuptools\command\install_lib.py", line 20, i
n run
File "C:\Python26\lib\distutils\command\install_lib.py", line 112, in build
self.run_command('build_ext')
File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command
self.distribution.run_command(command)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "F:\mongodb-mongo-python-driver-7269ec4\setup.py", line 108, in run
build_ext.run(self)
File "C:\Python26\lib\distutils\command\build_ext.py", line 345, in run
self.build_extensions()
File "C:\Python26\lib\distutils\command\build_ext.py", line 471, in build_exte
nsions
self.build_extension(ext)
File "F:\mongodb-mongo-python-driver-7269ec4\setup.py", line 118, in build_ext
ension
build_ext.build_extension(self, ext)
File "C:\Python26\lib\distutils\command\build_ext.py", line 536, in build_exte
nsion
depends=ext.depends)
File "C:\Python26\lib\distutils\msvc9compiler.py", line 448, in compile
self.initialize()
File "C:\Python26\lib\distutils\msvc9compiler.py", line 358, in initialize
vc_env = query_vcvarsall(VERSION, plat_spec)
File "C:\Python26\lib\distutils\msvc9compiler.py", line 274, in query_vcvarsal
l
raise ValueError(str(list(result.keys())))
ValueError: [u'path']
A:
Run vcvarsall.bat first, then install pymongo.
| Is there 64-bit version pymongo? | When i install pymongo using easy_install with 64-bit python, exception happens. But it works with 32-bit python. It seems only 32-bit python is supported.
So i want to know whether 64-bit pymongo exists?
Thanks.
--- more details ---
running install
running bdist_egg
running egg_info
writing pymongo.egg-info\PKG-INFO
writing top-level names to pymongo.egg-info\top_level.txt
writing dependency_links to pymongo.egg-info\dependency_links.txt
reading manifest file 'pymongo.egg-info\SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching '*.h' under directory 'pymongo'
writing manifest file 'pymongo.egg-info\SOURCES.txt'
installing library code to build\bdist.win-amd64\egg
running install_lib
running build_py
running build_ext
building 'bson._cbson' extension
Traceback (most recent call last):
File "F:\mongodb-mongo-python-driver-7269ec4\setup.py", line 184, in <module>
"doc": doc})
File "C:\Python26\lib\distutils\core.py", line 152, in setup
dist.run_commands()
File "C:\Python26\lib\distutils\dist.py", line 975, in run_commands
self.run_command(cmd)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "build\bdist.win-amd64\egg\setuptools\command\install.py", line 76, in ru
n
File "build\bdist.win-amd64\egg\setuptools\command\install.py", line 96, in do
_egg_install
File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command
self.distribution.run_command(command)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "build\bdist.win-amd64\egg\setuptools\command\bdist_egg.py", line 175, in
run
File "build\bdist.win-amd64\egg\setuptools\command\bdist_egg.py", line 161, in
call_command
File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command
self.distribution.run_command(command)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "build\bdist.win-amd64\egg\setuptools\command\install_lib.py", line 20, i
n run
File "C:\Python26\lib\distutils\command\install_lib.py", line 112, in build
self.run_command('build_ext')
File "C:\Python26\lib\distutils\cmd.py", line 333, in run_command
self.distribution.run_command(command)
File "C:\Python26\lib\distutils\dist.py", line 995, in run_command
cmd_obj.run()
File "F:\mongodb-mongo-python-driver-7269ec4\setup.py", line 108, in run
build_ext.run(self)
File "C:\Python26\lib\distutils\command\build_ext.py", line 345, in run
self.build_extensions()
File "C:\Python26\lib\distutils\command\build_ext.py", line 471, in build_exte
nsions
self.build_extension(ext)
File "F:\mongodb-mongo-python-driver-7269ec4\setup.py", line 118, in build_ext
ension
build_ext.build_extension(self, ext)
File "C:\Python26\lib\distutils\command\build_ext.py", line 536, in build_exte
nsion
depends=ext.depends)
File "C:\Python26\lib\distutils\msvc9compiler.py", line 448, in compile
self.initialize()
File "C:\Python26\lib\distutils\msvc9compiler.py", line 358, in initialize
vc_env = query_vcvarsall(VERSION, plat_spec)
File "C:\Python26\lib\distutils\msvc9compiler.py", line 274, in query_vcvarsal
l
raise ValueError(str(list(result.keys())))
ValueError: [u'path']
| [
"Run vcvarsall.bat first, then install pymongo.\n"
] | [
0
] | [] | [] | [
"mongodb",
"pymongo",
"python"
] | stackoverflow_0004132500_mongodb_pymongo_python.txt |
Q:
python service restart (when compiled to exe)
I have a service, as follows:
"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""
import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__
__builtin__.theService = None
class HelloWorld:
""" Sample request handler class. """
def __init__(self):
self.iVal = 0
@cherrypy.expose
def index(self):
try:
self.iVal += 1
if self.iVal == 5:
sys.exit()
return "Hello world! " + str(self.iVal)
except SystemExit:
StopServiceError(__builtin__.theService)
class MyService(win32serviceutil.ServiceFramework):
"""NT Service."""
_svc_name_ = "CherryPyService"
_svc_display_name_ = "CherryPy Service"
_svc_description_ = "Some description for this service"
def SvcDoRun(self):
__builtin__.theService = self
StartService()
def SvcStop(self):
StopService(__builtin__.theService)
def StartService():
cherrypy.tree.mount(HelloWorld(), '/')
cherrypy.config.update({
'global':{
'tools.log_tracebacks.on': True,
'log.error_file': '\\Error_File.txt',
'log.screen': True,
'engine.autoreload.on': False,
'engine.SIGHUP': None,
'engine.SIGTERM': None
}
})
cherrypy.engine.start()
cherrypy.engine.block()
def StopService(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(win32service.SERVICE_STOPPED)
def StopServiceError(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(serviceStatus=win32service.SERVICE_STOPPED, win32ExitCode=1, svcExitCode=1)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
I want windows to restart the service when the sys.ext() cause the service to exit. Does anyone know how to make it do this?
A:
A non programming-related option:
A windows service can be configured for recovery. Select the recovery tag of the service properties window. You can select to Restart the Service after the first, second or subsequent failures.
A simple idea - why don't you drop the sys.exit() call? This way the service just continues to run and you don't have to deal with restarting it. If you really need to know when self.iVal reaches 5, you can report to the event logger (and perhaps reset the counter).
A:
I've had exactly the same issue: trying to make a Python-based service exit with an error code so that the services framework can restart it. I tried the approach with ReportServiceStatus(win32service.SERVICE_STOP_PENDING, win32ExitCode=1, svcExitCode=1) as well as sys.exit(1) but none of them prompted Windows to restart the service, despite the latter showing up as an error in the event log. I ended up not relying on the services framework and just doing this:
def SvcDoRun(self):
restart_required = run_service() # will return True if the service needs
# to be restarted
if restart_required:
subprocess.Popen('sleep 5 & sc start %s' % self._svc_name_, shell=True)
| python service restart (when compiled to exe) | I have a service, as follows:
"""
The most basic (working) CherryPy 3.1 Windows service possible.
Requires Mark Hammond's pywin32 package.
"""
import cherrypy
import win32serviceutil
import win32service
import sys
import __builtin__
__builtin__.theService = None
class HelloWorld:
""" Sample request handler class. """
def __init__(self):
self.iVal = 0
@cherrypy.expose
def index(self):
try:
self.iVal += 1
if self.iVal == 5:
sys.exit()
return "Hello world! " + str(self.iVal)
except SystemExit:
StopServiceError(__builtin__.theService)
class MyService(win32serviceutil.ServiceFramework):
"""NT Service."""
_svc_name_ = "CherryPyService"
_svc_display_name_ = "CherryPy Service"
_svc_description_ = "Some description for this service"
def SvcDoRun(self):
__builtin__.theService = self
StartService()
def SvcStop(self):
StopService(__builtin__.theService)
def StartService():
cherrypy.tree.mount(HelloWorld(), '/')
cherrypy.config.update({
'global':{
'tools.log_tracebacks.on': True,
'log.error_file': '\\Error_File.txt',
'log.screen': True,
'engine.autoreload.on': False,
'engine.SIGHUP': None,
'engine.SIGTERM': None
}
})
cherrypy.engine.start()
cherrypy.engine.block()
def StopService(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(win32service.SERVICE_STOPPED)
def StopServiceError(classObject):
classObject.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
cherrypy.engine.exit()
classObject.ReportServiceStatus(serviceStatus=win32service.SERVICE_STOPPED, win32ExitCode=1, svcExitCode=1)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(MyService)
I want windows to restart the service when the sys.ext() cause the service to exit. Does anyone know how to make it do this?
| [
"A non programming-related option:\nA windows service can be configured for recovery. Select the recovery tag of the service properties window. You can select to Restart the Service after the first, second or subsequent failures.\nA simple idea - why don't you drop the sys.exit() call? This way the service just con... | [
4,
2
] | [] | [] | [
"python",
"restart",
"windows_services"
] | stackoverflow_0001031705_python_restart_windows_services.txt |
Q:
Excel Vlookup in Python
How do I implement the Excel VLOOKUP worksheet function in Python. Any idea?
A:
If you are using xlrd to read your Excel XLS file:
Get the key column values that need to be searched on:
key_values = sheet.col_values(KEY_COLX, start_rowx=START_ROWX, end_rowx=END_ROWX)
# UPPER_CASE variables (KEY_COLX etc) are part of your problem description.
Search those values to find what you are looking for:
# example here is exact match
try:
found_offset = key_values.index(QUERY_VALUE)
except IndexError:
# not found
# do something else
Then you pick out the data cell you want e.g.
sheet.cell(START_ROWX + found_offset, KEY_COLX + DATA_OFFSET)
Not using xlrd? See here.
| Excel Vlookup in Python | How do I implement the Excel VLOOKUP worksheet function in Python. Any idea?
| [
"If you are using xlrd to read your Excel XLS file:\nGet the key column values that need to be searched on:\nkey_values = sheet.col_values(KEY_COLX, start_rowx=START_ROWX, end_rowx=END_ROWX)\n# UPPER_CASE variables (KEY_COLX etc) are part of your problem description.\nSearch those values to find what you are lookin... | [
2
] | [] | [] | [
"excel",
"python"
] | stackoverflow_0004132060_excel_python.txt |
Q:
Where are some good places to reach great Django developers?
Are there communities where expert Django developers (ideally looking for jobs) like to hang out? Stackoverflow excluded :)
A:
I'm partial to the #django channel on Freenode's IRC server. A few big names in the Django community hang around there. ( irc://irc.freenode.net/#django since SO's Markdown processor doesn't like irc:// in URLs)
A:
You can checkout djangogigs. And hang out on #django and #django-dev on freenode.
A:
http://djangopeople.net/
| Where are some good places to reach great Django developers? | Are there communities where expert Django developers (ideally looking for jobs) like to hang out? Stackoverflow excluded :)
| [
"I'm partial to the #django channel on Freenode's IRC server. A few big names in the Django community hang around there. ( irc://irc.freenode.net/#django since SO's Markdown processor doesn't like irc:// in URLs)\n",
"You can checkout djangogigs. And hang out on #django and #django-dev on freenode.\n",
"http://... | [
3,
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004131096_django_python.txt |
Q:
How to mix serializers
I need to json serialize loads of data in django, and I need to use both django.utils.simplejson and django.core.serializers. The problem is that I can't mix them. I need something like this:
simplejson.dumps({
'money': money.quantity,
'items_left': item.quantity
'transport': serializers.serialize([transport])
})
While this may work, there still are some problems with it:
I need to use [transport] to serialize just one value. I still can't figure out why the hell couldn't they add support for serializing a single model
response.transport will be a string that would need another json decode
Also, if it helps, I'm using the wadofstuff json serialization module.
How can I make this kind of serialization less hackish?
A:
Use .values() in your query in order to generate a dict instead of a model instance, then just nest that dictionary in the outer dictionary.
| How to mix serializers | I need to json serialize loads of data in django, and I need to use both django.utils.simplejson and django.core.serializers. The problem is that I can't mix them. I need something like this:
simplejson.dumps({
'money': money.quantity,
'items_left': item.quantity
'transport': serializers.serialize([transport])
})
While this may work, there still are some problems with it:
I need to use [transport] to serialize just one value. I still can't figure out why the hell couldn't they add support for serializing a single model
response.transport will be a string that would need another json decode
Also, if it helps, I'm using the wadofstuff json serialization module.
How can I make this kind of serialization less hackish?
| [
"Use .values() in your query in order to generate a dict instead of a model instance, then just nest that dictionary in the outer dictionary.\n"
] | [
1
] | [] | [] | [
"django",
"json",
"python",
"serialization"
] | stackoverflow_0004133600_django_json_python_serialization.txt |
Q:
Massive Python set of integers using too much memory
Setup
Python 2.6
Ubuntu x64
I have a set of unique integers with values between 1 and 50 million. New integers are added at random e.g. numberset.add(random.randint(1, 50000000)). I need to be able to quickly add new integers and quickly check if an integer is already present.
Problem
After a while, the set grows too large for my low memory system and I experience MemoryErrors.
Question
How can I achieve this while using less memory? What's the fastest way to do this using the disk without reconfiguring the system e.g. swapfiles? Should I use a database file like sqlite? Is there a library that will compress the integers in memory?
A:
Use a bit-array.This will reduce the need for huge space requirement.
Realted SO Question:
Python equivalent to Java's BitSet
A:
You can avoid dependencies on 3rd-party bit-array modules by writing your own -- the functionality required is rather minimal:
import array
BITS_PER_ITEM = array.array('I').itemsize * 8
def make_bit_array(num_bits, initially=0):
num_items = (num_bits + BITS_PER_ITEM - 1) // BITS_PER_ITEM
return array.array('I', [initially]) * num_items
def set_bit(bit_array, offset):
item_index = offset // BITS_PER_ITEM
bit_index = offset % BITS_PER_ITEM
bit_array[item_index] |= 1 << bit_index
def clear_bit(bit_array, offset):
item_index = offset // BITS_PER_ITEM
bit_index = offset % BITS_PER_ITEM
bit_array[item_index] &= ~(1 << bit_index)
def get_bit(bit_array, offset):
item_index = offset // BITS_PER_ITEM
bit_index = offset % BITS_PER_ITEM
return (bit_array[item_index] >> bit_index) & 1
A:
Use an array of bits as flags for each integer - the memory needed will be only 50 million bits (about 6 MB). There are a few modules that can help. This example uses bitstring, another option is bitarray:
from bitstring import BitArray
i = BitArray(50000000) # initialise 50 million zero bits
for x in xrange(100):
v = random.randint(1, 50000000)
if not i[v]: # Test if it's already present
i.set(1, v) # Set a single bit
Setting and checking bits is very fast and it uses very little memory.
A:
Try to use array module.
A:
Depending on your requirements, you might also consider a bloom filter. It is a memory-efficient data structure for testing if an element is in a set. The catch is that it it can give false-positives, though it will never give false-negatives.
A:
If integers are unique then use bits. Example: binary 01011111 means that there are: 1, 3, 4, 5, 6 and 7. This way every bit is used to check if its integer index is used (value 1) or not (value 0).
It was described in one chapter of "Programming Pearls" by Jon Bentley (look for "The file contains at most ten million records; each record is a seven-digit integer.")
It seems that there is bitarray module mentioned by Emil that works this way.
| Massive Python set of integers using too much memory | Setup
Python 2.6
Ubuntu x64
I have a set of unique integers with values between 1 and 50 million. New integers are added at random e.g. numberset.add(random.randint(1, 50000000)). I need to be able to quickly add new integers and quickly check if an integer is already present.
Problem
After a while, the set grows too large for my low memory system and I experience MemoryErrors.
Question
How can I achieve this while using less memory? What's the fastest way to do this using the disk without reconfiguring the system e.g. swapfiles? Should I use a database file like sqlite? Is there a library that will compress the integers in memory?
| [
"Use a bit-array.This will reduce the need for huge space requirement.\nRealted SO Question:\n\nPython equivalent to Java's BitSet\n\n",
"You can avoid dependencies on 3rd-party bit-array modules by writing your own -- the functionality required is rather minimal:\nimport array\n\nBITS_PER_ITEM = array.array('I')... | [
5,
5,
2,
1,
1,
0
] | [] | [] | [
"memory_management",
"python",
"set"
] | stackoverflow_0004132207_memory_management_python_set.txt |
Q:
Is there a good NumPy clone for Jython?
I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order to do this quickly, I need a NumPy clone for Jython (or Java). Is there anything like this out there?
A:
I can't find anything that's a clone of numpy, but there's a long list of Java numerics packages here - these should all be usable from Jython. Which one meets your requirements depends on what you're doing with numpy, I guess.
A:
Wilberforce is essentially corrrect.
However, I suggest looking at the Apache Commons Math library -- that would be a better choice for a replacement Java numerics package than any of those listed in wilberforce's answer.
A:
Incanter, a Clojure scientific/statistical computing library, uses the Parallel Colt Java libraries with great success: http://incanter.org/. One route may be to start using the PColt classes in Jython, and slowly build up Python-esque bindings for it, as Incanter provides? (Let me know if you have interest in this.)
A:
There is a build called JNumeric available on sourceforge:
The sourceforge version has not had a release in a long time, but it seems like an updated version for Jython 2.51 is also available (have not tried it myself):
http://bitbucket.org/zornslemon/jnumeric-ra/downloads/
| Is there a good NumPy clone for Jython? | I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order to do this quickly, I need a NumPy clone for Jython (or Java). Is there anything like this out there?
| [
"I can't find anything that's a clone of numpy, but there's a long list of Java numerics packages here - these should all be usable from Jython. Which one meets your requirements depends on what you're doing with numpy, I guess.\n",
"Wilberforce is essentially corrrect. \nHowever, I suggest looking at the Apache ... | [
12,
10,
2,
1
] | [] | [] | [
"java",
"jython",
"numpy",
"python"
] | stackoverflow_0000316410_java_jython_numpy_python.txt |
Q:
Problem getting started with GeoDjango
As soon as I add "from django.contrib.gis.db import models" instead of "from django.db import models", Django stops recognizing the app and gives this error:
Error: App with label location could not be found. Are you sure your INSTALLED_APPS setting is correct?
The error goes away as soon as I comment out "from django.contrib.gis.db import models"...
I have added "django.contrib.gis" and the "location" app to the INSTALLED_APPS setting correctly.
Any clues why this is happening? I am running using Django v1.1.1 final, on my windows laptop.
A:
If you have location on your INSTALLED_APPS and are getting this error, most likely you don't have the location app in your PYTHONPATH.
A:
I had encountered the same issue using Postgres 8.4
Links to psycopg2 and GeoDjango given on GeoDjango installation instructions page rely on Postgres 8.3,
So, if you use Postgres 8.4 you must install appropriate version of psycopg2 from here also GeoDjango installer modifies the system Path environment variable to include C:\Program Files\PostgreSQL\8.3\bin.
In case of Postgres 8.4 you must change Path variable to C:\Program Files\PostgreSQL\8.4\bin.
After performing these modifications all must work fine :)
A:
I was having the same problem after installing Django on Ubuntu 10 using Synaptic Package manager...
Turns out it didn't install the required package "libgdal1". Manually selected it and GeoDjango works fine now.
| Problem getting started with GeoDjango | As soon as I add "from django.contrib.gis.db import models" instead of "from django.db import models", Django stops recognizing the app and gives this error:
Error: App with label location could not be found. Are you sure your INSTALLED_APPS setting is correct?
The error goes away as soon as I comment out "from django.contrib.gis.db import models"...
I have added "django.contrib.gis" and the "location" app to the INSTALLED_APPS setting correctly.
Any clues why this is happening? I am running using Django v1.1.1 final, on my windows laptop.
| [
"If you have location on your INSTALLED_APPS and are getting this error, most likely you don't have the location app in your PYTHONPATH.\n",
"I had encountered the same issue using Postgres 8.4\nLinks to psycopg2 and GeoDjango given on GeoDjango installation instructions page rely on Postgres 8.3,\nSo, if you use... | [
0,
0,
0
] | [] | [] | [
"django",
"django_models",
"geodjango",
"python"
] | stackoverflow_0001734147_django_django_models_geodjango_python.txt |
Q:
Python: pip installs sub-packages in root dir
I have such structure:
setup.py
package
__init__.py
sub_package
___init__.py
sub_package2
__init__.py
If I install package via setup.py install, then it works as appreciated (by copying whole package to site-packages dir):
site_packages
package
sub_package
sub_package2
But if I run pip install package, then pip installs each sub-package as independent package:
site-packages
package
sub_package
sub_package2
How can I avoid this? I use find_packages() from setuptools to specify packages.
A:
NOTE: This answer is not valid anymore, it's only kept for historical reasons, the right answer right now is to use setuptools, more info https://mail.python.org/pipermail/distutils-sig/2013-March/020126.html
First of all i will recommend to drop setuptools :
And use either distutils (which is the standard mechanism to distribute Python packages) or distribute you have also distutils2 but i think is not ready yet, and for the new standard here is a guide line to how to write a setup.py.
For your problem the find_packages() don't exist in the distutils and you will have to add your package like this:
setup(name='package',
version='0.0dev1',
description='blalal',
author='me',
packages=['package', 'package.sub_package', 'package.sub_package2'])
And if you have a lot of package and sub packages you will have to make some code that create the list of packages here is an example from Django source.
I think using distutils can help you with your problem,and i hope this can help :)
| Python: pip installs sub-packages in root dir | I have such structure:
setup.py
package
__init__.py
sub_package
___init__.py
sub_package2
__init__.py
If I install package via setup.py install, then it works as appreciated (by copying whole package to site-packages dir):
site_packages
package
sub_package
sub_package2
But if I run pip install package, then pip installs each sub-package as independent package:
site-packages
package
sub_package
sub_package2
How can I avoid this? I use find_packages() from setuptools to specify packages.
| [
"NOTE: This answer is not valid anymore, it's only kept for historical reasons, the right answer right now is to use setuptools, more info https://mail.python.org/pipermail/distutils-sig/2013-March/020126.html\n\nFirst of all i will recommend to drop setuptools :\n\nAnd use either distutils (which is the standard m... | [
7
] | [] | [] | [
"distutils",
"pip",
"python",
"setuptools"
] | stackoverflow_0004134209_distutils_pip_python_setuptools.txt |
Q:
Modifying an advanced-indexed subset of a NumPy recarray in place
I have a recarray with a couple columns that I use for selecting a subset. Something like
>>> x
array([ ('label1',True,3),
('label2',True,2),
('label1',False,4)],
dtype=[('status', '|S16'), ('select', '|b1'), ('somedata', '<i4')])
Data is selected from this array using an approach similar to a previous SO question.
condit=(x['status']=='label1')&(x['select']==True)
x_subids=numpy.where(condit)[0]
x_sub=x[x_subids]
Then I do some work on the subset and update the original.
x[x_subids]=x_sub
I understand that x_sub is a copy rather than a view due to advanced indexing, and I was wondering if there was an elegant way of avoiding the array copy and just working with the original given the conditions that I need to subset the data.
A:
The kind of modifications you mention in the comments to my first answer can be done with the numpy.place() function:
>>> import numpy
>>> x = numpy.array([("label1",True,3), ("label2",False,2), ("label1",True,4)],
... dtype=[("status", "|S16"), ("select", "|b1"), ("somedata", ">> mask = x["select"]
>>> numpy.place(x["somedata"], mask, (5, 6))
>>> print x
[('label1', True, 5) ('label2', False, 2) ('label1', True, 6)]
>>> numpy.place(x["status"], mask, "label3")
>>> print x
[('label3', True, 5) ('label2', False, 2) ('label3', True, 6)]
Note that
I changed the values and conditions a bit for the sake of a pertinent example.
This time, the values where mask is True are selected again, not masked out as in my previous answer.
The ==True part in your mask condit is redundant, just leave it out :)
A:
You could use a "masked array":
masked = numpy.ma.array(x,
mask=(x['status']!='label1')|(x['select']!=True),
copy=False)
Note that the mask is the inverse of your condit, since the values where the mask is True are masked out. You can now apply any numpy ufunc to this masked array, and only the values not masked out are affected.
| Modifying an advanced-indexed subset of a NumPy recarray in place | I have a recarray with a couple columns that I use for selecting a subset. Something like
>>> x
array([ ('label1',True,3),
('label2',True,2),
('label1',False,4)],
dtype=[('status', '|S16'), ('select', '|b1'), ('somedata', '<i4')])
Data is selected from this array using an approach similar to a previous SO question.
condit=(x['status']=='label1')&(x['select']==True)
x_subids=numpy.where(condit)[0]
x_sub=x[x_subids]
Then I do some work on the subset and update the original.
x[x_subids]=x_sub
I understand that x_sub is a copy rather than a view due to advanced indexing, and I was wondering if there was an elegant way of avoiding the array copy and just working with the original given the conditions that I need to subset the data.
| [
"The kind of modifications you mention in the comments to my first answer can be done with the numpy.place() function:\n\n>>> import numpy\n>>> x = numpy.array([(\"label1\",True,3), (\"label2\",False,2), (\"label1\",True,4)],\n... dtype=[(\"status\", \"|S16\"), (\"select\", \"|b1\"), (\"somedata\", \">> mask = ... | [
3,
2
] | [] | [] | [
"arrays",
"indexing",
"numpy",
"python"
] | stackoverflow_0004111514_arrays_indexing_numpy_python.txt |
Q:
Count the number of elements of same value in Python
Possible Duplicate:
How to count the frequency of the elements in a list?
I wish to count the number of elements of same value in a list and return a dict as such:
> a = map(int,[x**0.5 for x in range(20)])
> a
> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
> number_of_elements_by_value(a)
> {0:1, 1:3, 2:5, 3:7, 4:4}
I guess it is kind of a histogram?
A:
This is a good way if you don't have collections.Counter available
from collections import defaultdict
d = defaultdict(int)
a = map(int, [x**0.5 for x in range(20)])
for i in a:
d[i] += 1
print d
A:
Use a Counter:
>>> from collections import Counter
>>> a = map(int,[x**0.5 for x in range(20)])
>>> a
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> c = Counter(a)
>>> c[2]
5
A:
Use count to get the count of an element in list and set for unique elements:
>>> l = [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> k = [(x, l.count(x)) for x in set(l)]
>>> k
[(0, 1), (1, 3), (2, 5), (3, 7), (4, 4)]
>>>
>>>
>>> dict(k)
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
>>>
A:
Before there was Counter, there was groupby:
>>> a = map(int,[x**0.5 for x in range(20)])
>>> from itertools import groupby
>>> a_hist= dict((g[0],len(list(g[1]))) for g in groupby(a))
>>> a_hist
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
(For groupby to work for this purpose, the input list a must be in sorted order. In this case, a is already sorted.)
| Count the number of elements of same value in Python |
Possible Duplicate:
How to count the frequency of the elements in a list?
I wish to count the number of elements of same value in a list and return a dict as such:
> a = map(int,[x**0.5 for x in range(20)])
> a
> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
> number_of_elements_by_value(a)
> {0:1, 1:3, 2:5, 3:7, 4:4}
I guess it is kind of a histogram?
| [
"This is a good way if you don't have collections.Counter available\nfrom collections import defaultdict\nd = defaultdict(int)\na = map(int, [x**0.5 for x in range(20)])\nfor i in a:\n d[i] += 1\n\nprint d\n\n",
"Use a Counter:\n>>> from collections import Counter\n\n>>> a = map(int,[x**0.5 for x in range(20)]... | [
8,
7,
4,
0
] | [] | [] | [
"counter",
"histogram",
"python"
] | stackoverflow_0004131982_counter_histogram_python.txt |
Q:
Remove duplicate nodes in an XML
I'm generating an XML file using Python and markup.py ....it was all working out but due to recent changes in the script, I'm now getting duplicated values in the nodes due to the checks I put in place. Here's a sample of the output (they are vehicle records):
<?xml version='1.0' encoding='UTF-8' ?>
<datafeed>
<vehicle>
<vin>2HNYD18816H532105</vin>
<features>
<feature>AM/FM Radio</feature>
<feature>Air Conditioning</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>CD Player</feature>
<feature>Air Bags</feature>
<feature>Air Bags</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
</features>
</vehicle>
<vehicle>
<vin>2HKYF18746H537006</vin>
<features>
<feature>AM/FM Radio</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Air Bags</feature>
<feature>Air Bags</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
<feature>Alarm</feature>
</features>
</vehicle>
</datafeed>
This is a small excerpt from a larger XML file having over 100 records. What can I do to remove the duplicate nodes?
A:
There are no real "duplicates" in XML. Every node is different by definition. But I understand you that you want to get rid of all duplicate features in your interpretion.
You can do this by simply parsing that tree, putting the features (the values of the nodes) in a set (to get rid of duplicates) and writing out a new XML document.
Given that you are generating the file with Python, you should modify the creation routine the way that it doesn't generate duplicate values to begin with. You might want to tell us what the markup.py is or does.
edit
I just took a quick look at the markup script, so something like this might appear in your script:
// well, this might come from somewhere else, but I guess you have such a list somewhere
features = [ 'AM/FM Radio', 'Air Conditioning', 'Anti-Lock Brakes (ABS)', 'Alarm', 'CD Player', 'Air Bags', 'Air Bags', 'Anti-Lock Brakes (ABS)', 'Alarm', 'Air Bags', 'Alarm', 'Air Bags' ]
// write the XML
markup.features.open()
markup.feature( features )
markup.features.close()
In this case, just make features a set before passing it to the markup script:
// write the XML
markup.features.open()
markup.feature( set( features ) )
markup.features.close()
If you have multiple separate lists that contain your features for a single vehicle, combine those lists (or sets) first:
list1 = [...]
list2 = [...]
list3 = [...]
features = set( list1 + list2 + list3 )
| Remove duplicate nodes in an XML | I'm generating an XML file using Python and markup.py ....it was all working out but due to recent changes in the script, I'm now getting duplicated values in the nodes due to the checks I put in place. Here's a sample of the output (they are vehicle records):
<?xml version='1.0' encoding='UTF-8' ?>
<datafeed>
<vehicle>
<vin>2HNYD18816H532105</vin>
<features>
<feature>AM/FM Radio</feature>
<feature>Air Conditioning</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>CD Player</feature>
<feature>Air Bags</feature>
<feature>Air Bags</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
</features>
</vehicle>
<vehicle>
<vin>2HKYF18746H537006</vin>
<features>
<feature>AM/FM Radio</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Air Bags</feature>
<feature>Air Bags</feature>
<feature>Anti-Lock Brakes (ABS)</feature>
<feature>Alarm</feature>
<feature>Air Bags</feature>
<feature>Alarm</feature>
</features>
</vehicle>
</datafeed>
This is a small excerpt from a larger XML file having over 100 records. What can I do to remove the duplicate nodes?
| [
"There are no real \"duplicates\" in XML. Every node is different by definition. But I understand you that you want to get rid of all duplicate features in your interpretion.\nYou can do this by simply parsing that tree, putting the features (the values of the nodes) in a set (to get rid of duplicates) and writing ... | [
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004134531_python_xml.txt |
Q:
Recommended IDE for developing Pylons apps
I have been reading through this wonderful website regarding the recommended Python IDEs and have narrowed it down to either
WingIDE
KomodoIDE
which you guys will recommend for the purpose of developing Pylons apps? I know that most questions have been asked pertaining to Python IDEs but how about Python web framework IDEs which is a mishmash of various templating languages and Python itself.
One con i have to raise about WingIDE on Windows is that it has an AWFUL interface (probably cos of the GTK+ toolkit?)
I have been using e-text editor all the while and increasingly been dissatisfied with it especially when its unable to do correct syntax highlighting at times. Furthermore I am hoping syntax coloration can be done for Mako templates.
Thank you very much all and have a great day!
A:
Did you try Eclipse with PyDev plugin? Which is FREE plus works for any OS.
Screenshots at the PyDev website.
(source: sourceforge.net)
A:
+1 for WingIDE, It supports debugging pylons app.
A:
Netbeans has implemented beta support of python development. It unfortunately doesn't specifically support any templating languages that I know of, but I've been satisfied so far with its syntax highlighting and auto-complete (especially from imported modules).
Since everyone has a different preference for their coding environment, I suggest you just try out every IDE/editor you can get your hands on; so you can find the best mix-match of features that you're specifically looking for.
A:
I use Stani's Python Editor for most Python-esque editing tasks on Windows & Linux. I use Notepad++ for editing HTML, XML, CSV, and other text based "code like" files on Windows. They are both free, and meet my needs for home based weekend projects.
I have used Wing IDE 101, but I never the full versions. I did not do enough with WingIDE to develop any muscle memory, so it still feels a little artificial to me. YMMV.
To a certain degree, the IDE will influence how you think about the process of creating and debugging code. So you should take some time to try a few different options and see which makes the most sense to you.
A:
Try Aptana Studio... It's eclipse+pydev+web stuff, it doesnt have any specific pylons stuff or mako support. But eclipse+pydev alone is great + all the nice jscript+html+css stuff aptana adds.
A:
+1 for Spyder. Never heard of it before reading this page. Working great so far.
A:
after very very careful comparison, KomodoIDE 5.1 is most suitable for my purposes.
Reasons:
Extensibility
Support for Mako and YUI (required by me)
Native interface support (no GTK unfamiliarity)
Support for Mercurial SCM (required by me)
thats all I guess. I am extremely satisfied with KomodoIDE and have just shelled out some money to buy it.
I figured when making a choice of tools, spend a day or two (yes, it takes time) trying them out and choosing what best suits your day-to-day purposes. If its just your first time coding, using a standard free tool or open source tool is far more useful than expending the time to find out the best tool.
Only after some degree of expertise is acquired, you have a very narrow spectrum of requirements/preferences which will make choosing a tool far easier.
A:
Wow, I've also been looking for a good Pylons web app IDE. Seems like KomodoIDE 5.1 kicks some serious ass. I love the support for Mako and that it supports pretty much all of the SCMs.
I've been using Textmate, but KomodoIDE will take over from now onwards
A:
I'v been using Spyderlib for some time, its really worth trying.
http://code.google.com/p/spyderlib/
http://groups.google.com/group/pylons-discuss/browse_thread/thread/4f41aef28be741e5
| Recommended IDE for developing Pylons apps | I have been reading through this wonderful website regarding the recommended Python IDEs and have narrowed it down to either
WingIDE
KomodoIDE
which you guys will recommend for the purpose of developing Pylons apps? I know that most questions have been asked pertaining to Python IDEs but how about Python web framework IDEs which is a mishmash of various templating languages and Python itself.
One con i have to raise about WingIDE on Windows is that it has an AWFUL interface (probably cos of the GTK+ toolkit?)
I have been using e-text editor all the while and increasingly been dissatisfied with it especially when its unable to do correct syntax highlighting at times. Furthermore I am hoping syntax coloration can be done for Mako templates.
Thank you very much all and have a great day!
| [
"Did you try Eclipse with PyDev plugin? Which is FREE plus works for any OS.\nScreenshots at the PyDev website.\n\n(source: sourceforge.net) \n",
"+1 for WingIDE, It supports debugging pylons app. \n",
"Netbeans has implemented beta support of python development. It unfortunately doesn't specifically support an... | [
13,
3,
1,
1,
1,
1,
0,
0,
0
] | [] | [] | [
"ide",
"pylons",
"python"
] | stackoverflow_0001065964_ide_pylons_python.txt |
Q:
How can i access the file-selection in Path Finder via py-appscript?
Using the filemanager Path Finder on mac os x, i wanna retrieve the selected files/folders with python by using py-appscript. py-appscript is a high-level event bridge that allows you to control scriptable Mac OS X applications from Python.
In applescript it would be something like
tell application "Path Finder"
set selection_list to selection -- list of fsItems (fsFiles and fsFolders)
set _path to posix path of first item of selection_list
do shell script "python " & quoted form of _path
end tell
In python it would instead something like
from appscript import *
selectection_list = app('Path Finder').selection.get() # returns reference, not string
So, how can i convert the references in selection_list to python-strings?
A:
I'm not familiar with Pathfinder, but if it has its own file URL type (or maybe it's a POSIX path?), then there is presumably a delimiter of some kind that separates the levels of file hierarchy in the path. To convert between one and the other, you need to work with Applescript's text item delimiters. Something along these lines should work
set thePathFinderPath to "/pathfinder/path/to/finder"
set pathFinderPathDelimiter to "/" -- whatever it may be here
set finderPathDelimiter to ":"
set AppleScript's text item delimiters to {pathFinderPathDelimiter}
set thePathComponents to (get every text item in thePathFinderPath) as list
set AppleScript's text item delimiters to {finderPathDelimiter}
set theFinderPath to thePathComponents as text
set AppleScript's text item delimiters to "" -- very important you clear the TIDs.
Add salt to taste. But, if you can provide an example of the PathFinder URL, then I can provide a better answer.
A:
Why don't you try python-applescript, it can run applescript's script thru python. Get it here : http://pypi.python.org/pypi/python-applescript
| How can i access the file-selection in Path Finder via py-appscript? | Using the filemanager Path Finder on mac os x, i wanna retrieve the selected files/folders with python by using py-appscript. py-appscript is a high-level event bridge that allows you to control scriptable Mac OS X applications from Python.
In applescript it would be something like
tell application "Path Finder"
set selection_list to selection -- list of fsItems (fsFiles and fsFolders)
set _path to posix path of first item of selection_list
do shell script "python " & quoted form of _path
end tell
In python it would instead something like
from appscript import *
selectection_list = app('Path Finder').selection.get() # returns reference, not string
So, how can i convert the references in selection_list to python-strings?
| [
"I'm not familiar with Pathfinder, but if it has its own file URL type (or maybe it's a POSIX path?), then there is presumably a delimiter of some kind that separates the levels of file hierarchy in the path. To convert between one and the other, you need to work with Applescript's text item delimiters. Something a... | [
0,
0
] | [] | [] | [
"applescript",
"macos",
"path_finding",
"python",
"sourceforge_appscript"
] | stackoverflow_0004122750_applescript_macos_path_finding_python_sourceforge_appscript.txt |
Q:
Python, MySQL and a weird error
I have a bug that I don't know how to fix or even reproduce:
query = "SELECT id, name FROM names ORDER BY id"
results = database.execute(query)
where the class Database contains:
def execute(self, query):
cursor = self.db.cursor()
try:
cursor.execute(query)
return cursor.fetchall()
except:
import traceback
traceback.print_exc(file=debugFile)
return []
This is how I open the database connection:
self.db = MySQLdb.connect(
host=mysqlHost,
user=mysqlUser,
passwd=mysqlPasswd,
db=mysqlDB
)
This is the stacktrace of the error:
File "foo.py", line 169, in application results = config.db.execute(query)
File "Database.py", line 52, in execute
return cursor.fetchall()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 340, in fetchall
self._check_executed()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 70, in _check_executed
self.errorhandler(self, ProgrammingError, "execute() first")
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: execute() first
Do you have any ideas of why this is happening and how can I fix it? I searched on the internet and I found out that the reason may be having 2 cursors, but I have only one.
A:
try this in your traceback it's for debugging:
except ProgrammingError as ex:
if cursor:
print "\n".join(cursor.messages)
# You can show only the last error like this.
# print cursor.messages[-1]
else:
print "\n".join(self.db.messages)
# Same here you can also do.
# print self.db.messages[-1]
| Python, MySQL and a weird error | I have a bug that I don't know how to fix or even reproduce:
query = "SELECT id, name FROM names ORDER BY id"
results = database.execute(query)
where the class Database contains:
def execute(self, query):
cursor = self.db.cursor()
try:
cursor.execute(query)
return cursor.fetchall()
except:
import traceback
traceback.print_exc(file=debugFile)
return []
This is how I open the database connection:
self.db = MySQLdb.connect(
host=mysqlHost,
user=mysqlUser,
passwd=mysqlPasswd,
db=mysqlDB
)
This is the stacktrace of the error:
File "foo.py", line 169, in application results = config.db.execute(query)
File "Database.py", line 52, in execute
return cursor.fetchall()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 340, in fetchall
self._check_executed()
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 70, in _check_executed
self.errorhandler(self, ProgrammingError, "execute() first")
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
ProgrammingError: execute() first
Do you have any ideas of why this is happening and how can I fix it? I searched on the internet and I found out that the reason may be having 2 cursors, but I have only one.
| [
"try this in your traceback it's for debugging:\nexcept ProgrammingError as ex:\n if cursor:\n print \"\\n\".join(cursor.messages) \n # You can show only the last error like this.\n # print cursor.messages[-1]\n else:\n print \"\\n\".join(self.db.messages)\n # Same here you ... | [
3
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004134635_mysql_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.