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:
What does '_' do in Django code?
Why does this Django code use _ in front of 'has favicon'
has_favicon = models.BooleanField(_('has favicon'))
A:
If you look in the import statements, you'll find that they tied _ to a function that turns stuff into unicode and localizes it by writing:
from django.utils.translation import ugettext_lazy as _
A:
_ in Django is a convention that is used for localizing texts. It is an alias for ugettext_lazy. Read Lazy translation in the docs for more info about it.
A:
_ is usually a macro/function from gettext, it means the argument is a localized string. this is not limited to Django or Python. in fact gettext is originally a package for C programs, ported to many other languages over the years.
|
What does '_' do in Django code?
|
Why does this Django code use _ in front of 'has favicon'
has_favicon = models.BooleanField(_('has favicon'))
|
[
"If you look in the import statements, you'll find that they tied _ to a function that turns stuff into unicode and localizes it by writing:\nfrom django.utils.translation import ugettext_lazy as _\n\n",
"_ in Django is a convention that is used for localizing texts. It is an alias for ugettext_lazy. Read Lazy translation in the docs for more info about it.\n",
"_ is usually a macro/function from gettext, it means the argument is a localized string. this is not limited to Django or Python. in fact gettext is originally a package for C programs, ported to many other languages over the years.\n"
] |
[
34,
11,
9
] |
[] |
[] |
[
"django",
"gettext",
"internationalization",
"python"
] |
stackoverflow_0001962287_django_gettext_internationalization_python.txt
|
Q:
Python: error while checking IE state
Please, help me with Python 2.6 and win32com.
I'm a newbie to Python and I got error
when I start the next program:
import pywintypes
from win32com.client import Dispatch
from time import sleep
ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'
ie.navigate(url)
while ie.ReadyState !=4:
sleep(1)
print 'OK'
..........................
Error message:
while ie.ReadyState !=4:
...
pywintypes.com_error:
(-2147023179, 'Unknown interface.', None, None)
..........................
But when I change url to, for example, 'yahoo.com' -
there are no errors.
How can result of checking ReadyState may be dependant on url??
A:
The sleep trick won't work with IE. You actually need to pump messages while you wait. I don't think a thread will work, by the way, because IE hates to not be in the GUI thread.
Here's a ctypes-based message pump, with which I was able to get a 4 ReadyState for "hotfile.com" and "yahoo.com". It pulls all the messages currently on the queue, and processes them before running the check.
(Yes, this is pretty hairy, but you can tuck this away into a "pump_messages" function so you at least don't have to look at it!)
from ctypes import Structure, pointer, windll
from ctypes import c_int, c_long, c_uint
import win32con
import pywintypes
from win32com.client import Dispatch
class POINT(Structure):
_fields_ = [('x', c_long),
('y', c_long)]
def __init__( self, x=0, y=0 ):
self.x = x
self.y = y
class MSG(Structure):
_fields_ = [('hwnd', c_int),
('message', c_uint),
('wParam', c_int),
('lParam', c_int),
('time', c_int),
('pt', POINT)]
msg = MSG()
pMsg = pointer(msg)
NULL = c_int(win32con.NULL)
ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'
ie.navigate(url)
while True:
while windll.user32.PeekMessageW( pMsg, NULL, 0, 0, win32con.PM_REMOVE) != 0:
windll.user32.TranslateMessage(pMsg)
windll.user32.DispatchMessageW(pMsg)
if ie.ReadyState == 4:
print "Gotcha!"
break
|
Python: error while checking IE state
|
Please, help me with Python 2.6 and win32com.
I'm a newbie to Python and I got error
when I start the next program:
import pywintypes
from win32com.client import Dispatch
from time import sleep
ie = Dispatch("InternetExplorer.Application")
ie.visible=1
url='hotfile.com'
ie.navigate(url)
while ie.ReadyState !=4:
sleep(1)
print 'OK'
..........................
Error message:
while ie.ReadyState !=4:
...
pywintypes.com_error:
(-2147023179, 'Unknown interface.', None, None)
..........................
But when I change url to, for example, 'yahoo.com' -
there are no errors.
How can result of checking ReadyState may be dependant on url??
|
[
"The sleep trick won't work with IE. You actually need to pump messages while you wait. I don't think a thread will work, by the way, because IE hates to not be in the GUI thread.\nHere's a ctypes-based message pump, with which I was able to get a 4 ReadyState for \"hotfile.com\" and \"yahoo.com\". It pulls all the messages currently on the queue, and processes them before running the check.\n(Yes, this is pretty hairy, but you can tuck this away into a \"pump_messages\" function so you at least don't have to look at it!)\nfrom ctypes import Structure, pointer, windll\nfrom ctypes import c_int, c_long, c_uint\nimport win32con\nimport pywintypes\nfrom win32com.client import Dispatch\n\nclass POINT(Structure):\n _fields_ = [('x', c_long),\n ('y', c_long)]\n def __init__( self, x=0, y=0 ):\n self.x = x\n self.y = y\n\nclass MSG(Structure):\n _fields_ = [('hwnd', c_int),\n ('message', c_uint),\n ('wParam', c_int),\n ('lParam', c_int),\n ('time', c_int),\n ('pt', POINT)]\n\nmsg = MSG()\npMsg = pointer(msg)\nNULL = c_int(win32con.NULL)\n\nie = Dispatch(\"InternetExplorer.Application\")\nie.visible=1\nurl='hotfile.com'\nie.navigate(url)\n\nwhile True:\n\n while windll.user32.PeekMessageW( pMsg, NULL, 0, 0, win32con.PM_REMOVE) != 0:\n windll.user32.TranslateMessage(pMsg)\n windll.user32.DispatchMessageW(pMsg)\n\n if ie.ReadyState == 4:\n print \"Gotcha!\"\n break\n\n"
] |
[
1
] |
[] |
[] |
[
"python",
"win32com"
] |
stackoverflow_0001965911_python_win32com.txt
|
Q:
how can i determine if anything at the given url does exist
how can i determine if anything at the given url does exist in the web using python? it can be a html page or a pdf file, shouldnt be matter.
ive tried the solution written in this page http://code.activestate.com/recipes/101276/
but it just returns a 1 when its a pdf file or anything.
A:
You need to check HTTP response code. Python example:
from urllib2 import urlopen
code = urlopen("http://example.com/").code
4xx and 5xx code probably mean that you cannot get anything from this URL. 4xx status codes describe client errors (like "404 Not found") and 5xx status codes describe server errors (like "500 Internal server error"):
if (code / 100 >= 4):
print "Nothing there."
Links:
HTTP status codes
urllib2 reference
A:
Send a HEAD request
import httplib
connection = httplib.HTTPConnection(url)
connection.request('HEAD', '/')
response = connection.getresponse()
if response.status == 200:
print "Resource exists"
A:
The httplib in that example is using HTTP/1.0 instead of 1.1, and as such Slashdot is returning a status code 301 instead of 200. I would recommend using urllib2, and also probably checking for codes 20* and 30*.
The documentation for httplib states:
It is normally not used directly — the module urllib uses it to handle URLs that use HTTP and HTTPS.
[...]
The HTTP class is retained only for backward compatibility with 1.5.2. It should not be used in new code. Refer to the online docstrings for usage.
So yes. urllib is the way to open URLs in Python — an HTTP/1.0 client won't get very far on modern web servers.
(Also, a PDF link works for me.)
A:
This solution returns 1 because server is sending 200 OK response.
There's something wrong with your server. It should return 404 if the file doesn't exist.
|
how can i determine if anything at the given url does exist
|
how can i determine if anything at the given url does exist in the web using python? it can be a html page or a pdf file, shouldnt be matter.
ive tried the solution written in this page http://code.activestate.com/recipes/101276/
but it just returns a 1 when its a pdf file or anything.
|
[
"You need to check HTTP response code. Python example:\nfrom urllib2 import urlopen\ncode = urlopen(\"http://example.com/\").code\n\n4xx and 5xx code probably mean that you cannot get anything from this URL. 4xx status codes describe client errors (like \"404 Not found\") and 5xx status codes describe server errors (like \"500 Internal server error\"):\nif (code / 100 >= 4):\n print \"Nothing there.\"\n\nLinks:\n\nHTTP status codes\nurllib2 reference\n\n",
"Send a HEAD request\nimport httplib \nconnection = httplib.HTTPConnection(url) \nconnection.request('HEAD', '/') \nresponse = connection.getresponse() \nif response.status == 200:\n print \"Resource exists\"\n\n",
"The httplib in that example is using HTTP/1.0 instead of 1.1, and as such Slashdot is returning a status code 301 instead of 200. I would recommend using urllib2, and also probably checking for codes 20* and 30*.\nThe documentation for httplib states:\n\nIt is normally not used directly — the module urllib uses it to handle URLs that use HTTP and HTTPS.\n[...]\nThe HTTP class is retained only for backward compatibility with 1.5.2. It should not be used in new code. Refer to the online docstrings for usage.\n\nSo yes. urllib is the way to open URLs in Python — an HTTP/1.0 client won't get very far on modern web servers.\n(Also, a PDF link works for me.)\n",
"This solution returns 1 because server is sending 200 OK response.\nThere's something wrong with your server. It should return 404 if the file doesn't exist.\n"
] |
[
16,
9,
2,
0
] |
[] |
[] |
[
"http",
"python",
"url"
] |
stackoverflow_0001966086_http_python_url.txt
|
Q:
Remove all nested blocks, whilst leaving non-nested blocks alone via python
Source:
[This] is some text with [some [blocks that are nested [in a [variety] of ways]]]
Resultant text:
[This] is some text with
I don't think you can do a regex for this, from looking at the threads at stack overflow.
Is there a simple way to to do this -> or must one reach for pyparsing (or other parsing library)?
A:
Here's an easy way that doesn't require any dependencies: scan the text and keep a counter for the braces that you pass over. Increment the counter each time you see a "["; decrement it each time you see a "]".
As long as the counter is at zero or one, put the text you see onto the output string.
Otherwise, you are in a nested block, so don't put the text onto the output string.
If the counter doesn't finish at zero, the string is malformed; you have an unequal number of opening and closing braces. (If it's greater than zero, you have that many excess [s; if it's less than zero you have that many excess ]s.)
A:
Taking the OP's example as normative (any block including further nested blocks must be removed), what about...:
import itertools
x = '''[This] is some text with [some [blocks that are nested [in a [variety]
of ways]]] and some [which are not], and [any [with nesting] must go] away.'''
def nonest(txt):
pieces = []
d = 0
level = []
for c in txt:
if c == '[': d += 1
level.append(d)
if c == ']': d -= 1
for k, g in itertools.groupby(zip(txt, level), lambda x: x[1]>0):
block = list(g)
if max(d for c, d in block) > 1: continue
pieces.append(''.join(c for c, d in block))
print ''.join(pieces)
nonest(x)
This emits
[This] is some text with and some [which are not], and away.
which under the normatime hypothesis would seem to be the desired result.
The idea is to compute, in level, a parallel list of counts "how nested are we at this point" (i.e., how many opened and not yet closed brackets have we met so far); then segment the zip of level with the text, with groupby, into alternate blocks with zero nesting and nesting > 0. For each block, the maximum nesting herein is then computed (will stay at zero for blocks with zero nesting - more generally, it's just the maximum of the nesting levels throughout the block), and if the resulting nesting is <= 1, the corresponding block of text is preserved. Note that we need to make the group g into a list block as we want to perform two iteration passes (one to get the max nesting, one to rejoin the characters into a block of text) -- to do it in a single pass we'd need to keep some auxiliary state in the nested loop, which is a bit less convenient in this case.
A:
You will be better off writing a parser, especially if you use a parser generator like pyparsing. It will be more maintainable and extendable.
In fact pyparsing already implements the parser for you, you just need to write the function that filters the parser output.
A:
I took a couple of passes at writing a single parser expression that could be used with expression.transformString(), but I had difficulty distinguish between nested and unnested []'s at parse time. In the end I had to open up the loop in transformString and iterate over the scanString generator explicitly.
To address the question of whether [some] should be included or not based on the original question, I explored this by adding more "unnested" text at the end, using this string:
src = """[This] is some text with [some [blocks that are
nested [in a [variety] of ways]] in various places]"""
My first parser follows the original question's lead, and rejects any bracketed expression that has any nesting. My second pass takes the top level tokens of any bracketed expression, and returns them in brackets - I didn't like this solution so well, as we lose the information that "some" and "in various places" are not contiguous. So I took one last pass, and had to make a slight change to the default behavior of nestedExpr. See the code below:
from pyparsing import nestedExpr, ParseResults, CharsNotIn
# 1. scan the source string for nested [] exprs, and take only those that
# do not themselves contain [] exprs
out = []
last = 0
for tokens,start,end in nestedExpr("[","]").scanString(src):
out.append(src[last:start])
if not any(isinstance(tok,ParseResults) for tok in tokens[0]):
out.append(src[start:end])
last = end
out.append(src[last:])
print "".join(out)
# 2. scan the source string for nested [] exprs, and take only the toplevel
# tokens from each
out = []
last = 0
for t,s,e in nestedExpr("[","]").scanString(src):
out.append(src[last:s])
topLevel = [tok for tok in t[0] if not isinstance(tok,ParseResults)]
out.append('['+" ".join(topLevel)+']')
last = e
out.append(src[last:])
print "".join(out)
# 3. scan the source string for nested [] exprs, and take only the toplevel
# tokens from each, keeping each group separate
out = []
last = 0
for t,s,e in nestedExpr("[","]", CharsNotIn('[]')).scanString(src):
out.append(src[last:s])
for tok in t[0]:
if isinstance(tok,ParseResults): continue
out.append('['+tok.strip()+']')
last = e
out.append(src[last:])
print "".join(out)
Giving:
[This] is some text with
[This] is some text with [some in various places]
[This] is some text with [some][in various places]
I hope one of these comes close to the OP's question. But if nothing else, I got to explore nestedExpr's behavior a little further.
|
Remove all nested blocks, whilst leaving non-nested blocks alone via python
|
Source:
[This] is some text with [some [blocks that are nested [in a [variety] of ways]]]
Resultant text:
[This] is some text with
I don't think you can do a regex for this, from looking at the threads at stack overflow.
Is there a simple way to to do this -> or must one reach for pyparsing (or other parsing library)?
|
[
"Here's an easy way that doesn't require any dependencies: scan the text and keep a counter for the braces that you pass over. Increment the counter each time you see a \"[\"; decrement it each time you see a \"]\".\n\nAs long as the counter is at zero or one, put the text you see onto the output string.\nOtherwise, you are in a nested block, so don't put the text onto the output string.\nIf the counter doesn't finish at zero, the string is malformed; you have an unequal number of opening and closing braces. (If it's greater than zero, you have that many excess [s; if it's less than zero you have that many excess ]s.)\n\n",
"Taking the OP's example as normative (any block including further nested blocks must be removed), what about...:\nimport itertools\n\nx = '''[This] is some text with [some [blocks that are nested [in a [variety]\nof ways]]] and some [which are not], and [any [with nesting] must go] away.'''\n\ndef nonest(txt):\n pieces = []\n d = 0\n level = []\n for c in txt:\n if c == '[': d += 1\n level.append(d)\n if c == ']': d -= 1\n for k, g in itertools.groupby(zip(txt, level), lambda x: x[1]>0):\n block = list(g)\n if max(d for c, d in block) > 1: continue\n pieces.append(''.join(c for c, d in block))\n print ''.join(pieces)\n\nnonest(x)\n\nThis emits\n[This] is some text with and some [which are not], and away.\n\nwhich under the normatime hypothesis would seem to be the desired result.\nThe idea is to compute, in level, a parallel list of counts \"how nested are we at this point\" (i.e., how many opened and not yet closed brackets have we met so far); then segment the zip of level with the text, with groupby, into alternate blocks with zero nesting and nesting > 0. For each block, the maximum nesting herein is then computed (will stay at zero for blocks with zero nesting - more generally, it's just the maximum of the nesting levels throughout the block), and if the resulting nesting is <= 1, the corresponding block of text is preserved. Note that we need to make the group g into a list block as we want to perform two iteration passes (one to get the max nesting, one to rejoin the characters into a block of text) -- to do it in a single pass we'd need to keep some auxiliary state in the nested loop, which is a bit less convenient in this case.\n",
"You will be better off writing a parser, especially if you use a parser generator like pyparsing. It will be more maintainable and extendable.\nIn fact pyparsing already implements the parser for you, you just need to write the function that filters the parser output.\n",
"I took a couple of passes at writing a single parser expression that could be used with expression.transformString(), but I had difficulty distinguish between nested and unnested []'s at parse time. In the end I had to open up the loop in transformString and iterate over the scanString generator explicitly.\nTo address the question of whether [some] should be included or not based on the original question, I explored this by adding more \"unnested\" text at the end, using this string:\nsrc = \"\"\"[This] is some text with [some [blocks that are \n nested [in a [variety] of ways]] in various places]\"\"\"\n\nMy first parser follows the original question's lead, and rejects any bracketed expression that has any nesting. My second pass takes the top level tokens of any bracketed expression, and returns them in brackets - I didn't like this solution so well, as we lose the information that \"some\" and \"in various places\" are not contiguous. So I took one last pass, and had to make a slight change to the default behavior of nestedExpr. See the code below:\nfrom pyparsing import nestedExpr, ParseResults, CharsNotIn\n\n# 1. scan the source string for nested [] exprs, and take only those that\n# do not themselves contain [] exprs\nout = []\nlast = 0\nfor tokens,start,end in nestedExpr(\"[\",\"]\").scanString(src):\n out.append(src[last:start])\n if not any(isinstance(tok,ParseResults) for tok in tokens[0]):\n out.append(src[start:end])\n last = end\nout.append(src[last:])\nprint \"\".join(out)\n\n\n# 2. scan the source string for nested [] exprs, and take only the toplevel \n# tokens from each\nout = []\nlast = 0\nfor t,s,e in nestedExpr(\"[\",\"]\").scanString(src):\n out.append(src[last:s])\n topLevel = [tok for tok in t[0] if not isinstance(tok,ParseResults)]\n out.append('['+\" \".join(topLevel)+']')\n last = e\nout.append(src[last:])\nprint \"\".join(out)\n\n\n# 3. scan the source string for nested [] exprs, and take only the toplevel \n# tokens from each, keeping each group separate\nout = []\nlast = 0\nfor t,s,e in nestedExpr(\"[\",\"]\", CharsNotIn('[]')).scanString(src):\n out.append(src[last:s])\n for tok in t[0]:\n if isinstance(tok,ParseResults): continue\n out.append('['+tok.strip()+']')\n last = e\nout.append(src[last:])\nprint \"\".join(out)\n\nGiving:\n[This] is some text with \n[This] is some text with [some in various places]\n[This] is some text with [some][in various places]\n\nI hope one of these comes close to the OP's question. But if nothing else, I got to explore nestedExpr's behavior a little further.\n"
] |
[
5,
4,
3,
3
] |
[] |
[] |
[
"brackets",
"nested",
"python",
"recursion",
"regex"
] |
stackoverflow_0001965486_brackets_nested_python_recursion_regex.txt
|
Q:
When is the formfield() method called in Django?
This is a question on making custom fields in Django. I'm making a field called EditAreaField, which inherits from TextField. Here's what my code looks like:
class EditAreaField(models.TextField):
description = "A field for editing the HTML of a page"
def formfield(self, **kwargs):
defaults = {}
defaults['widget'] = EditArea() # setting a new widget
defaults.update(kwargs)
return super(EditAreaField, self).formfield(**defaults)
On the 5th line, I'm assigning a custom widget to this field. On line 6, I update the parameters.
The problem is, Django sends a parameter widget that's set to django.contrib.admin.widgets.AdminTextareaWidget, which overrides my EditArea() widget.
How can I change the value that Django is setting? Obviously I could just override their setting by switching lines 5 and 6, so my code looks like:
defaults.update(kwargs)
defaults['widget'] = EditArea() # override django here
But is that really the best way to do it?
As a side note, I couldn't find documentation on the formfield() function anywhere on Django's site: is it deprecated?
A:
It looks like the formfield method is called by the ModelForm helper. According to the docs, the formfield method should include only a form_class attribute to point to the formfield class for this custom model field. This is a custom (or default) form field class, which is where the default widget is defined
from myapp.forms import MyCustomFormField
#create a custom model field
class EditAreaField(models.TextField):
def formfield(self, **kwargs):
defaults={'form_class': MyCustomFormField}#pass our custom field as form_class
defaults.update(kwargs)
return super(EditAreaField, self).formfield(**defaults)
|
When is the formfield() method called in Django?
|
This is a question on making custom fields in Django. I'm making a field called EditAreaField, which inherits from TextField. Here's what my code looks like:
class EditAreaField(models.TextField):
description = "A field for editing the HTML of a page"
def formfield(self, **kwargs):
defaults = {}
defaults['widget'] = EditArea() # setting a new widget
defaults.update(kwargs)
return super(EditAreaField, self).formfield(**defaults)
On the 5th line, I'm assigning a custom widget to this field. On line 6, I update the parameters.
The problem is, Django sends a parameter widget that's set to django.contrib.admin.widgets.AdminTextareaWidget, which overrides my EditArea() widget.
How can I change the value that Django is setting? Obviously I could just override their setting by switching lines 5 and 6, so my code looks like:
defaults.update(kwargs)
defaults['widget'] = EditArea() # override django here
But is that really the best way to do it?
As a side note, I couldn't find documentation on the formfield() function anywhere on Django's site: is it deprecated?
|
[
"It looks like the formfield method is called by the ModelForm helper. According to the docs, the formfield method should include only a form_class attribute to point to the formfield class for this custom model field. This is a custom (or default) form field class, which is where the default widget is defined\nfrom myapp.forms import MyCustomFormField\n\n#create a custom model field\nclass EditAreaField(models.TextField):\n def formfield(self, **kwargs):\n defaults={'form_class': MyCustomFormField}#pass our custom field as form_class\n defaults.update(kwargs)\n return super(EditAreaField, self).formfield(**defaults)\n\n"
] |
[
2
] |
[] |
[] |
[
"custom_field_type",
"django",
"python",
"widget"
] |
stackoverflow_0001964545_custom_field_type_django_python_widget.txt
|
Q:
Specify input() type in Python?
Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:
morning = input('Enter morning Time:')
evening = input('Enter evening Time:')
.. I need (only) time here, how do I make sure that user enters input in xx:xx format where xx are integers only.
A:
input (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use raw_input, which returns a string, and do the conversion yourself, catching the TypeError if the conversion fails.
Python 3.any's input works like 2.any's raw_input, i.e., it returns a string.
A:
You can't really force the input function to return a certain type. It's best you write some kind of a wrapper that reads some input from the user and then converts it to an appropriate type for your application (or throw an exception in case of an error).
Also, as Alex said, it's better to use raw_input for user input since it will always return the entered value as a string. Much more manageable.
|
Specify input() type in Python?
|
Is it possible to define input times, like time, date, currency or that should be verified manually? Like for example:
morning = input('Enter morning Time:')
evening = input('Enter evening Time:')
.. I need (only) time here, how do I make sure that user enters input in xx:xx format where xx are integers only.
|
[
"input (in Python 2.any) will return the type of whatever expression the user types in. Better (in Python 2.any) is to use raw_input, which returns a string, and do the conversion yourself, catching the TypeError if the conversion fails.\nPython 3.any's input works like 2.any's raw_input, i.e., it returns a string.\n",
"You can't really force the input function to return a certain type. It's best you write some kind of a wrapper that reads some input from the user and then converts it to an appropriate type for your application (or throw an exception in case of an error). \nAlso, as Alex said, it's better to use raw_input for user input since it will always return the entered value as a string. Much more manageable.\n"
] |
[
10,
1
] |
[] |
[] |
[
"input",
"python",
"types"
] |
stackoverflow_0001964996_input_python_types.txt
|
Q:
frames per seconds
I want to limit the calculation-speed. There was a command for rate per second. Could anybody help me?
doesn't rate() work in the newer version of Python?
Thanks
A:
Like Ignacio said, you can measure the time since the last calculation, calculate the time until the next, and sleep until then. You can also do it without any other framework, for example, with these functions:
from datetime import datetime
import time
t = datetime.now()[5] # milliseconds
dt = # do some calculation for time needed to sleep
time.sleep(dt) # sleep in seconds
A:
Using an event loop framework such as Twisted will allow you to schedule your next calculation in the future once you have completed the current calculation, and to sleep until that time.
A:
i found it again. There is a rate()-function in the visual-module.
you can use it in the while-loop.
|
frames per seconds
|
I want to limit the calculation-speed. There was a command for rate per second. Could anybody help me?
doesn't rate() work in the newer version of Python?
Thanks
|
[
"Like Ignacio said, you can measure the time since the last calculation, calculate the time until the next, and sleep until then. You can also do it without any other framework, for example, with these functions:\nfrom datetime import datetime\nimport time\n\nt = datetime.now()[5] # milliseconds\ndt = # do some calculation for time needed to sleep\ntime.sleep(dt) # sleep in seconds\n\n",
"Using an event loop framework such as Twisted will allow you to schedule your next calculation in the future once you have completed the current calculation, and to sleep until that time.\n",
"i found it again. There is a rate()-function in the visual-module.\nyou can use it in the while-loop.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001957237_python.txt
|
Q:
python print statements fixes OverflowError
I'm hacking a security system DVR so I can add motion capture and other fun features in python (version 2.6). One of the functions I was able to decompile from java and convert to python was the following:
def ToInt(abyte0, i):
if(abyte0[i] >= 0):
j = abyte0[i]
print "A " + str(j)
else:
j = 256 + abyte0[i]
if abyte0[i + 1] >= 0:
j = j + (abyte0[i + 1] * 256)
print "A " + str(j)
else:
j = j + (256 + abyte0[i + 1]) * 256
if abyte0[i + 2] >= 0:
j = j+ abyte0[i + 2] * 256 * 256
print "A " + str(j)
else:
j = j + (256 + abyte0[i + 2]) * 256 * 256
if abyte0[i + 3] >= 0:
j = j + abyte0[i + 3] * 256 * 256 * 256
print "A " + str(j)
else:
j = j + (256 + abyte0[i + 3]) * 256 * 256 * 256
return j
I added print statements to it to see what was going on while I was figuring things out. Now that I have it working, I went back to remove the print statements and I get an error!
Traceback (most recent call last):
File "C:\Users\...\videostuff.py", line 154, in <module>
ReadData(i)
File "C:\Users\..\videostuff.py", line 122, in ReadData
data = s.recv(DATA_SIZE)
OverflowError: long int too large to convert to int
There seems to be a problem with converting from a long int to an int when reading from the socket with the returned value. But why does this work with the print statements in place?!
Calling code:
i = ToInt(data_string.tolist(), 0)
# First byte tells how big the data wil be
if i > 4 and (i - 4) > DATA_SIZE:
DATA_SIZE = i - 4
# line 122
data = s.recv(DATA_SIZE)
All the codez:
import socket
from array import array
import Image
import StringIO
import sys
def ToInt(abyte0, i):
if(abyte0[i] >= 0):
j = abyte0[i]
#print "A " + str(j)
else:
j = 256 + abyte0[i]
if abyte0[i + 1] >= 0:
j = j + (abyte0[i + 1] * 256)
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 1]) * 256
if abyte0[i + 2] >= 0:
j = j+ abyte0[i + 2] * 256 * 256
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 2]) * 256 * 256
if abyte0[i + 3] >= 0:
j = j + abyte0[i + 3] * 256 * 256 * 256
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 3]) * 256 * 256 * 256
return j
def StrLen(abyte0):
for i in len(abyte0):
if abyte0[i] == 0:
return i
def StrLen(abyte0, i):
for j in len(abyte0):
if abyte0[i] == 0:
return i
else:
i = i + 1
def Connect(s):
out_header = array('B', [32, 0, 0, 0, 205, 0, 0, 0])
data = array('B', [0, 0, 0, 0, \
5, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0 \
])
#print 'sending data: '
#print out_header.tostring()
#print out_header.buffer_info()
#print struct.unpack('BBBBBBBBB', out_header)
s.send(out_header)
s.send(data)
def ReadHeader():
global DATA_SIZE
global DATA_TYPE
DATA_SIZE = 32
# Read the reply header
data = s.recv(HEADER_SIZE)
data_string = array('B', data)
i = ToInt(data_string.tolist(), 0)
# First byte tells how big the data wil be
if i > 4 and (i - 4) > DATA_SIZE:
DATA_SIZE = i - 4
print "DATA_SIZE is " + str(DATA_SIZE)
# Second byte tells what the data is
DATA_TYPE = data_string[4]
#if DATA_TYPE == 1:
# print "Dunno"
#elif DATA_TYPE == 106:
# print "MESSAGE"
#elif DATA_TYPE == 207:
# print "IMAGE"
#elif DATA_TYPE == 0:
# print "FALSE"
#else:
# print "ERROR"
def ReadData(i):
global DATA_SIZE
#if DATA_SIZE > sys.maxint:
# DATA_SIZE = sys.maxint
data = s.recv(DATA_SIZE)
data_string = array('B', data)
#afile = open("Dataz.txt", 'w')
#data_string.tofile(afile)
#print data_string
abyte0 = data_string.tolist()
#draw image
image_w = ToInt(abyte0, 0)
image_h = ToInt(abyte0, 4)
# should be around 9k
image_data_length = ToInt(abyte0, 72)
datas = data_string[76:]
file1 = open("Dataz.jpg", 'wb')
datas.tofile(file1)
file1.close()
#print "Length of image data is: " + str(len(datas))
#file = StringIO.StringIO(datas)
#file1 = open("Dataz1.jpg", 'rb')
#image = Image.open(file1)
#image.show()
#Global variables
TCP_IP = '192.168.1.106'
TCP_PORT = 17860
HEADER_SIZE = 8
DATA_SIZE = 32
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
#Starts channel 1
Connect(s)
ReadHeader()
#first data contains the channel name and status
data = s.recv(DATA_SIZE)
data_string = array('B', data)
# Second data should be first image
ReadHeader()
ReadData(0)
for i in range(1, 20):
ReadHeader()
ReadData(i)
s.close()
A:
If you pass socket.recv() a value larger than 2147483647 (hex 0x7fffffff) Python will attempt to use a long integer instead of a regular integer. Clearly your value for DATA_SIZE is considered to be larger than that.
The ToInt() code appears to be trying to build up an integer out of individual bytes, and likely you aren't doing the conversion properly (specifically the part where you try to handle negative values). Generally when converting code from a C-like language, and I'll include Java in that set here, you want to find a higher-level way to express the code than working with individual bytes and characters.
Try using the standard library struct module to do the conversion instead of working with bytes. Making sure you specify the proper byte order (big/little endian) to get correct results. For example, assuming your data is a 4-character string where the first character represents the smallest value, this would probably do:
>>> import struct
>>> i = struct.unpack('<L', '\x23\x45\x00\x73')[0]
>>> print i
1929397539
You can interpret and modify that by checking the documentation referenced above.
A:
Here's an example of the problem
if abyte0[i + 3] >= 0:
j = j + abyte0[i + 3] * 256 * 256 * 256
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 3]) * 256 * 256 * 256
Let's pretend j == 0 and abyte0 == ( 0, 0, 0, 0) and i == 0
>>> j + (256 + abyte0[i + 3]) * 256 * 256 * 256
4294967296L
The result is a long value. With or without the print statement, this statement is unlikely to be correct. The "Now that I have it working" part of the question is unlikely to have been completely true to begin with. That makes the "remove the print statements and I get an error" unlikely to be true, also.
|
python print statements fixes OverflowError
|
I'm hacking a security system DVR so I can add motion capture and other fun features in python (version 2.6). One of the functions I was able to decompile from java and convert to python was the following:
def ToInt(abyte0, i):
if(abyte0[i] >= 0):
j = abyte0[i]
print "A " + str(j)
else:
j = 256 + abyte0[i]
if abyte0[i + 1] >= 0:
j = j + (abyte0[i + 1] * 256)
print "A " + str(j)
else:
j = j + (256 + abyte0[i + 1]) * 256
if abyte0[i + 2] >= 0:
j = j+ abyte0[i + 2] * 256 * 256
print "A " + str(j)
else:
j = j + (256 + abyte0[i + 2]) * 256 * 256
if abyte0[i + 3] >= 0:
j = j + abyte0[i + 3] * 256 * 256 * 256
print "A " + str(j)
else:
j = j + (256 + abyte0[i + 3]) * 256 * 256 * 256
return j
I added print statements to it to see what was going on while I was figuring things out. Now that I have it working, I went back to remove the print statements and I get an error!
Traceback (most recent call last):
File "C:\Users\...\videostuff.py", line 154, in <module>
ReadData(i)
File "C:\Users\..\videostuff.py", line 122, in ReadData
data = s.recv(DATA_SIZE)
OverflowError: long int too large to convert to int
There seems to be a problem with converting from a long int to an int when reading from the socket with the returned value. But why does this work with the print statements in place?!
Calling code:
i = ToInt(data_string.tolist(), 0)
# First byte tells how big the data wil be
if i > 4 and (i - 4) > DATA_SIZE:
DATA_SIZE = i - 4
# line 122
data = s.recv(DATA_SIZE)
All the codez:
import socket
from array import array
import Image
import StringIO
import sys
def ToInt(abyte0, i):
if(abyte0[i] >= 0):
j = abyte0[i]
#print "A " + str(j)
else:
j = 256 + abyte0[i]
if abyte0[i + 1] >= 0:
j = j + (abyte0[i + 1] * 256)
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 1]) * 256
if abyte0[i + 2] >= 0:
j = j+ abyte0[i + 2] * 256 * 256
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 2]) * 256 * 256
if abyte0[i + 3] >= 0:
j = j + abyte0[i + 3] * 256 * 256 * 256
#print "A " + str(j)
else:
j = j + (256 + abyte0[i + 3]) * 256 * 256 * 256
return j
def StrLen(abyte0):
for i in len(abyte0):
if abyte0[i] == 0:
return i
def StrLen(abyte0, i):
for j in len(abyte0):
if abyte0[i] == 0:
return i
else:
i = i + 1
def Connect(s):
out_header = array('B', [32, 0, 0, 0, 205, 0, 0, 0])
data = array('B', [0, 0, 0, 0, \
5, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0 \
])
#print 'sending data: '
#print out_header.tostring()
#print out_header.buffer_info()
#print struct.unpack('BBBBBBBBB', out_header)
s.send(out_header)
s.send(data)
def ReadHeader():
global DATA_SIZE
global DATA_TYPE
DATA_SIZE = 32
# Read the reply header
data = s.recv(HEADER_SIZE)
data_string = array('B', data)
i = ToInt(data_string.tolist(), 0)
# First byte tells how big the data wil be
if i > 4 and (i - 4) > DATA_SIZE:
DATA_SIZE = i - 4
print "DATA_SIZE is " + str(DATA_SIZE)
# Second byte tells what the data is
DATA_TYPE = data_string[4]
#if DATA_TYPE == 1:
# print "Dunno"
#elif DATA_TYPE == 106:
# print "MESSAGE"
#elif DATA_TYPE == 207:
# print "IMAGE"
#elif DATA_TYPE == 0:
# print "FALSE"
#else:
# print "ERROR"
def ReadData(i):
global DATA_SIZE
#if DATA_SIZE > sys.maxint:
# DATA_SIZE = sys.maxint
data = s.recv(DATA_SIZE)
data_string = array('B', data)
#afile = open("Dataz.txt", 'w')
#data_string.tofile(afile)
#print data_string
abyte0 = data_string.tolist()
#draw image
image_w = ToInt(abyte0, 0)
image_h = ToInt(abyte0, 4)
# should be around 9k
image_data_length = ToInt(abyte0, 72)
datas = data_string[76:]
file1 = open("Dataz.jpg", 'wb')
datas.tofile(file1)
file1.close()
#print "Length of image data is: " + str(len(datas))
#file = StringIO.StringIO(datas)
#file1 = open("Dataz1.jpg", 'rb')
#image = Image.open(file1)
#image.show()
#Global variables
TCP_IP = '192.168.1.106'
TCP_PORT = 17860
HEADER_SIZE = 8
DATA_SIZE = 32
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
#Starts channel 1
Connect(s)
ReadHeader()
#first data contains the channel name and status
data = s.recv(DATA_SIZE)
data_string = array('B', data)
# Second data should be first image
ReadHeader()
ReadData(0)
for i in range(1, 20):
ReadHeader()
ReadData(i)
s.close()
|
[
"If you pass socket.recv() a value larger than 2147483647 (hex 0x7fffffff) Python will attempt to use a long integer instead of a regular integer. Clearly your value for DATA_SIZE is considered to be larger than that.\nThe ToInt() code appears to be trying to build up an integer out of individual bytes, and likely you aren't doing the conversion properly (specifically the part where you try to handle negative values). Generally when converting code from a C-like language, and I'll include Java in that set here, you want to find a higher-level way to express the code than working with individual bytes and characters.\nTry using the standard library struct module to do the conversion instead of working with bytes. Making sure you specify the proper byte order (big/little endian) to get correct results. For example, assuming your data is a 4-character string where the first character represents the smallest value, this would probably do:\n>>> import struct\n>>> i = struct.unpack('<L', '\\x23\\x45\\x00\\x73')[0]\n>>> print i\n1929397539\n\nYou can interpret and modify that by checking the documentation referenced above.\n",
"Here's an example of the problem\nif abyte0[i + 3] >= 0:\n j = j + abyte0[i + 3] * 256 * 256 * 256\n #print \"A \" + str(j)\nelse:\n j = j + (256 + abyte0[i + 3]) * 256 * 256 * 256\n\nLet's pretend j == 0 and abyte0 == ( 0, 0, 0, 0) and i == 0\n>>> j + (256 + abyte0[i + 3]) * 256 * 256 * 256\n4294967296L\n\nThe result is a long value. With or without the print statement, this statement is unlikely to be correct. The \"Now that I have it working\" part of the question is unlikely to have been completely true to begin with. That makes the \"remove the print statements and I get an error\" unlikely to be true, also.\n"
] |
[
4,
0
] |
[] |
[] |
[
"casting",
"python"
] |
stackoverflow_0001966456_casting_python.txt
|
Q:
Converting arrays between NumPy and JPype?
Does a library or script exist to convert between NumPy and JPype arrays?
A:
Doesn't
JArray(float, 1)(numpyarray)
work?
At least
JArray(float, 1)(numpyarray.tolist())
should work.
|
Converting arrays between NumPy and JPype?
|
Does a library or script exist to convert between NumPy and JPype arrays?
|
[
"Doesn't \nJArray(float, 1)(numpyarray)\n\nwork?\nAt least\nJArray(float, 1)(numpyarray.tolist())\n\nshould work.\n"
] |
[
3
] |
[] |
[] |
[
"java",
"numpy",
"python"
] |
stackoverflow_0001966253_java_numpy_python.txt
|
Q:
Why I can't call packagename.modulename.foo()?
In my working python directory I create:
packagename/__init__.py
packagename/modulename.py
test.py
In modulename.py I create some empty class:
class Someclass(object):
pass
in test.py:
import packagename
packagename.modulename.Someclass()
Why I can't call packagename.modulename.someclass() in test.py ?
AttributeError: 'module' object has no attribute 'modulename'
I understand that the right way is:
import packagename.modulename
or
from packagename import modulename
But I do not understand why I get this error in my case.
Update:
In other words is there any way to import a package's content with all modules in the distinct namespace?
I need correct pythonic expression for:
from packagename import * as mynamespace
A:
Python does not automatically recurse and import subpackages. When you say:
import packagename
That is all it imports. If you say:
import packagename.modulename
Then it first imports packagename, then imports packagename.modulename and assignes a reference to it as an attribute of packagename. Therefore, when you say in code:
packagename.modulename.Someclass()
Python is just using 100% normal attribute lookups. First lookup the packagename variable in the current namespace. Then lookup the modulename attribute of the packagename object. Then lookup the Someclass attribute of the modulename object.
If you neglected to import packagename.modulename, then there is plainly no attribute on packagename called modulename, and henceforth the AttributeError.
I suggest you pop onto the command line and import something, then use dir() to examine it. Then import a subpackage, and use dir() again. You will quickly see the difference.
Lastly, the syntax:
from packagename.modulename import SomePackage
Is essentially the same as this:
import packagename.modulename
SomePackage = packagename.modulename.SomePackage
(of course, it's implemented differently, but more or less the same result).
Does that help?
A:
If you had 100 modules in the "packagename" package, would you want them all to be imported automatically when you imported just the top-level name? That wouldn't usually be a good idea, so Python doesn't do it.
If you want to have that particular module imported automatically, just include it in the __init__.py like so:
from packagename import modulename
Alternatively, using Python 2.5 or 2.6:
from __future__ import absolute_import
from . import modulename
(In later versions, you can ditch the from __future__ part.)
Edit: there is no built-in mechanism to ask Python to import all possible submodules inside a package. That's not a common use case, and it's better handled explicitly by having your __init__.py import precisely those things that you want. It would be possible to put something together to do the job (using __import__() and such) but it is better in most cases just to explicitly import all submodules as described.
A:
Some packages are very large and importing everything within them would take a lot of time. It's better to offer fine granularity for imports, so the user only imports what he really needs.
|
Why I can't call packagename.modulename.foo()?
|
In my working python directory I create:
packagename/__init__.py
packagename/modulename.py
test.py
In modulename.py I create some empty class:
class Someclass(object):
pass
in test.py:
import packagename
packagename.modulename.Someclass()
Why I can't call packagename.modulename.someclass() in test.py ?
AttributeError: 'module' object has no attribute 'modulename'
I understand that the right way is:
import packagename.modulename
or
from packagename import modulename
But I do not understand why I get this error in my case.
Update:
In other words is there any way to import a package's content with all modules in the distinct namespace?
I need correct pythonic expression for:
from packagename import * as mynamespace
|
[
"Python does not automatically recurse and import subpackages. When you say:\nimport packagename\n\nThat is all it imports. If you say:\nimport packagename.modulename\n\nThen it first imports packagename, then imports packagename.modulename and assignes a reference to it as an attribute of packagename. Therefore, when you say in code:\npackagename.modulename.Someclass()\n\nPython is just using 100% normal attribute lookups. First lookup the packagename variable in the current namespace. Then lookup the modulename attribute of the packagename object. Then lookup the Someclass attribute of the modulename object.\nIf you neglected to import packagename.modulename, then there is plainly no attribute on packagename called modulename, and henceforth the AttributeError.\nI suggest you pop onto the command line and import something, then use dir() to examine it. Then import a subpackage, and use dir() again. You will quickly see the difference.\n\nLastly, the syntax:\nfrom packagename.modulename import SomePackage\n\nIs essentially the same as this:\nimport packagename.modulename\nSomePackage = packagename.modulename.SomePackage\n\n(of course, it's implemented differently, but more or less the same result).\nDoes that help?\n",
"If you had 100 modules in the \"packagename\" package, would you want them all to be imported automatically when you imported just the top-level name? That wouldn't usually be a good idea, so Python doesn't do it.\nIf you want to have that particular module imported automatically, just include it in the __init__.py like so:\nfrom packagename import modulename\n\nAlternatively, using Python 2.5 or 2.6:\nfrom __future__ import absolute_import\nfrom . import modulename\n\n(In later versions, you can ditch the from __future__ part.)\nEdit: there is no built-in mechanism to ask Python to import all possible submodules inside a package. That's not a common use case, and it's better handled explicitly by having your __init__.py import precisely those things that you want. It would be possible to put something together to do the job (using __import__() and such) but it is better in most cases just to explicitly import all submodules as described.\n",
"Some packages are very large and importing everything within them would take a lot of time. It's better to offer fine granularity for imports, so the user only imports what he really needs.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"import",
"package",
"python"
] |
stackoverflow_0001966783_import_package_python.txt
|
Q:
Python UDP socket port random, despite assignment
I have two simple Python files: client.py and server.py. The client simply sends the text you type to the server, via UDP socket.
The port assigned and listened to is 21567, BUT... the line reading:
print "\nReceived message '", data,"' from ", addr
in server.py outputs the addr to be something looking like this: ('127.0.0.1', 60471)
Now I don't understand why this seemingly random port is reported, the 60471 is random everytime the script is run. Can anyone please shed some light on this matter, why is it not saying 21567 like set in the code? Thanks!
The Python script file contents are as follows:
client.py
# Client program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg
# Send messages
while (1):
data = raw_input('>> ')
if not data:
break
else:
if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'....."
# Close socket
UDPSock.close()
server.py
# Server program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"' from ", addr
# Close socket
UDPSock.close()
A:
60471 is the client's port and 21567 is the server's port. They can't be the same: Any IP traffic has to declare its source address and port, and its destination address and port. The client port is usually a random number in the range 32768 to 65535. addr is telling you the client's address.
This is done so you can have multiple clients talking to the same server (i.e. IP address and port combination), and the streams can be disambiguated using the client port numbers, even with a connectionless protocol like UDP/IP.
A:
The port you are printing is that of the sender. The client's port is always random, stardard operating system mechanism. Just like a web server's port is 80, but when your computer connects to a server, you exit with a random port every time.
|
Python UDP socket port random, despite assignment
|
I have two simple Python files: client.py and server.py. The client simply sends the text you type to the server, via UDP socket.
The port assigned and listened to is 21567, BUT... the line reading:
print "\nReceived message '", data,"' from ", addr
in server.py outputs the addr to be something looking like this: ('127.0.0.1', 60471)
Now I don't understand why this seemingly random port is reported, the 60471 is random everytime the script is run. Can anyone please shed some light on this matter, why is it not saying 21567 like set in the code? Thanks!
The Python script file contents are as follows:
client.py
# Client program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket
UDPSock = socket(AF_INET,SOCK_DGRAM)
def_msg = "===Enter message to send to server===";
print "\n",def_msg
# Send messages
while (1):
data = raw_input('>> ')
if not data:
break
else:
if(UDPSock.sendto(data,addr)):
print "Sending message '",data,"'....."
# Close socket
UDPSock.close()
server.py
# Server program
from socket import *
# Set the socket parameters
host = "localhost"
port = 21567
buf = 1024
addr = (host,port)
# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"' from ", addr
# Close socket
UDPSock.close()
|
[
"60471 is the client's port and 21567 is the server's port. They can't be the same: Any IP traffic has to declare its source address and port, and its destination address and port. The client port is usually a random number in the range 32768 to 65535. addr is telling you the client's address.\nThis is done so you can have multiple clients talking to the same server (i.e. IP address and port combination), and the streams can be disambiguated using the client port numbers, even with a connectionless protocol like UDP/IP.\n",
"The port you are printing is that of the sender. The client's port is always random, stardard operating system mechanism. Just like a web server's port is 80, but when your computer connects to a server, you exit with a random port every time.\n"
] |
[
4,
2
] |
[] |
[] |
[
"python",
"sockets",
"udp"
] |
stackoverflow_0001967188_python_sockets_udp.txt
|
Q:
Why is "def InvalidArgsSpecified:" a syntax error?
I'm just starting to learn python... so bear with me please
Why is it giving me a Invalid Syntax error with this block of code
def InvalidArgsSpecified:
print ("*** Simtho Usage ***\n")
print ("-i Installs Local App,, include full path")
print ("-u Uninstalls Installed App,include ID or Name")
print ("-li Lists all installed Apps and their ID")
print ("-all Lists All Apps in Repository")
print ("-di Downloads and Installs App from repository, enter the title or id number")
print ("-dw Downloads and Installs Single App from a full link")
print ("-rmall Removes All Packages installed and removes Simtho itself\n")
print ("*** End of Simtho Usage ***")
sys.exit()
edit: Now its saying that it's undefined at line 9
Line 9 is
InvalidArgsSpecified()
A:
The syntax error is in the very first line, where you have:
def InvalidArgsSpecified:
change it to:
def InvalidArgsSpecified():
Those parentheses are mandatory in a def, even when there's nothing between them (just as parentheses are always used to call a function -- empty parentheses, in that case, if you're calling without arguments).
Edit: now the OP's getting an error for trying to call this function in line 9: since this function definition is more than 9 lines, it's probably getting called (from module top-level, rather than from within another function) before it's defined, in which case the simple fix is to call it only after it's defined. If it's anything subtler than that, we'll need to see the code to debug it for you!-)
A:
A function without arguments must still include brackets, e.g.:
def InvalidArgsSpecified():
|
Why is "def InvalidArgsSpecified:" a syntax error?
|
I'm just starting to learn python... so bear with me please
Why is it giving me a Invalid Syntax error with this block of code
def InvalidArgsSpecified:
print ("*** Simtho Usage ***\n")
print ("-i Installs Local App,, include full path")
print ("-u Uninstalls Installed App,include ID or Name")
print ("-li Lists all installed Apps and their ID")
print ("-all Lists All Apps in Repository")
print ("-di Downloads and Installs App from repository, enter the title or id number")
print ("-dw Downloads and Installs Single App from a full link")
print ("-rmall Removes All Packages installed and removes Simtho itself\n")
print ("*** End of Simtho Usage ***")
sys.exit()
edit: Now its saying that it's undefined at line 9
Line 9 is
InvalidArgsSpecified()
|
[
"The syntax error is in the very first line, where you have:\ndef InvalidArgsSpecified:\n\nchange it to:\ndef InvalidArgsSpecified():\n\nThose parentheses are mandatory in a def, even when there's nothing between them (just as parentheses are always used to call a function -- empty parentheses, in that case, if you're calling without arguments).\nEdit: now the OP's getting an error for trying to call this function in line 9: since this function definition is more than 9 lines, it's probably getting called (from module top-level, rather than from within another function) before it's defined, in which case the simple fix is to call it only after it's defined. If it's anything subtler than that, we'll need to see the code to debug it for you!-)\n",
"A function without arguments must still include brackets, e.g.:\ndef InvalidArgsSpecified():\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"function",
"python",
"syntax_error"
] |
stackoverflow_0001967336_function_python_syntax_error.txt
|
Q:
Delete the \n and following letters in the end of words in a list
How can I delete the \n and the following letters? Thanks a lot.
wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
for x in wordlist:
...?
A:
>>> import re
>>> wordlist = ['Schreiben\nEs', 'Schreiben', \
'Schreiben\nEventuell', 'Schreiben\nHaruki']
>>> [ re.sub("\n.*", "", word) for word in wordlist ]
['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']
Done via re.sub:
>>> help(re.sub)
1 Help on function sub in module re:
2
3 sub(pattern, repl, string, count=0)
4 Return the string obtained by replacing the leftmost
5 non-overlapping occurrences of the pattern in string by the
6 replacement repl. repl can be either a string or a callable;
7 if a callable, it's passed the match object and must return
8 a replacement string to be used.
A:
[w[:w.find('\n')] fow w in wordlist]
few tests:
$ python -m timeit -s "wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']" "[w[:w.find('\n')] for w in wordlist]"
100000 loops, best of 3: 2.03 usec per loop
$ python -m timeit -s "import re; wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']" "[re.sub('\n.*', '', w) for w in wordlist]"
10000 loops, best of 3: 17.5 usec per loop
$ python -m timeit -s "import re; RE = re.compile('\n.*'); wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']" "[RE.sub('', w) for w in wordlist]"
100000 loops, best of 3: 6.76 usec per loop
Edit:
The solution above is completely wrong (see the comment from Peter Hansen). here the corrected one:
def truncate(words, s):
for w in words:
i = w.find(s)
yield w[:i] if i != -1 else w
A:
You could use a regular expression to do so:
import re
wordlist = [re.sub("\n.*", "", word) for word in wordlist]
The regular expression \n.* matches the first \n and anything that might follow (.*) and replaces it with nothing.
A:
>>> wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
>>> [ i.split("\n")[0] for i in wordlist ]
['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']
|
Delete the \n and following letters in the end of words in a list
|
How can I delete the \n and the following letters? Thanks a lot.
wordlist = ['Schreiben\nEs', 'Schreiben', 'Schreiben\nEventuell', 'Schreiben\nHaruki']
for x in wordlist:
...?
|
[
">>> import re\n>>> wordlist = ['Schreiben\\nEs', 'Schreiben', \\\n 'Schreiben\\nEventuell', 'Schreiben\\nHaruki']\n>>> [ re.sub(\"\\n.*\", \"\", word) for word in wordlist ]\n['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']\n\nDone via re.sub:\n>>> help(re.sub)\n 1 Help on function sub in module re:\n 2 \n 3 sub(pattern, repl, string, count=0)\n 4 Return the string obtained by replacing the leftmost\n 5 non-overlapping occurrences of the pattern in string by the\n 6 replacement repl. repl can be either a string or a callable;\n 7 if a callable, it's passed the match object and must return\n 8 a replacement string to be used.\n\n",
"[w[:w.find('\\n')] fow w in wordlist]\n\nfew tests:\n$ python -m timeit -s \"wordlist = ['Schreiben\\nEs', 'Schreiben', 'Schreiben\\nEventuell', 'Schreiben\\nHaruki']\" \"[w[:w.find('\\n')] for w in wordlist]\"\n100000 loops, best of 3: 2.03 usec per loop\n$ python -m timeit -s \"import re; wordlist = ['Schreiben\\nEs', 'Schreiben', 'Schreiben\\nEventuell', 'Schreiben\\nHaruki']\" \"[re.sub('\\n.*', '', w) for w in wordlist]\"\n10000 loops, best of 3: 17.5 usec per loop\n$ python -m timeit -s \"import re; RE = re.compile('\\n.*'); wordlist = ['Schreiben\\nEs', 'Schreiben', 'Schreiben\\nEventuell', 'Schreiben\\nHaruki']\" \"[RE.sub('', w) for w in wordlist]\"\n100000 loops, best of 3: 6.76 usec per loop\n\nEdit:\nThe solution above is completely wrong (see the comment from Peter Hansen). here the corrected one:\ndef truncate(words, s):\n for w in words:\n i = w.find(s)\n yield w[:i] if i != -1 else w\n\n",
"You could use a regular expression to do so:\nimport re\nwordlist = [re.sub(\"\\n.*\", \"\", word) for word in wordlist]\n\nThe regular expression \\n.* matches the first \\n and anything that might follow (.*) and replaces it with nothing.\n",
">>> wordlist = ['Schreiben\\nEs', 'Schreiben', 'Schreiben\\nEventuell', 'Schreiben\\nHaruki']\n>>> [ i.split(\"\\n\")[0] for i in wordlist ]\n['Schreiben', 'Schreiben', 'Schreiben', 'Schreiben']\n\n"
] |
[
4,
3,
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001966495_python_string.txt
|
Q:
cut off empty spaces
How can i cut off the last empty space?
a = ['Hello ','everybody ','! ']
for i in range(len(a)):
a[i,-1]=''
print a
A:
To cut off only last (right) empty spaces, use rstrip() method. strip() removes spaces from both ends:
>>> s = " abc "
>>> s.rstrip()
' abc'
>>> s.strip()
'abc'
In your example:
>>> [s.rstrip() for s in ['Hello ','everybody ','! '] ]
['Hello', 'everybody', '!']
A:
Solution via list comprehension:
>>> a = ['Hello ','everybody ','! ']
>>> [ e.strip() for e in a ]
['Hello', 'everybody', '!']
Documentation: string.strip / string.rstrip, string.lstrip respectively
A:
print [x.strip() for x in a]
This is called list comprehension
A:
The list comprehension approaches mentioned above would be the Pythonic way to solve this problem but they don't alter the list itself (ie. a). If you want to change those, you'll have to iterate as you've done over the list and instead of your assignment do an
a[i] = a[i].rstrip() # For stripping off trailing whitespaces only.
This is of course, bad style and I would recommend the list comprehension based method as well.
A:
>>> a = ['Hello ','everybody ','! ']
>>> map(str.rstrip,a)
['Hello', 'everybody', '!']
>>> b = map(str.rstrip,a)
|
cut off empty spaces
|
How can i cut off the last empty space?
a = ['Hello ','everybody ','! ']
for i in range(len(a)):
a[i,-1]=''
print a
|
[
"To cut off only last (right) empty spaces, use rstrip() method. strip() removes spaces from both ends:\n>>> s = \" abc \"\n>>> s.rstrip()\n' abc'\n>>> s.strip()\n'abc'\n\nIn your example:\n>>> [s.rstrip() for s in ['Hello ','everybody ','! '] ]\n['Hello', 'everybody', '!']\n\n",
"Solution via list comprehension:\n>>> a = ['Hello ','everybody ','! ']\n>>> [ e.strip() for e in a ]\n['Hello', 'everybody', '!']\n\nDocumentation: string.strip / string.rstrip, string.lstrip respectively\n",
"print [x.strip() for x in a]\n\nThis is called list comprehension\n",
"The list comprehension approaches mentioned above would be the Pythonic way to solve this problem but they don't alter the list itself (ie. a). If you want to change those, you'll have to iterate as you've done over the list and instead of your assignment do an \na[i] = a[i].rstrip() # For stripping off trailing whitespaces only. \n\nThis is of course, bad style and I would recommend the list comprehension based method as well.\n",
">>> a = ['Hello ','everybody ','! ']\n>>> map(str.rstrip,a)\n['Hello', 'everybody', '!']\n>>> b = map(str.rstrip,a)\n\n"
] |
[
10,
5,
1,
1,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001966426_python_string.txt
|
Q:
When are function local python variables created?
When are function-local variables are created? For example, in the following code is dictionary d1 created each time the function f1 is called or only once when it is compiled?
def f1():
d1 = {1: 2, 3: 4}
return id(d1)
d2 = {1: 2, 3: 4}
def f2():
return id(d2)
Is it faster in general to define a dictionary within function scope or to define it globally (assuming the dictionary is used only in that function). I know it is slower to look up global symbols than local ones, but what if the dictionary is large?
Much python code I've seen seems to define these dictionaries globally, which would seem not to be optimal. But also in the case where you have a class with multiple 'encoding' methods, each with a unique (large-ish) lookup dictionary, it's awkward to have the code and data spread throughout the file.
A:
Local variables are created when assigned to, i.e., during the execution of the function.
If every execution of the function needs (and does not modify!-) the same dict, creating it once, before the function is ever called, is faster. As an alternative to a global variable, a fake argument with a default value is even (marginally) faster, since it's accessed as fast as a local variable but also created only once (at def time):
def f(x, y, _d={1:2, 3:4}):
I'm using the name _d, with a leading underscore, to point out that it's meant as a private implementation detail of the function. Nevertheless it's a bit fragile, as a bumbling calles might accidentally and erroneously pass three arguments (the third one would be bound as _d within the function, likely causing bugs), or the function's body might mistakenly alter _d, so this is only recommended as an optimization to use when profiling reveals it's really needed. A global dict is also subject to erroneous alterations, so, even though it's faster than buiding a local dict afresh on every call, you might still pick the latter possibility to achieve higher robustness (although the global dict solution, plus good unit tests to catch any "oops"es in the function, are the recommended alternative;-).
A:
If you look at the disassembly with the dis module you'll see that the creation and filling of d1 is done on every execution. Given that dictionaries are mutable this is unlikely to change anytime soon, at least until good escape analysis comes to Python virtual machines. On the other hand lookup of global constants will get speculatively optimized with the next generation of Python VM's such as unladen-swallow (the speculation part is that they are constant).
A:
Speed is relative to what you're doing. If you're writing a database-intensive application, I doubt your application is going to suffer one way or another from your choice of global versus local variables. Use a profiler to be sure. ;-)
As Alex noted, the locals are initialized when the function is called. As easy way to demonstrate this for yourself:
import random
def f():
d = [random.randint(1, 100), random.randint(100, 1000)]
print(d)
f()
f()
f()
|
When are function local python variables created?
|
When are function-local variables are created? For example, in the following code is dictionary d1 created each time the function f1 is called or only once when it is compiled?
def f1():
d1 = {1: 2, 3: 4}
return id(d1)
d2 = {1: 2, 3: 4}
def f2():
return id(d2)
Is it faster in general to define a dictionary within function scope or to define it globally (assuming the dictionary is used only in that function). I know it is slower to look up global symbols than local ones, but what if the dictionary is large?
Much python code I've seen seems to define these dictionaries globally, which would seem not to be optimal. But also in the case where you have a class with multiple 'encoding' methods, each with a unique (large-ish) lookup dictionary, it's awkward to have the code and data spread throughout the file.
|
[
"Local variables are created when assigned to, i.e., during the execution of the function.\nIf every execution of the function needs (and does not modify!-) the same dict, creating it once, before the function is ever called, is faster. As an alternative to a global variable, a fake argument with a default value is even (marginally) faster, since it's accessed as fast as a local variable but also created only once (at def time):\ndef f(x, y, _d={1:2, 3:4}):\n\nI'm using the name _d, with a leading underscore, to point out that it's meant as a private implementation detail of the function. Nevertheless it's a bit fragile, as a bumbling calles might accidentally and erroneously pass three arguments (the third one would be bound as _d within the function, likely causing bugs), or the function's body might mistakenly alter _d, so this is only recommended as an optimization to use when profiling reveals it's really needed. A global dict is also subject to erroneous alterations, so, even though it's faster than buiding a local dict afresh on every call, you might still pick the latter possibility to achieve higher robustness (although the global dict solution, plus good unit tests to catch any \"oops\"es in the function, are the recommended alternative;-).\n",
"If you look at the disassembly with the dis module you'll see that the creation and filling of d1 is done on every execution. Given that dictionaries are mutable this is unlikely to change anytime soon, at least until good escape analysis comes to Python virtual machines. On the other hand lookup of global constants will get speculatively optimized with the next generation of Python VM's such as unladen-swallow (the speculation part is that they are constant).\n",
"Speed is relative to what you're doing. If you're writing a database-intensive application, I doubt your application is going to suffer one way or another from your choice of global versus local variables. Use a profiler to be sure. ;-)\nAs Alex noted, the locals are initialized when the function is called. As easy way to demonstrate this for yourself:\nimport random\n\ndef f():\n d = [random.randint(1, 100), random.randint(100, 1000)]\n print(d)\n\nf()\nf()\nf()\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001967454_python.txt
|
Q:
Google App Engine - How do I split code into multiple files? (webapp)
I have a question about splitting up a main.py file.
right now, I have everything in my main.py. I have no other .py files. And I always have to scroll long lines of code before reaching the section I wish to edit.
How do I split it up?
(i'm going to have more than 20 pages, so that means the main.py will be HUGE if I don't split it up.
PS: also, I noticed that I had to setup the template values, template path, and call template.render each time. Any way of shortening them all?
Code:
# everything here in main.py
class MainPage(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Page2(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Page3(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication(
[('/', MainPage),
('/page2', Page2)
('/page3', Page3)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
A:
Splitting the code is no different than splitting code for any Python app - find a bunch of related code that you want to move to another file, move it to that file, and import it into the main handler file.
For example, you could move the Page2 code to page2.py, put
import page2
at the top of your file, and change your mapping to load /page2 from page2.Page2 (you might want to rename these classes in this case...
Alternatively, you could have separate .py files handle different (groups of) pages by editing the app.yaml file as described in Script Handlers.
You can wrap your template-handling code in a convenience function and call it, to reduce repeated code a little bit. You may be able to streamline the loading of the template values, but once you want to render, you could call a method something like
def render(template_file, template_values):
path = os.path.join(os.path.dirname(__file__), template_file)
self.response.out.write(template.render(path, template_values))
It's not much of a savings, but it's a little more readable. Probably you'd want to move render to a different file and import it where you want it.
A:
Define your classes in other .py files and use "import" to use them in your main.py. It is quite simple actually.
A:
thx for the input, really appreciate them.
as for grouping imports together, i tried to keep all app-engine related imports into a .py file called ext.py
Then I called it anywhere I wanted to use it by this line:
from ext import *
ext.py contains the following:
import os
# import from appengine's libs
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
# import models
from models import *
|
Google App Engine - How do I split code into multiple files? (webapp)
|
I have a question about splitting up a main.py file.
right now, I have everything in my main.py. I have no other .py files. And I always have to scroll long lines of code before reaching the section I wish to edit.
How do I split it up?
(i'm going to have more than 20 pages, so that means the main.py will be HUGE if I don't split it up.
PS: also, I noticed that I had to setup the template values, template path, and call template.render each time. Any way of shortening them all?
Code:
# everything here in main.py
class MainPage(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Page2(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Page3(webapp.RequestHandler):
def get(self):
# Models are queried here, results transferred to template_values
template_values = {
'value1': value1,
'value2': value2,
'value3': value3,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication(
[('/', MainPage),
('/page2', Page2)
('/page3', Page3)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
|
[
"Splitting the code is no different than splitting code for any Python app - find a bunch of related code that you want to move to another file, move it to that file, and import it into the main handler file.\nFor example, you could move the Page2 code to page2.py, put\nimport page2\n\nat the top of your file, and change your mapping to load /page2 from page2.Page2 (you might want to rename these classes in this case...\nAlternatively, you could have separate .py files handle different (groups of) pages by editing the app.yaml file as described in Script Handlers.\nYou can wrap your template-handling code in a convenience function and call it, to reduce repeated code a little bit. You may be able to streamline the loading of the template values, but once you want to render, you could call a method something like\ndef render(template_file, template_values):\n path = os.path.join(os.path.dirname(__file__), template_file)\n self.response.out.write(template.render(path, template_values))\n\nIt's not much of a savings, but it's a little more readable. Probably you'd want to move render to a different file and import it where you want it.\n",
"Define your classes in other .py files and use \"import\" to use them in your main.py. It is quite simple actually.\n",
"thx for the input, really appreciate them.\nas for grouping imports together, i tried to keep all app-engine related imports into a .py file called ext.py\nThen I called it anywhere I wanted to use it by this line:\nfrom ext import *\n\next.py contains the following:\nimport os\n\n# import from appengine's libs\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.ext import db\n\n# import models\nfrom models import *\n\n"
] |
[
22,
2,
0
] |
[] |
[] |
[
"google_app_engine",
"python",
"web_applications"
] |
stackoverflow_0001966974_google_app_engine_python_web_applications.txt
|
Q:
Return value of os.path in Python
For this code:
import os
a=os.path.join('dsa','wqqqq','ffff')
print a
print os.path.exists('dsa\wqqqq\ffff') #what situation this will be print True?
When will os.path.exists('what') print True?
A:
'dsa\wqqqq\ffff' does not mean what you probably think it does: \f, within a string, is an escape sequence and expands to the same character as chr(12) (ASCII "form feed").
So print os.path.exists('dsa\wqqqq\ffff') will print True if:
on Windows, there's a subdirectory dsa in the current working directory, and within it a file or subdirectory whose name is equal to the string `'wqqqq' + chr(12) + 'fff'
on Linux, Mac, etc, if there's a file or subdirectory in the current directory whose name is equal to the string `'dsa' + '\' + 'wqqqq' + chr(12) + 'fff'
They seem like two peculiar conditions to check, and that you actually want to check their combination depending on the platform seems even less likely.
More likely you might want to
print os.path.exists(os.path.join('dsa', 'wqqqq', 'ffff'))
which works cross-platform, printing True if in the current working directory there's a subdirectory dsa containing a subdirectory wqqqq containing a file or subdirectory ffff. This avoids messing with backslashes.
If you're keen to have your code perform this check only on Windows (and have very different semantics on all other platforms), you can use
print os.path.exists(r'dsa\wqqqq\ffff')
the leading r in the string literal tells the Python compiler to avoid interpreting backslashes in it (however, don't try to end such a literal with backslash, since the backslash is still taken to escape the quote). Or:
print os.path.exists('dsa\\wqqqq\\ffff')
doubling-up the backslashes works. Note, also, that:
print os.path.exists('dsa/wqqqq/ffff')
with normal slashes instead of backslashes, works just fine in BOTH Windows and elsewhere (which makes it particularly absurd to want to use backslashes here, unless one is deliberately trying to obtain a program that behaves weirdly on non-Windows machines).
The much-simpler other question which you ask in the text after your code is easier: os.path.exists('what'), on any platform, prints True if there is a file or subdirectory named what in the current working directory.
A:
Return True if path refers to an
existing path. Returns False for
broken symbolic links. On some
platforms, this function may return
False if permission is not granted to
execute os.stat() on the requested
file, even if the path physically
exists.
http://docs.python.org/library/os.path.html#os.path.exists
A:
It will print True if the path exists. Not sure what the confusion is, here. Not to be rude, but RTFM.
% mkdir -p dsa/wqqqq/ffff
% cat <<EOF | python
> import os
> a=os.path.join('dsa','wqqqq','ffff')
> print a
> print os.path.exists('dsa/wqqqq/ffff')
> EOF
dsa/wqqqq/ffff
True
|
Return value of os.path in Python
|
For this code:
import os
a=os.path.join('dsa','wqqqq','ffff')
print a
print os.path.exists('dsa\wqqqq\ffff') #what situation this will be print True?
When will os.path.exists('what') print True?
|
[
"'dsa\\wqqqq\\ffff' does not mean what you probably think it does: \\f, within a string, is an escape sequence and expands to the same character as chr(12) (ASCII \"form feed\").\nSo print os.path.exists('dsa\\wqqqq\\ffff') will print True if:\n\non Windows, there's a subdirectory dsa in the current working directory, and within it a file or subdirectory whose name is equal to the string `'wqqqq' + chr(12) + 'fff'\non Linux, Mac, etc, if there's a file or subdirectory in the current directory whose name is equal to the string `'dsa' + '\\' + 'wqqqq' + chr(12) + 'fff'\n\nThey seem like two peculiar conditions to check, and that you actually want to check their combination depending on the platform seems even less likely.\nMore likely you might want to\nprint os.path.exists(os.path.join('dsa', 'wqqqq', 'ffff'))\n\nwhich works cross-platform, printing True if in the current working directory there's a subdirectory dsa containing a subdirectory wqqqq containing a file or subdirectory ffff. This avoids messing with backslashes.\nIf you're keen to have your code perform this check only on Windows (and have very different semantics on all other platforms), you can use\nprint os.path.exists(r'dsa\\wqqqq\\ffff')\n\nthe leading r in the string literal tells the Python compiler to avoid interpreting backslashes in it (however, don't try to end such a literal with backslash, since the backslash is still taken to escape the quote). Or:\nprint os.path.exists('dsa\\\\wqqqq\\\\ffff')\n\ndoubling-up the backslashes works. Note, also, that:\nprint os.path.exists('dsa/wqqqq/ffff')\n\nwith normal slashes instead of backslashes, works just fine in BOTH Windows and elsewhere (which makes it particularly absurd to want to use backslashes here, unless one is deliberately trying to obtain a program that behaves weirdly on non-Windows machines).\nThe much-simpler other question which you ask in the text after your code is easier: os.path.exists('what'), on any platform, prints True if there is a file or subdirectory named what in the current working directory.\n",
"\nReturn True if path refers to an\n existing path. Returns False for\n broken symbolic links. On some\n platforms, this function may return\n False if permission is not granted to\n execute os.stat() on the requested\n file, even if the path physically\n exists.\n\nhttp://docs.python.org/library/os.path.html#os.path.exists\n",
"It will print True if the path exists. Not sure what the confusion is, here. Not to be rude, but RTFM.\n% mkdir -p dsa/wqqqq/ffff\n% cat <<EOF | python\n> import os\n> a=os.path.join('dsa','wqqqq','ffff')\n> print a\n> print os.path.exists('dsa/wqqqq/ffff')\n> EOF\ndsa/wqqqq/ffff\nTrue\n\n"
] |
[
8,
1,
0
] |
[] |
[] |
[
"path",
"python"
] |
stackoverflow_0001967643_path_python.txt
|
Q:
Is there any Visual Studio-like tool for creating GUIs for Python?
My girlfriend asked me if there was a tool (actually, an IDE) that would let her create her GUI visually and edit functions associated with GUI-related events with little effort.
For example, she wants to double-click a button she just created and immediately see (and edit) the code associated with that button's on-click event. I believe this is what she does in Visual Studio.
The toolkit doesn't matter. She just wants this funcionality.
Is there some tool that accomplishes this?
Thank you.
EDIT: Made the example look bold. Seemed no one was looking at it, and it's an important requirement.
A:
I would recommend based on your needs:
Qt Designer
wxGlade
Check this out:
http://wiki.python.org/moin/GuiProgramming
A:
For GTK+ there is Glade. Python can load interface files created with Glade. There are some tutorials on the net.
For Qt there is QtDesigner. PyQt manual covers how to use PyQt with QtDesigner.
As far as I know QtDesigner is integrated into some IDEs (e.g. Eclipse)
A:
Python(x,y) includes an installation of Eclipse with PyDev and QT Designer integrated. If you configure PyUIC to run from Eclipse (see this brief HOWTO) then, once the GUI has been designed, the framework code can be generated at the push of a button.
Admittedly this is not as easy or as polished as VS and there may be problems when it comes to refactoring the GUI ...
A:
http://www.codeplex.com/IronPythonStudio
A:
WxGlade. I'm not sure if you can do the click and edit code thing, but it comes pretty close.
A:
Qt Creator is pretty slick. It's for C++ coding only, but Qt manages to make that a bit easier.
|
Is there any Visual Studio-like tool for creating GUIs for Python?
|
My girlfriend asked me if there was a tool (actually, an IDE) that would let her create her GUI visually and edit functions associated with GUI-related events with little effort.
For example, she wants to double-click a button she just created and immediately see (and edit) the code associated with that button's on-click event. I believe this is what she does in Visual Studio.
The toolkit doesn't matter. She just wants this funcionality.
Is there some tool that accomplishes this?
Thank you.
EDIT: Made the example look bold. Seemed no one was looking at it, and it's an important requirement.
|
[
"I would recommend based on your needs:\n\nQt Designer\nwxGlade\n\nCheck this out:\nhttp://wiki.python.org/moin/GuiProgramming\n",
"For GTK+ there is Glade. Python can load interface files created with Glade. There are some tutorials on the net.\n\nFor Qt there is QtDesigner. PyQt manual covers how to use PyQt with QtDesigner.\nAs far as I know QtDesigner is integrated into some IDEs (e.g. Eclipse)\n",
"Python(x,y) includes an installation of Eclipse with PyDev and QT Designer integrated. If you configure PyUIC to run from Eclipse (see this brief HOWTO) then, once the GUI has been designed, the framework code can be generated at the push of a button.\nAdmittedly this is not as easy or as polished as VS and there may be problems when it comes to refactoring the GUI ...\n",
"http://www.codeplex.com/IronPythonStudio\n",
"WxGlade. I'm not sure if you can do the click and edit code thing, but it comes pretty close.\n",
"Qt Creator is pretty slick. It's for C++ coding only, but Qt manages to make that a bit easier.\n"
] |
[
8,
2,
2,
1,
0,
0
] |
[] |
[] |
[
"gtk",
"python",
"qt",
"visual_studio",
"wxwidgets"
] |
stackoverflow_0001967220_gtk_python_qt_visual_studio_wxwidgets.txt
|
Q:
Accessing a file relatively in Python if you do not know your starting point?
Hey. I've got a project in Python, whose directory layout is the following:
root
|-bin
|-conf
|-[project]
Python files in [project] need to be able to read configuration data from the 'conf' directory, but I cannot guarantee the location of root, plus it may be used on both Linux, Mac and Windows machines so I am trying to relatively address the conf directory from the root directory.
At the minute it's working with a dirty hack (from root/bin, particular python filename is 8 chars long):
path = os.path.abspath(__file__)[:-8]
os.chdir(path)
os.chdir("..")
[projectclass].config('config/scans.json') #for example
But this is particularly horrid and is giving me nightmares. Is there a better way to accomplish what I'm trying to achieve that doesn't feel so dirty? I feel like I'm missing something very obvious. Thanks in advance.
A:
Instead of:
path = os.path.abspath(__file__)[:-8]
use:
path = os.path.dirname(os.path.abspath(__file__))
See the docs here.
|
Accessing a file relatively in Python if you do not know your starting point?
|
Hey. I've got a project in Python, whose directory layout is the following:
root
|-bin
|-conf
|-[project]
Python files in [project] need to be able to read configuration data from the 'conf' directory, but I cannot guarantee the location of root, plus it may be used on both Linux, Mac and Windows machines so I am trying to relatively address the conf directory from the root directory.
At the minute it's working with a dirty hack (from root/bin, particular python filename is 8 chars long):
path = os.path.abspath(__file__)[:-8]
os.chdir(path)
os.chdir("..")
[projectclass].config('config/scans.json') #for example
But this is particularly horrid and is giving me nightmares. Is there a better way to accomplish what I'm trying to achieve that doesn't feel so dirty? I feel like I'm missing something very obvious. Thanks in advance.
|
[
"Instead of:\npath = os.path.abspath(__file__)[:-8]\n\nuse:\npath = os.path.dirname(os.path.abspath(__file__))\n\nSee the docs here.\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001967688_python.txt
|
Q:
How can you use a font file in GTK
I'm writing an open source program (key-train) in Python and GTK (with Cairo) and I would like to use some more attractive fonts. I was hoping that it would be possible to load a ttf font from within the program and just use it (instead of installing it), but I haven't been able to figure out how to do this.
A:
You might want to take a look at this feature request It shows a work-a-round if using cairo and freetype for the backend.
A:
You could use pango to set the ttf font:
#!/usr/bin/env python
import pango
import gtk
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
main_vbox = gtk.VBox(homogeneous=False,spacing=0)
window.add(main_vbox)
textview = gtk.TextView()
main_vbox.pack_start(textview,expand=False,fill=True,padding=0)
textbuffer = textview.get_buffer()
font_desc=pango.FontDescription('FreeSans Bold 64')
textview.modify_font(font_desc)
textbuffer.set_text('Hi Scott Kirkwood')
textview.show()
main_vbox.show()
window.show()
gtk.main()
|
How can you use a font file in GTK
|
I'm writing an open source program (key-train) in Python and GTK (with Cairo) and I would like to use some more attractive fonts. I was hoping that it would be possible to load a ttf font from within the program and just use it (instead of installing it), but I haven't been able to figure out how to do this.
|
[
"You might want to take a look at this feature request It shows a work-a-round if using cairo and freetype for the backend.\n",
"You could use pango to set the ttf font:\n#!/usr/bin/env python\nimport pango\nimport gtk\n\nwindow = gtk.Window(gtk.WINDOW_TOPLEVEL)\nmain_vbox = gtk.VBox(homogeneous=False,spacing=0)\nwindow.add(main_vbox)\ntextview = gtk.TextView()\nmain_vbox.pack_start(textview,expand=False,fill=True,padding=0)\ntextbuffer = textview.get_buffer()\nfont_desc=pango.FontDescription('FreeSans Bold 64')\ntextview.modify_font(font_desc)\ntextbuffer.set_text('Hi Scott Kirkwood')\ntextview.show()\nmain_vbox.show()\nwindow.show()\ngtk.main()\n\n"
] |
[
4,
0
] |
[] |
[] |
[
"fonts",
"gtk",
"linux",
"python"
] |
stackoverflow_0001967257_fonts_gtk_linux_python.txt
|
Q:
Why doesn't my code print `os.path`
For the code:
def a(x):
if x=='s':
__import__('os') #I think __import__ == import
print os.path
Why doesn't print a('os') print os.path?
My next question is: Why does the following code use __import__('some') instead of something like, a = __import__('os') ?
def import_module(name, package=None):
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name) #Why does it do this
return sys.modules[name] #Instead of `return __import__(name)`
A:
__import__ returns a module. It doesn't actually add anything to the current namespace.
You probably want to just use import os:
def a(x):
if x=='s':
import os
print os.path
a('s')
Alternatively, if you want to import the module as a string, you can explicitly assign it:
def a(x):
if x=='s':
os = __import__('os')
print os.path
a('s')
A:
@statictype.org's answer is correct (__import__ does not bind any name in local namespace), but why ever do you want to print <module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc'> or something equally weird depending on your platform?! That's what print os.path will do once you've fixed your bug -- what are you trying to accomplish by that?!
You sure you don't want something completely different such as print os.environ['PATH'] or print os.getcwd()...?
Edit: to answer the OP's follow-on question:
__import__(name)#why it do this
return sys.modules[name]
__import__ does install what's importing in sys.modules; this is better than
return __import__(name)
if name contains one or more .s (dots): in that case, __import__ returns the top-level module, but sys.modules has the real thing. For example:
return __import__('foo.bar')
is equivalent to
__import__('foo.bar')
return sys.modules['foo']
not as one might think to
__import__('foo.bar')
return sys.modules['foo.bar']
|
Why doesn't my code print `os.path`
|
For the code:
def a(x):
if x=='s':
__import__('os') #I think __import__ == import
print os.path
Why doesn't print a('os') print os.path?
My next question is: Why does the following code use __import__('some') instead of something like, a = __import__('os') ?
def import_module(name, package=None):
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name) #Why does it do this
return sys.modules[name] #Instead of `return __import__(name)`
|
[
"__import__ returns a module. It doesn't actually add anything to the current namespace.\nYou probably want to just use import os:\ndef a(x):\n if x=='s':\n import os\n print os.path\na('s')\n\nAlternatively, if you want to import the module as a string, you can explicitly assign it:\ndef a(x):\n if x=='s':\n os = __import__('os')\n print os.path\na('s')\n\n",
"@statictype.org's answer is correct (__import__ does not bind any name in local namespace), but why ever do you want to print <module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/posixpath.pyc'> or something equally weird depending on your platform?! That's what print os.path will do once you've fixed your bug -- what are you trying to accomplish by that?!\nYou sure you don't want something completely different such as print os.environ['PATH'] or print os.getcwd()...?\nEdit: to answer the OP's follow-on question:\n__import__(name)#why it do this\nreturn sys.modules[name]\n\n__import__ does install what's importing in sys.modules; this is better than\nreturn __import__(name)\n\nif name contains one or more .s (dots): in that case, __import__ returns the top-level module, but sys.modules has the real thing. For example:\nreturn __import__('foo.bar')\n\nis equivalent to\n__import__('foo.bar')\nreturn sys.modules['foo']\n\nnot as one might think to\n__import__('foo.bar')\nreturn sys.modules['foo.bar']\n\n"
] |
[
11,
5
] |
[] |
[] |
[
"import",
"module",
"python"
] |
stackoverflow_0001967702_import_module_python.txt
|
Q:
Python string concatenation Idiom. Need Clarification.
From http://jaynes.colorado.edu/PythonIdioms.html
"Build strings as a list and use
''.join at the end. join is a string
method called on the separator, not
the list. Calling it from the empty
string concatenates the pieces with no
separator, which is a Python quirk and
rather surprising at first. This is
important: string building with + is
quadratic time instead of linear! If
you learn one idiom, learn this one.
Wrong: for s in strings: result += s
Right: result = ''.join(strings)"
I'm not sure why this is true. If I have some strings I want to join them, for me it isn't intuitively better to me to put them in a list then call ''.join. Doesn't putting them into a list create some overhead? To Clarify...
Python Command Line:
>>> str1 = 'Not'
>>> str2 = 'Cool'
>>> str3 = ''.join([str1, ' ', str2]) #The more efficient way **A**
>>> print str3
Not Cool
>>> str3 = str1 + ' ' + str2 #The bad way **B**
>>> print str3
Not Cool
Is A really linear time and B is quadratic time?
A:
Yes. For the examples you chose the importance isn't clear because you only have two very short strings so the append would probably be faster.
But every time you do a + b with strings in Python it causes a new allocation and then copies all the bytes from a and b into the new string. If you do this in a loop with lots of strings these bytes have to be copied again, and again, and again and each time the amount that has to be copied gets longer. This gives the quadratic behaviour.
On the other hand, creating a list of strings doesn't copy the contents of the strings - it just copies the references. This is incredibly fast, and runs in linear time. The join method then makes just one memory allocation and copies each string into the correct position only once. This also takes only linear time.
So yes, do use the ''.join idiom if you are potentially dealing with a large number of strings. For just two strings it doesn't matter.
If you need more convincing, try it for yourself creating a string from 10M characters:
>>> chars = ['a'] * 10000000
>>> r = ''
>>> for c in chars: r += c
>>> print len(r)
Compared with:
>>> chars = ['a'] * 10000000
>>> r = ''.join(chars)
>>> print len(r)
The first method takes about 10 seconds. The second takes under 1 second.
A:
Repeated concatenation is quadratic because it's Schlemiel the Painter's Algorithm (beware that some implementations will optimize this away so that it is not quadratic). join avoids this because it takes the entire list of strings, allocates the necessary space and does the concatenation in one pass.
A:
When you code s1 + s2, Python needs to allocate a new string object, copy all characters of s1 into it, then after that all characters of s2. This trivial operation does not bear quadratic time costs: the cost is O(len(s1) + len(s2)) (plus a constant for allocation, but that doesn't figure in big-O;-).
However, consider the code in the quote you're giving: for s in strings: result += s.
Here, every time a new s is added, all the previous ones have to be first copied into the newly allocated space for result (strings are immutable, so the new allocation and copy must take place). Suppose you have N strings of length L: you'll copy L characters the first time, then 2 * L the second time, then 3 * L the third time... in all, that makes it L * N * (N+1) / 2 characters getting copied... so, yep, it's quadratic in N.
In some other cases, a quadratic algorithm may be faster than a linear one for small-enough values of N (because the multipliers and constant fixed-costs may be much smaller); but that's not the case here because allocations are costly (both directly, and indirectly because of the likelihood of fragmenting memory). In comparison, the overheads of accumulating the strings into a list is essentially negligible.
A:
Joel writes about this in Back to Basics.
A:
It's not obvious if you're referring to the same thing as other people. This optimization is important when you have many strings, say M of length N. Then
A
x = ''.join(strings) # Takes M*N operations
B
x = ''
for s in strings:
x = x + s # Takes N + 2*N + ... + M*N operations
Unless optimized away by the implementation, yes, A is linear in the total length T = M*N and B is T*T / N which is always worse and roughly quadratic if M >> N.
Now why it is actually quite intuitive to join: when you say "I have some strings" this typically can be formalized by saying that you have an iterator that returns strings. Now, this is exactly what you pass to "string".join()
|
Python string concatenation Idiom. Need Clarification.
|
From http://jaynes.colorado.edu/PythonIdioms.html
"Build strings as a list and use
''.join at the end. join is a string
method called on the separator, not
the list. Calling it from the empty
string concatenates the pieces with no
separator, which is a Python quirk and
rather surprising at first. This is
important: string building with + is
quadratic time instead of linear! If
you learn one idiom, learn this one.
Wrong: for s in strings: result += s
Right: result = ''.join(strings)"
I'm not sure why this is true. If I have some strings I want to join them, for me it isn't intuitively better to me to put them in a list then call ''.join. Doesn't putting them into a list create some overhead? To Clarify...
Python Command Line:
>>> str1 = 'Not'
>>> str2 = 'Cool'
>>> str3 = ''.join([str1, ' ', str2]) #The more efficient way **A**
>>> print str3
Not Cool
>>> str3 = str1 + ' ' + str2 #The bad way **B**
>>> print str3
Not Cool
Is A really linear time and B is quadratic time?
|
[
"Yes. For the examples you chose the importance isn't clear because you only have two very short strings so the append would probably be faster.\nBut every time you do a + b with strings in Python it causes a new allocation and then copies all the bytes from a and b into the new string. If you do this in a loop with lots of strings these bytes have to be copied again, and again, and again and each time the amount that has to be copied gets longer. This gives the quadratic behaviour.\nOn the other hand, creating a list of strings doesn't copy the contents of the strings - it just copies the references. This is incredibly fast, and runs in linear time. The join method then makes just one memory allocation and copies each string into the correct position only once. This also takes only linear time.\nSo yes, do use the ''.join idiom if you are potentially dealing with a large number of strings. For just two strings it doesn't matter.\nIf you need more convincing, try it for yourself creating a string from 10M characters:\n>>> chars = ['a'] * 10000000\n>>> r = ''\n>>> for c in chars: r += c\n>>> print len(r)\n\nCompared with:\n>>> chars = ['a'] * 10000000\n>>> r = ''.join(chars)\n>>> print len(r)\n\nThe first method takes about 10 seconds. The second takes under 1 second. \n",
"Repeated concatenation is quadratic because it's Schlemiel the Painter's Algorithm (beware that some implementations will optimize this away so that it is not quadratic). join avoids this because it takes the entire list of strings, allocates the necessary space and does the concatenation in one pass.\n",
"When you code s1 + s2, Python needs to allocate a new string object, copy all characters of s1 into it, then after that all characters of s2. This trivial operation does not bear quadratic time costs: the cost is O(len(s1) + len(s2)) (plus a constant for allocation, but that doesn't figure in big-O;-).\nHowever, consider the code in the quote you're giving: for s in strings: result += s.\nHere, every time a new s is added, all the previous ones have to be first copied into the newly allocated space for result (strings are immutable, so the new allocation and copy must take place). Suppose you have N strings of length L: you'll copy L characters the first time, then 2 * L the second time, then 3 * L the third time... in all, that makes it L * N * (N+1) / 2 characters getting copied... so, yep, it's quadratic in N.\nIn some other cases, a quadratic algorithm may be faster than a linear one for small-enough values of N (because the multipliers and constant fixed-costs may be much smaller); but that's not the case here because allocations are costly (both directly, and indirectly because of the likelihood of fragmenting memory). In comparison, the overheads of accumulating the strings into a list is essentially negligible.\n",
"Joel writes about this in Back to Basics.\n",
"It's not obvious if you're referring to the same thing as other people. This optimization is important when you have many strings, say M of length N. Then \nA \nx = ''.join(strings) # Takes M*N operations \n\nB\nx = ''\nfor s in strings:\n x = x + s # Takes N + 2*N + ... + M*N operations\n\nUnless optimized away by the implementation, yes, A is linear in the total length T = M*N and B is T*T / N which is always worse and roughly quadratic if M >> N. \nNow why it is actually quite intuitive to join: when you say \"I have some strings\" this typically can be formalized by saying that you have an iterator that returns strings. Now, this is exactly what you pass to \"string\".join()\n"
] |
[
14,
6,
4,
1,
0
] |
[] |
[] |
[
"idioms",
"performance",
"python"
] |
stackoverflow_0001967723_idioms_performance_python.txt
|
Q:
Are there other Type in addition to the class to be called by hasattr
For code:
class a(object):
a='aaa'
b=a()
print hasattr(a,'a')
print hasattr(b,'a')
who can be called by hasattr except 'class somebody'?
Thanks!
A:
You can call hasattr with any object as the first argument (and any string as the second argument): it just returns False if that object does not have an attribute by that name ("having" an attribute of course includes possibly inheriting or synthesizing it; hasattr(x,'y') is True if and only if accessing x.y would not raise an exception -- that's how it works internally: it tries getattr and catches the exception if any).
A:
Accordingly to the Python documentation you must pass an object as parameter of the hasttr() function.
hasattr(object, name): The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)
|
Are there other Type in addition to the class to be called by hasattr
|
For code:
class a(object):
a='aaa'
b=a()
print hasattr(a,'a')
print hasattr(b,'a')
who can be called by hasattr except 'class somebody'?
Thanks!
|
[
"You can call hasattr with any object as the first argument (and any string as the second argument): it just returns False if that object does not have an attribute by that name (\"having\" an attribute of course includes possibly inheriting or synthesizing it; hasattr(x,'y') is True if and only if accessing x.y would not raise an exception -- that's how it works internally: it tries getattr and catches the exception if any).\n",
"Accordingly to the Python documentation you must pass an object as parameter of the hasttr() function. \n\nhasattr(object, name): The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001967730_python.txt
|
Q:
Parse Facebook feed datetime in python?
I am reading a Facebook updates feed using the python library 'feedparser'.
I loop through the collection of entries in my Django templates, and display the results.
The updated field is returned in a big long string, of some format I am unfamiliar with.
Tue, 01 Dec 2009 23:55:52 +0000
How can I...
A) Use a Django filter to clean the date time in the for loop on the template.
...or...
B) Parse the date and format the updated date in the view, esentially cleaning the date in the collection of entries before it is iterated over in the view.
NOTE: I have tried both approaches. Django's date filter does't recognize it, and the iso8601 library I tried to parse the string didn't either.
Anybody have any experience with this? Thanks for your help!
UPDATE:
Using the updated_parsed value from feedparser in a Django template didn't work so well. But a Django snippet of a filter for this very thing already exists!**
Django Snippet: http://www.djangosnippets.org/snippets/1595/
A:
Use entries[i].updated_parsed instead of entries[i].updated, and feedparser will return a parsed 9-tuple for you. (Documentation)
Then build a datetime object and pass it to Django or format to a string by yourself.
There is a similar question here.
A:
This worked but wasn't what my final solution ended up becoming.
This solution iterates over the feed entries collection I get back from Facebook. I then parse the datetime and set the updated property to that new datetime. (Also, ignoring the +0000)
for entry in feed.entries:
entry.updated = datetime.strptime(entry.updated, "%a, %d %b %Y %H:%M:%S +0000")
The entries collection is returned to the template which I can now use the Django 'date' filter to format the date.
|
Parse Facebook feed datetime in python?
|
I am reading a Facebook updates feed using the python library 'feedparser'.
I loop through the collection of entries in my Django templates, and display the results.
The updated field is returned in a big long string, of some format I am unfamiliar with.
Tue, 01 Dec 2009 23:55:52 +0000
How can I...
A) Use a Django filter to clean the date time in the for loop on the template.
...or...
B) Parse the date and format the updated date in the view, esentially cleaning the date in the collection of entries before it is iterated over in the view.
NOTE: I have tried both approaches. Django's date filter does't recognize it, and the iso8601 library I tried to parse the string didn't either.
Anybody have any experience with this? Thanks for your help!
UPDATE:
Using the updated_parsed value from feedparser in a Django template didn't work so well. But a Django snippet of a filter for this very thing already exists!**
Django Snippet: http://www.djangosnippets.org/snippets/1595/
|
[
"Use entries[i].updated_parsed instead of entries[i].updated, and feedparser will return a parsed 9-tuple for you. (Documentation)\nThen build a datetime object and pass it to Django or format to a string by yourself.\nThere is a similar question here.\n",
"This worked but wasn't what my final solution ended up becoming.\nThis solution iterates over the feed entries collection I get back from Facebook. I then parse the datetime and set the updated property to that new datetime. (Also, ignoring the +0000)\nfor entry in feed.entries:\n entry.updated = datetime.strptime(entry.updated, \"%a, %d %b %Y %H:%M:%S +0000\")\n\nThe entries collection is returned to the template which I can now use the Django 'date' filter to format the date.\n"
] |
[
4,
2
] |
[] |
[] |
[
"datetime",
"django",
"facebook",
"feedparser",
"python"
] |
stackoverflow_0001967801_datetime_django_facebook_feedparser_python.txt
|
Q:
How to use C++ lib from python
I would like to know how to use python to make calls to a C++ library called libwpd to read word perfect files and build python objects from them, but I have no experience with C++ or calling C++ functions from python, and I don't understand how to figure out what the output of these library functions would be. So that's really two questions: 1) how to call C++ functions from python, and 2) how to figure out what the output of these functions would be--namely, the result of the WPDocument::parse function (see http://www.abisource.com/~uwog/libwpd/) and how to use it in my python code. The function appears to return an object WPDResult, but I can't figure out what it does or how I would use it.
I looked into SWIG briefly, and it looks promising. Thoughts?
A:
Checkout ctypes. It's part of the standard Python library set. I can't speak to it's use with C++, but I suspect it will work nicely.
A:
The Boost.Python library allows easy interoperability between C++ and Python.
The tutorial shows how to wrap C++ functions and classes to use them from Python.
|
How to use C++ lib from python
|
I would like to know how to use python to make calls to a C++ library called libwpd to read word perfect files and build python objects from them, but I have no experience with C++ or calling C++ functions from python, and I don't understand how to figure out what the output of these library functions would be. So that's really two questions: 1) how to call C++ functions from python, and 2) how to figure out what the output of these functions would be--namely, the result of the WPDocument::parse function (see http://www.abisource.com/~uwog/libwpd/) and how to use it in my python code. The function appears to return an object WPDResult, but I can't figure out what it does or how I would use it.
I looked into SWIG briefly, and it looks promising. Thoughts?
|
[
"Checkout ctypes. It's part of the standard Python library set. I can't speak to it's use with C++, but I suspect it will work nicely.\n",
"The Boost.Python library allows easy interoperability between C++ and Python.\nThe tutorial shows how to wrap C++ functions and classes to use them from Python.\n"
] |
[
2,
2
] |
[] |
[] |
[
"python",
"swig",
"wordperfect"
] |
stackoverflow_0001967755_python_swig_wordperfect.txt
|
Q:
Simulate mouse click/Detect color under cursor in Python
I am very new to python. I am trying to write a program that will click the mouse at (x, y), move it to (a, b), and then wait until the color under the mouse is a certain color, lets say #fff. When it is that color, it clicks again and then repeats.
I cannot find a good API for mouse related stuff for python.
A:
The API for simulating mouse events depends on your platform. I don't know any cross-platform solution.
On Windows, you can access the Win32 API thanks to ctypes. see mouse_event on MSDN. You may also be interested by pywinauto
For getting the color under the mouse, you need the mouse position. See GetCursorPos on MSDN. Then if your app has an API for getting the color at this position you can use it. If not, you can try to grab a small portion of the screen around the cursor and to use PIL for getting the colors of every pixel in this area. I think that PIL screen capture is only working on Windows paltform but I am not sure.
I am using the following function for a similar need:
def grab_main_color(self, rect, max_colors=256):
"""returns a tuple with the RGB value of the most present color in the given rect"""
img=ImageGrab.grab(rect)
colors = img.getcolors(max_colors)
max_occurence, most_present = 0, 0
try:
for c in colors:
if c[0] > max_occurence:
(max_occurence, most_present) = c
return most_present
except TypeError:
raise Exception("Too many colors in the given rect")
|
Simulate mouse click/Detect color under cursor in Python
|
I am very new to python. I am trying to write a program that will click the mouse at (x, y), move it to (a, b), and then wait until the color under the mouse is a certain color, lets say #fff. When it is that color, it clicks again and then repeats.
I cannot find a good API for mouse related stuff for python.
|
[
"The API for simulating mouse events depends on your platform. I don't know any cross-platform solution. \nOn Windows, you can access the Win32 API thanks to ctypes. see mouse_event on MSDN. You may also be interested by pywinauto\nFor getting the color under the mouse, you need the mouse position. See GetCursorPos on MSDN. Then if your app has an API for getting the color at this position you can use it. If not, you can try to grab a small portion of the screen around the cursor and to use PIL for getting the colors of every pixel in this area. I think that PIL screen capture is only working on Windows paltform but I am not sure.\nI am using the following function for a similar need:\ndef grab_main_color(self, rect, max_colors=256):\n \"\"\"returns a tuple with the RGB value of the most present color in the given rect\"\"\"\n img=ImageGrab.grab(rect)\n colors = img.getcolors(max_colors)\n max_occurence, most_present = 0, 0\n try:\n for c in colors:\n if c[0] > max_occurence:\n (max_occurence, most_present) = c\n return most_present\n except TypeError:\n raise Exception(\"Too many colors in the given rect\")\n\n"
] |
[
9
] |
[
"if you're on Windows, then, for this kind of thing, you really want to try autohotkey. It's not python, but it is extremely powerful for doing this kind of thing on a Windows machine. The user community is extremely helpful, also. Check out their \"ask for help\" forum.\n"
] |
[
-1
] |
[
"colors",
"mouse",
"python"
] |
stackoverflow_0001967096_colors_mouse_python.txt
|
Q:
i don't know why django do this,it is about os.stat
What is the benefits of doing so:
import os
ST_MODE = 0
ST_INO = 1
ST_DEV = 2
ST_NLINK = 3
ST_UID = 4
ST_GID = 5
ST_SIZE = 6
ST_ATIME = 7
ST_MTIME = 8
ST_CTIME = 9
# Extract bits from the mode
def S_IMODE(mode):
return mode & 07777
def S_IFMT(mode):
return mode & 0170000
# Constants used as S_IFMT() for various file types
# (not all are implemented on all systems)
S_IFDIR = 0040000
S_IFCHR = 0020000
S_IFBLK = 0060000
S_IFREG = 0100000
S_IFIFO = 0010000
S_IFLNK = 0120000
S_IFSOCK = 0140000
# Functions to test for each file type
def S_ISDIR(mode):
return S_IFMT(mode) == S_IFDIR
def isdir(path):
"""Test whether a path is a directory"""
try:
st = os.stat(path)
except os.error:
return False
return S_ISDIR(st.st_mode)#this code ,why
thanks
A:
The benefits? I imagine one of them (a 'negative' one) is to stop the code from trying to process directories as regular files. If you run code such as:
myprog *
the shell will change that * into a list of all files within the current directory (including subdirectories, pipes, device nodes and all sorts of other special files), equivalent to:
myprog mydir1 mydir2 myfile1.jpg myfile2.txt mynamedpipe1
Testing to see whether one of the arguments is a non-regular file is vital to ensure you only process the types of files you want. You don't want to (for example) open a pipe file for input and read until end of file since end of file will only occur when the other end of the pipe closes it. This will look like your program has frozen.
Another possibility (a 'positive' one) is to ensure something that the program expects to be a directory (such as a temporary directory or configuration file directory) actually is a directory.
It's because of the UNIX philosophy - everything is a file and, if you only want certain types of files, you have to filter them yourself.
The way in which this works is that stat returns all sorts of wonderful information about a file and one of those pieces of information is its mode. In this mode, certain bits are set to indicate what type of file it is.
The S_ISDIR function tests for a specific combination of bits indicating that the file is a directory and returns true in that case. It returns false if either those bits aren't set to indicate a directory or if the file does not exist.
|
i don't know why django do this,it is about os.stat
|
What is the benefits of doing so:
import os
ST_MODE = 0
ST_INO = 1
ST_DEV = 2
ST_NLINK = 3
ST_UID = 4
ST_GID = 5
ST_SIZE = 6
ST_ATIME = 7
ST_MTIME = 8
ST_CTIME = 9
# Extract bits from the mode
def S_IMODE(mode):
return mode & 07777
def S_IFMT(mode):
return mode & 0170000
# Constants used as S_IFMT() for various file types
# (not all are implemented on all systems)
S_IFDIR = 0040000
S_IFCHR = 0020000
S_IFBLK = 0060000
S_IFREG = 0100000
S_IFIFO = 0010000
S_IFLNK = 0120000
S_IFSOCK = 0140000
# Functions to test for each file type
def S_ISDIR(mode):
return S_IFMT(mode) == S_IFDIR
def isdir(path):
"""Test whether a path is a directory"""
try:
st = os.stat(path)
except os.error:
return False
return S_ISDIR(st.st_mode)#this code ,why
thanks
|
[
"The benefits? I imagine one of them (a 'negative' one) is to stop the code from trying to process directories as regular files. If you run code such as:\nmyprog *\n\nthe shell will change that * into a list of all files within the current directory (including subdirectories, pipes, device nodes and all sorts of other special files), equivalent to:\nmyprog mydir1 mydir2 myfile1.jpg myfile2.txt mynamedpipe1\n\nTesting to see whether one of the arguments is a non-regular file is vital to ensure you only process the types of files you want. You don't want to (for example) open a pipe file for input and read until end of file since end of file will only occur when the other end of the pipe closes it. This will look like your program has frozen.\nAnother possibility (a 'positive' one) is to ensure something that the program expects to be a directory (such as a temporary directory or configuration file directory) actually is a directory.\nIt's because of the UNIX philosophy - everything is a file and, if you only want certain types of files, you have to filter them yourself.\nThe way in which this works is that stat returns all sorts of wonderful information about a file and one of those pieces of information is its mode. In this mode, certain bits are set to indicate what type of file it is.\nThe S_ISDIR function tests for a specific combination of bits indicating that the file is a directory and returns true in that case. It returns false if either those bits aren't set to indicate a directory or if the file does not exist.\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001968272_python.txt
|
Q:
Can a standalone web application built with cherrypy be compiled?
I want to build a web application that stands completely by itself, apache not required. Is cherrypy a good solution, and can this be compiled with something like py2exe?
A:
Python is a scripting language and is not usually compiled. What you are talking about is packaging your scripts into an exe (via p2exe), bundled with the relative modules and an interpreter.
This is possible with many scripts, including CherryPy, as p2exe basically sticks all your scripts together in one place, then executes it with the interpreter. This link will allow you to build your application into an exe. I would however recommend that you use pyinstaller instead, as I have found it to be much easier.
This question shows that you can daemonize CherryPy, and from the page of CherryPy ->
Your CherryPy powered web applications
are in fact stand-alone Python
applications embedding their own
multi-threaded web server. You can
deploy them anywhere you can run
Python applications. Apache is not
required
So yes you can deploy CherryPy, self-contained without Apache. CherryPy seems to be a fine solution.
A:
You are basically describing web2py.
|
Can a standalone web application built with cherrypy be compiled?
|
I want to build a web application that stands completely by itself, apache not required. Is cherrypy a good solution, and can this be compiled with something like py2exe?
|
[
"Python is a scripting language and is not usually compiled. What you are talking about is packaging your scripts into an exe (via p2exe), bundled with the relative modules and an interpreter.\nThis is possible with many scripts, including CherryPy, as p2exe basically sticks all your scripts together in one place, then executes it with the interpreter. This link will allow you to build your application into an exe. I would however recommend that you use pyinstaller instead, as I have found it to be much easier.\nThis question shows that you can daemonize CherryPy, and from the page of CherryPy -> \n\nYour CherryPy powered web applications\n are in fact stand-alone Python\n applications embedding their own\n multi-threaded web server. You can\n deploy them anywhere you can run\n Python applications. Apache is not\n required\n\nSo yes you can deploy CherryPy, self-contained without Apache. CherryPy seems to be a fine solution.\n",
"You are basically describing web2py.\n"
] |
[
1,
0
] |
[] |
[] |
[
"cherrypy",
"python"
] |
stackoverflow_0001967705_cherrypy_python.txt
|
Q:
How can i create a melody? Is there any sound-module?
I am confused because there are a lot of programms. But i am looking something like this. I will type a melody like "a4 c3 h3 a2" etc. and then i want to hear this. Does anybody know what i am looking for?
thanks in advance
A:
computing frequencies from note name is easy. each half-note is 2^(1/12) away from the preceding note, 440 Hz is A4.
if by any chance you are on windows, you may try this piece of code, which plays a song through the PC speaker:
import math
import winsound
import time
labels = ['a','a#','b','c','c#','d','d#','e','f','f#','g','g#']
# name is the complete name of a note (label + octave). the parameter
# n is the number of half-tone from A4 (e.g. D#1 is -42, A3 is -12, A5 is 12)
name = lambda n: labels[n%len(labels)] + str(int((n+(9+4*12))/12))
# the frequency of a note. the parameter n is the number of half-tones
# from a4, which has a frequency of 440Hz, and is our reference note.
freq = lambda n: int(440*(math.pow(2,1/12)**n))
# a dictionnary associating note frequencies to note names
notes = {name(n): freq(n) for n in range(-42,60)}
# the period expressed in second, computed from a tempo in bpm
period = lambda tempo: 1/(tempo/60)
# play each note in sequence through the PC speaker at the given tempo
def play(song, tempo):
for note in song.lower().split():
if note in notes.keys():
winsound.Beep(notes[note], int(period(tempo)*1000))
else:
time.sleep(period(tempo))
# "au clair de la lune"!! 'r' is a rest
play( 'c4 c4 C4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '
'c4 C4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '
'd4 d4 d4 d4 A3 r a3 r d4 c4 B3 a3 g3 r r r '
'c4 c4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r ', 180 )
(please note that i am using python 3.x, you may need to adapt some part of the code in order to use it on python 2.x.)
ho, by the way, i used abcdefg as a scale, but you will surely find the way to use h instead of b.
A:
One outside option is JFugue as shown here (with Groovy). Note that you would use Jython instead of Python, which hopefully is within bounds as an answer.
A:
you could use any library that produces MIDI output, in case of .net I'd recommend
the one created by Stephen Toub from Microsoft(can't find from where i got it, but google for it.)
A:
Check this out: http://www.algorithm.co.il/blogs/index.php/pytuner/
It's a very similar projet and looks like a very decent reference.
|
How can i create a melody? Is there any sound-module?
|
I am confused because there are a lot of programms. But i am looking something like this. I will type a melody like "a4 c3 h3 a2" etc. and then i want to hear this. Does anybody know what i am looking for?
thanks in advance
|
[
"computing frequencies from note name is easy. each half-note is 2^(1/12) away from the preceding note, 440 Hz is A4. \nif by any chance you are on windows, you may try this piece of code, which plays a song through the PC speaker:\nimport math\nimport winsound\nimport time\n\nlabels = ['a','a#','b','c','c#','d','d#','e','f','f#','g','g#']\n# name is the complete name of a note (label + octave). the parameter\n# n is the number of half-tone from A4 (e.g. D#1 is -42, A3 is -12, A5 is 12)\nname = lambda n: labels[n%len(labels)] + str(int((n+(9+4*12))/12))\n# the frequency of a note. the parameter n is the number of half-tones\n# from a4, which has a frequency of 440Hz, and is our reference note.\nfreq = lambda n: int(440*(math.pow(2,1/12)**n))\n\n# a dictionnary associating note frequencies to note names\nnotes = {name(n): freq(n) for n in range(-42,60)}\n\n# the period expressed in second, computed from a tempo in bpm\nperiod = lambda tempo: 1/(tempo/60)\n\n# play each note in sequence through the PC speaker at the given tempo\ndef play(song, tempo):\n for note in song.lower().split():\n if note in notes.keys():\n winsound.Beep(notes[note], int(period(tempo)*1000))\n else:\n time.sleep(period(tempo))\n\n# \"au clair de la lune\"!! 'r' is a rest\nplay( 'c4 c4 C4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '\n 'c4 C4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '\n 'd4 d4 d4 d4 A3 r a3 r d4 c4 B3 a3 g3 r r r '\n 'c4 c4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r ', 180 )\n\n(please note that i am using python 3.x, you may need to adapt some part of the code in order to use it on python 2.x.)\nho, by the way, i used abcdefg as a scale, but you will surely find the way to use h instead of b.\n",
"One outside option is JFugue as shown here (with Groovy). Note that you would use Jython instead of Python, which hopefully is within bounds as an answer.\n",
"you could use any library that produces MIDI output, in case of .net I'd recommend\n the one created by Stephen Toub from Microsoft(can't find from where i got it, but google for it.)\n",
"Check this out: http://www.algorithm.co.il/blogs/index.php/pytuner/\nIt's a very similar projet and looks like a very decent reference.\n"
] |
[
8,
3,
2,
1
] |
[] |
[] |
[
"audio",
"python"
] |
stackoverflow_0001967040_audio_python.txt
|
Q:
Python with MySQL on Windows: installation errors
I tried to run the following command, in the folder of my Django project:
$ python manage.py dbshell
It shows me this error:
$python manage.py dbshell
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\lib\site-packages\django\core\management\__init__.py", line
362, in execute_manager
utility.execute()
File "C:\Python25\lib\site-packages\django\core\management\__init__.py", line
303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 195,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 222,
in execute
output = self.handle(*args, **options)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 351,
in handle
return self.handle_noargs(**options)
File "C:\Python25\lib\site-packages\django\core\management\commands\dbshell.py
", line 9, in handle_noargs
from django.db import connection
File "C:\Python25\lib\site-packages\django\db\__init__.py", line 41, in <modul
e>
backend = load_backend(settings.DATABASE_ENGINE)
File "C:\Python25\lib\site-packages\django\db\__init__.py", line 17, in load_b
ackend
return import_module('.base', 'django.db.backends.%s' % backend_name)
File "C:\Python25\Lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
__import__(name)
File "C:\Python25\lib\site-packages\django\db\backends\mysql\base.py", line 13
, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No mo
dule named MySQLdb
First question is, why does Python not simply include this MySQLdb module?
OK, just fine, try to search to solve this message.
I have looked around stackoverflow.com for installing this module but did not have a good result.
Download this module at: http://sourceforge.net/projects/mysql-python/
Comes to the installation of this module on my Windows Vista system.
After the extraction of the package, I run the cmd prompt to continue with the installation:
$ python setup.py install
Again it showed me one other message:
D:\SOFTWARE\PROGRAMMING\MySQL-python-1.2.3c1>python setup.py install
Traceback (most recent call last):
File "setup.py", line 5, in <module>
from setuptools import setup, Extension
ImportError: No module named setuptools
Playing around with this error message, I know that there is the ez_setup.py within the package:
$python ez_setup.py
It seems that everything is OK:
D:\SOFTWARE\PROGRAMMING\MySQL-python-1.2.3c1>python ez_setup.py
Downloading http://pypi.python.org/packages/2.5/s/setuptools/setuptools-0.6c9-py
2.5.egg
Processing setuptools-0.6c9-py2.5.egg
Copying setuptools-0.6c9-py2.5.egg to c:\python25\lib\site-packages
Adding setuptools 0.6c9 to easy-install.pth file
Installing easy_install-script.py script to C:\Python25\Scripts
Installing easy_install.exe script to C:\Python25\Scripts
Installing easy_install-2.5-script.py script to C:\Python25\Scripts
Installing easy_install-2.5.exe script to C:\Python25\Scripts
Installed c:\python25\lib\site-packages\setuptools-0.6c9-py2.5.egg
Processing dependencies for setuptools==0.6c9
Finished processing dependencies for setuptools==0.6c9
Now comes back to the setup.py to install again:
$python setup.py install
It again gave me one other error message:
D:\SOFTWARE\PROGRAMMING\MySQL-python-1.2.3c1>python setup.py install
running install
running bdist_egg
....
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-2.5\MySQLdb\constants
running build_ext
error: Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible binaries.
Visual Studio 2003 was not found on this system. If you have Cygwin installed,
you can try compiling with MingW32, by passing "-c mingw32" to setup.py.
How can I fix this problem?
A:
Did you try looking here: http://sourceforge.net/projects/mysql-python/files/
That is the download area of MySQLdb project, it has nothing to do with django, so your question is incorrect - django does not make switching database backends hard, you just change one line. And of course, your python installation should support that database first, so by downloading binary package for Windows from the link I gave above (chose correct version to match your version of python) you can avoid all the hassle of compiling the source release.
Most probably you need either MySQL-python-1.2.2.win32-py2.5.exe or MySQL-python-1.2.2.win32-py2.4.exe
A:
Uh, this isn't Django, this is you downloading some unspecified Python environment and expecting it to magically do everything exactly the way you wanted it to. Find a good tutorial on this and follow the instructions.
BTW, this is a very helpful forum, but giving no specifics and then delivering a non-question with an attitude is not a good way to get people to feel helpful.
A:
I once had the same problem running Python and MySQL on the same computer. Like the guys/gals said above, Python does not come with built-in support for MySQL, so you will need to download the connectors.
The link given above by @kibitzer will most likely not work on Windows successfully, so go here to download a copy of the connector that works with windows. It comes with installer and no need to run setup.py script manually.
|
Python with MySQL on Windows: installation errors
|
I tried to run the following command, in the folder of my Django project:
$ python manage.py dbshell
It shows me this error:
$python manage.py dbshell
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "C:\Python25\lib\site-packages\django\core\management\__init__.py", line
362, in execute_manager
utility.execute()
File "C:\Python25\lib\site-packages\django\core\management\__init__.py", line
303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 195,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 222,
in execute
output = self.handle(*args, **options)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 351,
in handle
return self.handle_noargs(**options)
File "C:\Python25\lib\site-packages\django\core\management\commands\dbshell.py
", line 9, in handle_noargs
from django.db import connection
File "C:\Python25\lib\site-packages\django\db\__init__.py", line 41, in <modul
e>
backend = load_backend(settings.DATABASE_ENGINE)
File "C:\Python25\lib\site-packages\django\db\__init__.py", line 17, in load_b
ackend
return import_module('.base', 'django.db.backends.%s' % backend_name)
File "C:\Python25\Lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
__import__(name)
File "C:\Python25\lib\site-packages\django\db\backends\mysql\base.py", line 13
, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No mo
dule named MySQLdb
First question is, why does Python not simply include this MySQLdb module?
OK, just fine, try to search to solve this message.
I have looked around stackoverflow.com for installing this module but did not have a good result.
Download this module at: http://sourceforge.net/projects/mysql-python/
Comes to the installation of this module on my Windows Vista system.
After the extraction of the package, I run the cmd prompt to continue with the installation:
$ python setup.py install
Again it showed me one other message:
D:\SOFTWARE\PROGRAMMING\MySQL-python-1.2.3c1>python setup.py install
Traceback (most recent call last):
File "setup.py", line 5, in <module>
from setuptools import setup, Extension
ImportError: No module named setuptools
Playing around with this error message, I know that there is the ez_setup.py within the package:
$python ez_setup.py
It seems that everything is OK:
D:\SOFTWARE\PROGRAMMING\MySQL-python-1.2.3c1>python ez_setup.py
Downloading http://pypi.python.org/packages/2.5/s/setuptools/setuptools-0.6c9-py
2.5.egg
Processing setuptools-0.6c9-py2.5.egg
Copying setuptools-0.6c9-py2.5.egg to c:\python25\lib\site-packages
Adding setuptools 0.6c9 to easy-install.pth file
Installing easy_install-script.py script to C:\Python25\Scripts
Installing easy_install.exe script to C:\Python25\Scripts
Installing easy_install-2.5-script.py script to C:\Python25\Scripts
Installing easy_install-2.5.exe script to C:\Python25\Scripts
Installed c:\python25\lib\site-packages\setuptools-0.6c9-py2.5.egg
Processing dependencies for setuptools==0.6c9
Finished processing dependencies for setuptools==0.6c9
Now comes back to the setup.py to install again:
$python setup.py install
It again gave me one other error message:
D:\SOFTWARE\PROGRAMMING\MySQL-python-1.2.3c1>python setup.py install
running install
running bdist_egg
....
copying MySQLdb\constants\CLIENT.py -> build\lib.win32-2.5\MySQLdb\constants
running build_ext
error: Python was built with Visual Studio 2003;
extensions must be built with a compiler than can generate compatible binaries.
Visual Studio 2003 was not found on this system. If you have Cygwin installed,
you can try compiling with MingW32, by passing "-c mingw32" to setup.py.
How can I fix this problem?
|
[
"Did you try looking here: http://sourceforge.net/projects/mysql-python/files/\nThat is the download area of MySQLdb project, it has nothing to do with django, so your question is incorrect - django does not make switching database backends hard, you just change one line. And of course, your python installation should support that database first, so by downloading binary package for Windows from the link I gave above (chose correct version to match your version of python) you can avoid all the hassle of compiling the source release. \nMost probably you need either MySQL-python-1.2.2.win32-py2.5.exe or MySQL-python-1.2.2.win32-py2.4.exe\n",
"Uh, this isn't Django, this is you downloading some unspecified Python environment and expecting it to magically do everything exactly the way you wanted it to. Find a good tutorial on this and follow the instructions.\nBTW, this is a very helpful forum, but giving no specifics and then delivering a non-question with an attitude is not a good way to get people to feel helpful.\n",
"I once had the same problem running Python and MySQL on the same computer. Like the guys/gals said above, Python does not come with built-in support for MySQL, so you will need to download the connectors. \nThe link given above by @kibitzer will most likely not work on Windows successfully, so go here to download a copy of the connector that works with windows. It comes with installer and no need to run setup.py script manually.\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001964448_mysql_python.txt
|
Q:
How does the Python conditional operator workaround work?
From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
I couldn't understand how this code works; can anyone explain me how actually the code is working? I am also interested to know why the ternary operator doesn't exist; any references or links about this will be ore useful.
I'm running Python 2.6.4 on Windows Vista.
A:
Python has a construct that is sort of like the ternary operator in C, et al. It works something like this:
my_var = "Retired" if age > 65 else "Working"
and is equivalent to this C code:
my_var = age > 65 ? "Retired" : "Working";
As for how the code you posted works, let's step through it:
("Working","Retired")
creates a 2-tuple (an immutable list) with the element "Working" at index 0, and "Retired" at index 1.
var>65
returns True if var is greater than 65, False if not. When applied to an index, it is converted into 1 (True) or 0 (False). Thus, this boolean value provides an index into the tuple created on the same line.
Why hasn't Python always had a ternary operator? The simple answer is that Guido van Rossum, the author of Python, didn't like/didn't want it, apparently believing that it was an unnecessary construct that could lead to confusing code (and anyone who's seen massively-nested ternary operators in C can probably agree). But for Python 2.5, he relented and added the grammar seen above.
A:
Python (2.5 and above) does indeed have a syntax for what you are looking for:
x = foo if condition else bar
If condition is True, x will be set to foo, otherwise it will be set to bar.
Examples:
>>> age = 68
>>> x = 'Retired' if age > 65 else 'Working'
>>> x
'Retired'
>>> age = 35
>>> y = 'Retired' if age > 65 else 'Working'
>>> y
'Working'
A:
because True casts to 1 and False casts to 0 so if var = 70
("Working","Retired")[var>65]
becomes
("Working", "Retired")[1]
a nice little shortcut ... but I find it can be a little confusing with anything but a simple condition, so I would go with TM's suggestion
"Retired" if var > 65 else "Working"
A:
indexing into a list
The use of
[expression_when_false, expression_when_true][condition] # or
(expression_when_false, expression_when_true)[condition]
takes advantage of the fact that in Python True equals (but isn't!) 1 and False equals (but isn't!) 0. The expression above constructs a list of two elements, and uses the result of condition to index in the list and return only one expression. The drawback of this method is that both expressions are evaluated.
and-or shortcuts
Since the creation of Python, there was a form of this operation:
condition and expression_when_true or expression_when_false
This takes a shortcut and evaluates only one expression, but has a bug-prone drawback: the expression_when_true must not evaluate to a non-true value, otherwise the result is expression_when_false. and and or are "short-circuiting" in Python, and the following rules apply:
a and b #→ a if a is false, else b
a or b #→ a if a is true, else b
If condition is false, then expression_when_true is never evaluated and the result is expression_when_false. OTOH, if condition is true, then the result is the result of (expression_when_true or expression_when_false); consult the table above.
ternary conditional operator
Of course, since Python 2.5, there is a ternary conditional operator:
expression_when_true if condition else expression_when_false
The strange (if you are accustomed to the C-like ternary conditional operator) order of the operands is attributed to many things; the general intention is that condition should be true most of the time, so that the most common output comes first and is most visible.
A:
Short-circuit boolean expressions
There is also an option to short-circuit logical operations:
>>> (2+2 == 4) and "Yes" or "No"
'Yes'
>>> (2+2 == 5) and "Yes" or "No"
'No'
In your example:
>>> (int(raw_input("Age: ")) > 65) and "Retired" or "Working"
Age: 20
'Working'
>>> (int(raw_input("Age: ")) > 65) and "Retired" or "Working"
Age: 70
'Retired'
Read more about this technique in Charming Python: Functional Programming in Python, Part 1.
A:
In Python 2.6 and up:
print "You should be {0}.".format("retired" if var>65 else "working")
In Python 3.1 and up:
print ("You should be {}.".format("retired" if var>65 else "working"))
A:
in the code that you posted the following line is emulating ternary:
status = ("Working","Retired")[var>65]
here tuple ("Working","Retired") accessed with an index [var>65] which evaluates to either True (1) or False (0). When it's accessed with index 0, status will be 'Working'; if index is 1 then it'll be ``Retired'`. It's a fairly obscure way to do conditional assignment, use the normal ternary syntax that was introduced in py2.5 as was said.
A:
this is the form with the python ternary operator
def val():
var = float(raw_input("Age:"))
status = "Retired" if var > 65 else "Working"
print "You should be:",status
the code you showed is a bit tricky: it creates a two elements tuple whose elements are at position 0 and 1. to select the right element it uses a condition which return a boolean but booleans in python are integers so you can use it as special indexes (they can be either 0 or 1).
A:
There was originally no ternary operator because "Explicit is better than implicit", and it was seen as unpythonic. I don't like python's ternary op too much, either, but it exists:
x = foo if condition else bar
as shown by TM.
As for status = ("Working","Retired")[var>65],
var > 65 returns a boolean value: either True or False; however, Python treats boolean types quite weakly: True is 1 and False is 0 in some contexts. You can check it out by doing >>> True == 1.
A:
status = ("Working","Retired")[var>65]
This line works as a ternary operator because the expression var>65 returns 1 or 0, depending on whether var is bigger than 65 or not. So if var>65, then the line becomes this:
status = ("Working","Retired")[1]
that is, the second element of the sequence ("Working","Retired"). It looks odd but not if you write it like this instead:
status_sequence = ("Working","Retired")
status = status_sequence[1]
so status = "Retired".
Similarly, if var<=65 then it becomes
status = ("Working","Retired")[0]
and status = "Working".
A:
Only the "status =" line of that code implements something like the ternary operator.
status = ("Working","Retired")[var>65]
This creates a two-element tuple, with strings 'Working' at index 0, and 'Retired' at index 1. Following this, it indexes into that tuple to pick one of the two items, using the results of the expression var > 65.
This expression will return True (equivalent to 1, thus picking 'Retired') if the value of var is greater than 65. Otherwise it will return False (equivalent to 0, thus picking 'Working').
There is a key difference between this approach and the ternary operator, however, although it doesn't matter in your particular example. With the tuple-indexing approach, both values are evaluated but only one is returned. With the ternary operator, only one of the two values is actually evaluated; this is referred to as "short-circuit" behaviour. It can matter in cases like this:
status = funcA() if var > 65 else funcB()
status = (funcB(), funcA())[var > 65]
In the first case, either funcA() is called or funcB() is called, but never both. In the latter case, both are called first, and the results are stored in the tuple -- then only one is picked and the tuple is discarded.
This is especially important to understand if either funcA() or funcB() have "side-effects", meaning they change other data as they execute.
A:
trying to give a complete answer based on the answers given here.
the way you found (please don't use this one because it is not very readable):
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
using the python 2.5+ syntax:
def val():
var = float(raw_input("Age:"))
status = "Working" if var>65 else "Retired"
print "You should be:",status
using the other common method still preferred by some people:
def val():
var = float(raw_input("Age:"))
status = var>65 and "Working" or "Retired"
print "You should be:",status
i personally tend to use the last since the order of the operands is the same as the C ternary operator.
EDIT:
found some problems with the last approach (thx Roberto Bonvallet).
from wikipedia:
this code would break if op1 could be
a "falsy" value (None, False, 0, an
empty sequence or collection, …) as
the expression would return op2
(whether it was truthy or falsy)
instead of the (falsy) op1
so my final suggestion would be to use the 2.5+ ternary operator since it is simple, readable and offers short-circuit behavior.
|
How does the Python conditional operator workaround work?
|
From what I have read, I found that a built-in ternary operator does not exist (I will be happy to know more about it.).
I found the following code as a substitute:
def val():
var = float(raw_input("Age:"))
status = ("Working","Retired")[var>65]
print "You should be:",status
I couldn't understand how this code works; can anyone explain me how actually the code is working? I am also interested to know why the ternary operator doesn't exist; any references or links about this will be ore useful.
I'm running Python 2.6.4 on Windows Vista.
|
[
"Python has a construct that is sort of like the ternary operator in C, et al. It works something like this:\nmy_var = \"Retired\" if age > 65 else \"Working\"\n\nand is equivalent to this C code:\nmy_var = age > 65 ? \"Retired\" : \"Working\";\n\nAs for how the code you posted works, let's step through it:\n(\"Working\",\"Retired\")\n\ncreates a 2-tuple (an immutable list) with the element \"Working\" at index 0, and \"Retired\" at index 1.\nvar>65\n\nreturns True if var is greater than 65, False if not. When applied to an index, it is converted into 1 (True) or 0 (False). Thus, this boolean value provides an index into the tuple created on the same line.\nWhy hasn't Python always had a ternary operator? The simple answer is that Guido van Rossum, the author of Python, didn't like/didn't want it, apparently believing that it was an unnecessary construct that could lead to confusing code (and anyone who's seen massively-nested ternary operators in C can probably agree). But for Python 2.5, he relented and added the grammar seen above.\n",
"Python (2.5 and above) does indeed have a syntax for what you are looking for:\nx = foo if condition else bar\n\nIf condition is True, x will be set to foo, otherwise it will be set to bar.\nExamples:\n>>> age = 68\n>>> x = 'Retired' if age > 65 else 'Working'\n>>> x\n'Retired'\n>>> age = 35\n>>> y = 'Retired' if age > 65 else 'Working'\n>>> y\n'Working'\n\n",
"because True casts to 1 and False casts to 0 so if var = 70\n(\"Working\",\"Retired\")[var>65]\n\nbecomes\n(\"Working\", \"Retired\")[1]\n\na nice little shortcut ... but I find it can be a little confusing with anything but a simple condition, so I would go with TM's suggestion\n\"Retired\" if var > 65 else \"Working\"\n\n",
"indexing into a list\nThe use of\n[expression_when_false, expression_when_true][condition] # or\n(expression_when_false, expression_when_true)[condition]\n\ntakes advantage of the fact that in Python True equals (but isn't!) 1 and False equals (but isn't!) 0. The expression above constructs a list of two elements, and uses the result of condition to index in the list and return only one expression. The drawback of this method is that both expressions are evaluated.\nand-or shortcuts\nSince the creation of Python, there was a form of this operation:\ncondition and expression_when_true or expression_when_false\n\nThis takes a shortcut and evaluates only one expression, but has a bug-prone drawback: the expression_when_true must not evaluate to a non-true value, otherwise the result is expression_when_false. and and or are \"short-circuiting\" in Python, and the following rules apply:\na and b #→ a if a is false, else b\na or b #→ a if a is true, else b\n\nIf condition is false, then expression_when_true is never evaluated and the result is expression_when_false. OTOH, if condition is true, then the result is the result of (expression_when_true or expression_when_false); consult the table above.\nternary conditional operator\nOf course, since Python 2.5, there is a ternary conditional operator:\nexpression_when_true if condition else expression_when_false\n\nThe strange (if you are accustomed to the C-like ternary conditional operator) order of the operands is attributed to many things; the general intention is that condition should be true most of the time, so that the most common output comes first and is most visible.\n",
"Short-circuit boolean expressions\nThere is also an option to short-circuit logical operations:\n>>> (2+2 == 4) and \"Yes\" or \"No\"\n'Yes'\n>>> (2+2 == 5) and \"Yes\" or \"No\"\n'No'\n\nIn your example:\n>>> (int(raw_input(\"Age: \")) > 65) and \"Retired\" or \"Working\"\nAge: 20\n'Working'\n>>> (int(raw_input(\"Age: \")) > 65) and \"Retired\" or \"Working\"\nAge: 70\n'Retired'\n\nRead more about this technique in Charming Python: Functional Programming in Python, Part 1.\n",
"In Python 2.6 and up:\nprint \"You should be {0}.\".format(\"retired\" if var>65 else \"working\")\n\nIn Python 3.1 and up:\nprint (\"You should be {}.\".format(\"retired\" if var>65 else \"working\"))\n\n",
"in the code that you posted the following line is emulating ternary:\nstatus = (\"Working\",\"Retired\")[var>65]\n\nhere tuple (\"Working\",\"Retired\") accessed with an index [var>65] which evaluates to either True (1) or False (0). When it's accessed with index 0, status will be 'Working'; if index is 1 then it'll be ``Retired'`. It's a fairly obscure way to do conditional assignment, use the normal ternary syntax that was introduced in py2.5 as was said.\n",
"this is the form with the python ternary operator\ndef val():\n var = float(raw_input(\"Age:\"))\n status = \"Retired\" if var > 65 else \"Working\"\n print \"You should be:\",status\n\nthe code you showed is a bit tricky: it creates a two elements tuple whose elements are at position 0 and 1. to select the right element it uses a condition which return a boolean but booleans in python are integers so you can use it as special indexes (they can be either 0 or 1).\n",
"There was originally no ternary operator because \"Explicit is better than implicit\", and it was seen as unpythonic. I don't like python's ternary op too much, either, but it exists:\nx = foo if condition else bar\n\nas shown by TM.\nAs for status = (\"Working\",\"Retired\")[var>65], \nvar > 65 returns a boolean value: either True or False; however, Python treats boolean types quite weakly: True is 1 and False is 0 in some contexts. You can check it out by doing >>> True == 1.\n",
"status = (\"Working\",\"Retired\")[var>65]\n\nThis line works as a ternary operator because the expression var>65 returns 1 or 0, depending on whether var is bigger than 65 or not. So if var>65, then the line becomes this:\nstatus = (\"Working\",\"Retired\")[1]\n\nthat is, the second element of the sequence (\"Working\",\"Retired\"). It looks odd but not if you write it like this instead:\nstatus_sequence = (\"Working\",\"Retired\")\nstatus = status_sequence[1]\n\nso status = \"Retired\".\nSimilarly, if var<=65 then it becomes\nstatus = (\"Working\",\"Retired\")[0]\n\nand status = \"Working\".\n",
"Only the \"status =\" line of that code implements something like the ternary operator.\nstatus = (\"Working\",\"Retired\")[var>65]\n\nThis creates a two-element tuple, with strings 'Working' at index 0, and 'Retired' at index 1. Following this, it indexes into that tuple to pick one of the two items, using the results of the expression var > 65.\nThis expression will return True (equivalent to 1, thus picking 'Retired') if the value of var is greater than 65. Otherwise it will return False (equivalent to 0, thus picking 'Working').\nThere is a key difference between this approach and the ternary operator, however, although it doesn't matter in your particular example. With the tuple-indexing approach, both values are evaluated but only one is returned. With the ternary operator, only one of the two values is actually evaluated; this is referred to as \"short-circuit\" behaviour. It can matter in cases like this:\nstatus = funcA() if var > 65 else funcB()\nstatus = (funcB(), funcA())[var > 65]\n\nIn the first case, either funcA() is called or funcB() is called, but never both. In the latter case, both are called first, and the results are stored in the tuple -- then only one is picked and the tuple is discarded.\nThis is especially important to understand if either funcA() or funcB() have \"side-effects\", meaning they change other data as they execute.\n",
"trying to give a complete answer based on the answers given here.\nthe way you found (please don't use this one because it is not very readable):\ndef val():\n var = float(raw_input(\"Age:\"))\n status = (\"Working\",\"Retired\")[var>65]\n print \"You should be:\",status\n\nusing the python 2.5+ syntax:\ndef val():\n var = float(raw_input(\"Age:\"))\n status = \"Working\" if var>65 else \"Retired\"\n print \"You should be:\",status\n\nusing the other common method still preferred by some people:\ndef val():\n var = float(raw_input(\"Age:\"))\n status = var>65 and \"Working\" or \"Retired\"\n print \"You should be:\",status\n\ni personally tend to use the last since the order of the operands is the same as the C ternary operator.\nEDIT:\nfound some problems with the last approach (thx Roberto Bonvallet).\nfrom wikipedia:\n\nthis code would break if op1 could be\n a \"falsy\" value (None, False, 0, an\n empty sequence or collection, …) as\n the expression would return op2\n (whether it was truthy or falsy)\n instead of the (falsy) op1\n\nso my final suggestion would be to use the 2.5+ ternary operator since it is simple, readable and offers short-circuit behavior.\n"
] |
[
51,
9,
8,
7,
2,
0,
0,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"boolean",
"conditional_operator",
"indexing",
"python"
] |
stackoverflow_0001947030_boolean_conditional_operator_indexing_python.txt
|
Q:
Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules
I wrote a small script. It's designed to search the python directory for all available modules (whether they are installed or not), then it is supposed to check what modules are currently loaded, then it offers an option to dynamically load a module of your choice. The latter using __import__() because I am passing a string to it - (this is where I am having a problem - but I'll get back to it shortly)...then it gives the option to "browse" the module for all its classes, functions, etc. (using dir([module name]) ...).
The problem:
When the module is loaded dynamically - it is embedded in a try/except statement - if it succeeds it reports that the "module is loaded" and if it fails it reports...duh..."Failed to load..."
If you type the name of a module, for example a module named "uu", it says "loaded". So I know it is loading - however, when I go back and call the function that checks all of the LOADED modules - it is blank (using sys.modules)
I am thinking that python is loading the module into a temporary place which is not sys.modules because when I exit out of the script and check sys.modules it is not there.
A:
Nascent_Notes, nice script!
I tried loading uu (command 3) and printing the list of loaded modules (command 2) and they both seem to work fine.
However, if I try to "browse the module" (command 4), I get the following error:
HlpWiz>>> 4
What module do you want to look more into?: uu
*An error occurred - probably because the module isn't loaded or is misspelled*
Try running
#!/usr/bin/env python
import sys
__import__('uu')
print(sys.modules['uu'])
print(dir(uu))
You should get NameError: name 'uu' is not defined.
So it appears that although __import__ successfully imports the uu module,
it does not add uu to the global namespace -- the module uu can not be
accessed by the variable name uu. It can be accessed through sys.modules however:
Therefore, change
var_mod = input("What module do you want to look more into?: ")
print "\n attempting to browse... please wait!"
time.sleep(2)
browse_mod(zlib = var_mod)
to
var_mod = raw_input("What module do you want to look more into?: ")
print "\n attempting to browse... please wait!"
time.sleep(2)
browse_mod(zlib = sys.modules[var_mod])
Not only is using raw_input much safer than input (the user will not be able to execute unexpected/malicious commands), but also raw_input does what you want here.
On a minor note, you could also change
i = 1
for line in sample:
print i, line
i = i + 1
to the more pythonic
for i,line in enumerate(sample):
print i+1, line
Edit:
sys.modules is a dict (short for dictionary). Dicts are like telephone books -- you give it a name (better known as a "key") and it returns a phone number (or more generally, a "value").
In the case of sys.modules, the keys are module names (strings). The values are the module objects themselves.
You access the values in the dict using bracket notation. So uu is just a string, but
sys.modules['uu'] is the module uu.
You can read the full story on dicts here: http://docs.python.org/tutorial/datastructures.html#dictionaries
|
Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules
|
I wrote a small script. It's designed to search the python directory for all available modules (whether they are installed or not), then it is supposed to check what modules are currently loaded, then it offers an option to dynamically load a module of your choice. The latter using __import__() because I am passing a string to it - (this is where I am having a problem - but I'll get back to it shortly)...then it gives the option to "browse" the module for all its classes, functions, etc. (using dir([module name]) ...).
The problem:
When the module is loaded dynamically - it is embedded in a try/except statement - if it succeeds it reports that the "module is loaded" and if it fails it reports...duh..."Failed to load..."
If you type the name of a module, for example a module named "uu", it says "loaded". So I know it is loading - however, when I go back and call the function that checks all of the LOADED modules - it is blank (using sys.modules)
I am thinking that python is loading the module into a temporary place which is not sys.modules because when I exit out of the script and check sys.modules it is not there.
|
[
"Nascent_Notes, nice script! \nI tried loading uu (command 3) and printing the list of loaded modules (command 2) and they both seem to work fine. \nHowever, if I try to \"browse the module\" (command 4), I get the following error:\nHlpWiz>>> 4\nWhat module do you want to look more into?: uu\n\n*An error occurred - probably because the module isn't loaded or is misspelled*\n\nTry running\n#!/usr/bin/env python\nimport sys\n__import__('uu')\nprint(sys.modules['uu'])\nprint(dir(uu))\n\nYou should get NameError: name 'uu' is not defined.\nSo it appears that although __import__ successfully imports the uu module, \nit does not add uu to the global namespace -- the module uu can not be \naccessed by the variable name uu. It can be accessed through sys.modules however:\nTherefore, change\n var_mod = input(\"What module do you want to look more into?: \")\n print \"\\n attempting to browse... please wait!\"\n time.sleep(2)\n browse_mod(zlib = var_mod)\n\nto\n var_mod = raw_input(\"What module do you want to look more into?: \")\n print \"\\n attempting to browse... please wait!\"\n time.sleep(2)\n browse_mod(zlib = sys.modules[var_mod])\n\nNot only is using raw_input much safer than input (the user will not be able to execute unexpected/malicious commands), but also raw_input does what you want here.\nOn a minor note, you could also change\ni = 1\nfor line in sample:\n print i, line\n i = i + 1\n\nto the more pythonic\nfor i,line in enumerate(sample):\n print i+1, line\n\nEdit: \nsys.modules is a dict (short for dictionary). Dicts are like telephone books -- you give it a name (better known as a \"key\") and it returns a phone number (or more generally, a \"value\"). \nIn the case of sys.modules, the keys are module names (strings). The values are the module objects themselves. \nYou access the values in the dict using bracket notation. So uu is just a string, but\nsys.modules['uu'] is the module uu.\nYou can read the full story on dicts here: http://docs.python.org/tutorial/datastructures.html#dictionaries\n"
] |
[
1
] |
[] |
[] |
[
"import",
"operating_system",
"python",
"sys"
] |
stackoverflow_0001969097_import_operating_system_python_sys.txt
|
Q:
free Website testing tool
I am eager to know about any website testing software which is good in usability and look and feel.
Here are the main areas that software should cover.
1. Find the image size.
2. To check broken links.
3. Loading time of website.
4. Test the load with many virtual users.
5. Check for useless codes placed in the source code.
In short, I want all these things cover under one software....
Mayank
A:
I recommend YSlow for frontend testing.
A:
You certainly won't find these requirements wrapped in one app - although I'm sure you could build a test script for this.
That been said, take a look at JMeter for load testing (very flexible app once you've get the hang of it), Xenu for link checking. There are tools available that can check code quality to some degree, but they're obviously language specific. FxCop (for .NET) is one example.
A:
If you are Firefox user, try Web Developer (kit for nearly everything) and Pinger (extremely fast link checker developed by my colleague) addons.
|
free Website testing tool
|
I am eager to know about any website testing software which is good in usability and look and feel.
Here are the main areas that software should cover.
1. Find the image size.
2. To check broken links.
3. Loading time of website.
4. Test the load with many virtual users.
5. Check for useless codes placed in the source code.
In short, I want all these things cover under one software....
Mayank
|
[
"I recommend YSlow for frontend testing.\n",
"You certainly won't find these requirements wrapped in one app - although I'm sure you could build a test script for this.\nThat been said, take a look at JMeter for load testing (very flexible app once you've get the hang of it), Xenu for link checking. There are tools available that can check code quality to some degree, but they're obviously language specific. FxCop (for .NET) is one example.\n",
"If you are Firefox user, try Web Developer (kit for nearly everything) and Pinger (extremely fast link checker developed by my colleague) addons.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"c#",
"python",
"ruby"
] |
stackoverflow_0001346503_c#_python_ruby.txt
|
Q:
pylint PyQt4 error
I write a program :
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication([])
button = QPushButton("hello?")
button.show()
app.exec_()
if __name__=="__main__":
main()
the file name is t.py,
when I run:
pylint t.py
in ubuntu9.10, pyqt4,
I got this:
pylint t.py
No config file found, using default configuration
error while building astng for /home/halida/data/workspace/test/t.py
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 126, in astng_from_file
astng = ASTNGBuilder(self).file_build(filepath, modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 118, in file_build
node = self.string_build(data, modname, path)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 128, in string_build
return self.ast_build(parse(data + '\n'), modname, path)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 147, in ast_build
self.rebuilder.walk(node)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 89, in walk
self._walk(node)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 109, in _walk
self._walk(child, node)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 103, in _walk
handle_leave = node.accept(self)
File "/usr/lib/pymodules/python2.6/logilab/astng/nodes.py", line 159, in accept
return func(self)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 188, in visit_from
imported = node.root().import_module(node.modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/scoped_nodes.py", line 282, in import_module
return MANAGER.astng_from_module_name(self.relative_name(modname, level))
File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 172, in astng_from_module_name
return self.astng_from_module(module, modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 207, in astng_from_module
astng = ASTNGBuilder(self).module_build(module, modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 80, in module_build
node = self.inspect_build(module, modname=modname, path=path)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 95, in inspect_build
self.object_build(node, module)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 195, in object_build
self.object_build(class_node, member)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 198, in object_build
object_build_methoddescriptor(node, member)
File "/usr/lib/pymodules/python2.6/logilab/astng/raw_building.py", line 150, in object_build_methoddescriptor
func = build_function(member.__name__, doc=member.__doc__)
AttributeError: 'PyQt4.QtCore.pyqtSignal' object has no attribute '__name__'
************* Module t
F: 1: <class 'logilab.astng._exceptions.ASTNGBuildingException'>: Unable to load module t ('PyQt4.QtCore.pyqtSignal' object has no attribute '__name__')
Compilation exited abnormally with code 1 at Sat Dec 26 10:43:54
in windows XP, with pythonxy,
I only got a error message, why?
A:
Looks like a bug in astng. They try to read the name of a function which does not publish it (native extension func). I'd report a bug to both astng and pyqt projects. The first one would be that they should handle a no-name situation better. The second one would be that every sane extension should publish at least the function names.
A:
I would check if you're using the very latest astng, pylint, etc.
|
pylint PyQt4 error
|
I write a program :
from PyQt4.QtCore import *
from PyQt4.QtGui import *
def main():
app = QApplication([])
button = QPushButton("hello?")
button.show()
app.exec_()
if __name__=="__main__":
main()
the file name is t.py,
when I run:
pylint t.py
in ubuntu9.10, pyqt4,
I got this:
pylint t.py
No config file found, using default configuration
error while building astng for /home/halida/data/workspace/test/t.py
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 126, in astng_from_file
astng = ASTNGBuilder(self).file_build(filepath, modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 118, in file_build
node = self.string_build(data, modname, path)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 128, in string_build
return self.ast_build(parse(data + '\n'), modname, path)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 147, in ast_build
self.rebuilder.walk(node)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 89, in walk
self._walk(node)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 109, in _walk
self._walk(child, node)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 103, in _walk
handle_leave = node.accept(self)
File "/usr/lib/pymodules/python2.6/logilab/astng/nodes.py", line 159, in accept
return func(self)
File "/usr/lib/pymodules/python2.6/logilab/astng/rebuilder.py", line 188, in visit_from
imported = node.root().import_module(node.modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/scoped_nodes.py", line 282, in import_module
return MANAGER.astng_from_module_name(self.relative_name(modname, level))
File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 172, in astng_from_module_name
return self.astng_from_module(module, modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/manager.py", line 207, in astng_from_module
astng = ASTNGBuilder(self).module_build(module, modname)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 80, in module_build
node = self.inspect_build(module, modname=modname, path=path)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 95, in inspect_build
self.object_build(node, module)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 195, in object_build
self.object_build(class_node, member)
File "/usr/lib/pymodules/python2.6/logilab/astng/builder.py", line 198, in object_build
object_build_methoddescriptor(node, member)
File "/usr/lib/pymodules/python2.6/logilab/astng/raw_building.py", line 150, in object_build_methoddescriptor
func = build_function(member.__name__, doc=member.__doc__)
AttributeError: 'PyQt4.QtCore.pyqtSignal' object has no attribute '__name__'
************* Module t
F: 1: <class 'logilab.astng._exceptions.ASTNGBuildingException'>: Unable to load module t ('PyQt4.QtCore.pyqtSignal' object has no attribute '__name__')
Compilation exited abnormally with code 1 at Sat Dec 26 10:43:54
in windows XP, with pythonxy,
I only got a error message, why?
|
[
"Looks like a bug in astng. They try to read the name of a function which does not publish it (native extension func). I'd report a bug to both astng and pyqt projects. The first one would be that they should handle a no-name situation better. The second one would be that every sane extension should publish at least the function names.\n",
"I would check if you're using the very latest astng, pylint, etc.\n"
] |
[
1,
0
] |
[] |
[] |
[
"pylint",
"pyqt4",
"python"
] |
stackoverflow_0001962500_pylint_pyqt4_python.txt
|
Q:
Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python
I have a list with objects of x type. Those objects have an attribute name.
I want to find if a string matchs any of those object names. If I would have a list with the object names I just would do if string in list, so I was wondering given the current situation if there is a way to do it without having to loop over the list.
A:
any(obj for obj in objs if obj.name==name)
Note, that it will stop looping after first match found.
A:
Here's another
dict( (o.name,o) for o in obj_list )[name]
The trick, though, is avoid creating a list obj_list in the first place.
Since you know that you're going to fetch objects by the string value of an attribute, do not use a list, use a dictionary instead of a list.
A dictionary can be trivially "searched" for matching strings. It's a better choice than a list.
A:
What do you want to do if the string matches? Do you just want to return True/False, or return a list of objects that match?
To return a boolean:
any(obj.name == name for obj in objs)
(I find this slightly more readable than Denis Otkidach's version).
to filter the list:
[obj for obj in objs if obj.name == name]
A:
if string in [x.name for x in list_of_x]
A:
for i in listOfItemsOfTypeX:
if i.name == myString: return True
return False
|
Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python
|
I have a list with objects of x type. Those objects have an attribute name.
I want to find if a string matchs any of those object names. If I would have a list with the object names I just would do if string in list, so I was wondering given the current situation if there is a way to do it without having to loop over the list.
|
[
"any(obj for obj in objs if obj.name==name)\n\nNote, that it will stop looping after first match found.\n",
"Here's another\ndict( (o.name,o) for o in obj_list )[name]\n\nThe trick, though, is avoid creating a list obj_list in the first place.\nSince you know that you're going to fetch objects by the string value of an attribute, do not use a list, use a dictionary instead of a list.\nA dictionary can be trivially \"searched\" for matching strings. It's a better choice than a list.\n",
"What do you want to do if the string matches? Do you just want to return True/False, or return a list of objects that match?\nTo return a boolean:\nany(obj.name == name for obj in objs)\n\n(I find this slightly more readable than Denis Otkidach's version).\nto filter the list:\n[obj for obj in objs if obj.name == name]\n\n",
"if string in [x.name for x in list_of_x]\n",
"for i in listOfItemsOfTypeX:\n if i.name == myString: return True\nreturn False\n\n"
] |
[
5,
4,
4,
1,
0
] |
[] |
[] |
[
"algorithm",
"python"
] |
stackoverflow_0001969490_algorithm_python.txt
|
Q:
Problem with python-proxy for mp3-streams
I am trying to make a proxy for internet-radio in mp3. It is working fine when accessing mp3-files, but not for mp3-streams.
I suppose I am missing some very basic difference but could not find a hint.
Best regards,
wolf
My test code:
#!/usr/local/bin/python2.5
import urllib;
import SocketServer, BaseHTTPServer
import subprocess
class Proxy:
def __init__(self, port=4500):
self.port = port
self.server = SocketServer.ThreadingTCPServer(('', self.port), self.Manager)
class Manager(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "audio/mpeg");
self.end_headers();
process = subprocess.Popen("lame --mp3input -m m --abr 128 -b 64 - -", shell=True, bufsize=64,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
(streamin, streamout) = (process.stdin, process.stdout)
# Does not work
url = urllib.urlopen("http://stream.srg-ssr.ch:80%s" % "/drs3/mp3_128.m3u")
# Does work
#url = urllib.urlopen("http://www.openbsd.org:80%s" % "/songs/song46.mp3")
buffer = url.read(4096)
while len(buffer) > 0:
streamin.streamout(buffer);
while 1:
data = select.select([streamout.fileno()], [],[],.1);
if len(data[0]) == 0:
break
mp3 = streamout.read(4096)
self.wfile.write(mp3)
buf = url.read(4096)
A:
The problem is that you are reading not mp3 stream but M3U playlist file. This file doesn't contain any mp3 data itself.
The content of your file is simple text:
http://zlz-stream10.streamserver.ch/1/drs3/mp3_128
http://glb-stream12.streamserver.ch/1/drs3/mp3_128
http://zlz-stream13.streamserver.ch/1/drs3/mp3_128
http://zlz-stream11.streamserver.ch/1/drs3/mp3_128
http://glb-stream10.streamserver.ch/1/drs3/mp3_128
http://zlz-stream12.streamserver.ch/1/drs3/mp3_128
http://glb-stream13.streamserver.ch/1/drs3/mp3_128
http://glb-stream11.streamserver.ch/1/drs3/mp3_128
Each line is an URL for the stream itself. Read the M3U file, parse it and download the stream data from these URLs.
|
Problem with python-proxy for mp3-streams
|
I am trying to make a proxy for internet-radio in mp3. It is working fine when accessing mp3-files, but not for mp3-streams.
I suppose I am missing some very basic difference but could not find a hint.
Best regards,
wolf
My test code:
#!/usr/local/bin/python2.5
import urllib;
import SocketServer, BaseHTTPServer
import subprocess
class Proxy:
def __init__(self, port=4500):
self.port = port
self.server = SocketServer.ThreadingTCPServer(('', self.port), self.Manager)
class Manager(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "audio/mpeg");
self.end_headers();
process = subprocess.Popen("lame --mp3input -m m --abr 128 -b 64 - -", shell=True, bufsize=64,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
(streamin, streamout) = (process.stdin, process.stdout)
# Does not work
url = urllib.urlopen("http://stream.srg-ssr.ch:80%s" % "/drs3/mp3_128.m3u")
# Does work
#url = urllib.urlopen("http://www.openbsd.org:80%s" % "/songs/song46.mp3")
buffer = url.read(4096)
while len(buffer) > 0:
streamin.streamout(buffer);
while 1:
data = select.select([streamout.fileno()], [],[],.1);
if len(data[0]) == 0:
break
mp3 = streamout.read(4096)
self.wfile.write(mp3)
buf = url.read(4096)
|
[
"The problem is that you are reading not mp3 stream but M3U playlist file. This file doesn't contain any mp3 data itself.\nThe content of your file is simple text:\nhttp://zlz-stream10.streamserver.ch/1/drs3/mp3_128\nhttp://glb-stream12.streamserver.ch/1/drs3/mp3_128\nhttp://zlz-stream13.streamserver.ch/1/drs3/mp3_128\nhttp://zlz-stream11.streamserver.ch/1/drs3/mp3_128\nhttp://glb-stream10.streamserver.ch/1/drs3/mp3_128\nhttp://zlz-stream12.streamserver.ch/1/drs3/mp3_128\nhttp://glb-stream13.streamserver.ch/1/drs3/mp3_128\nhttp://glb-stream11.streamserver.ch/1/drs3/mp3_128\n\nEach line is an URL for the stream itself. Read the M3U file, parse it and download the stream data from these URLs.\n"
] |
[
0
] |
[] |
[] |
[
"audio",
"mp3",
"python",
"stream"
] |
stackoverflow_0001969621_audio_mp3_python_stream.txt
|
Q:
Iteration WAS working in my script, now I cant get python to iterate - what happened?
Did my python ide break or something?
import sys
i = 0
sample = ("this", "is", "Annoying!")
for line in sample:
print i, line
i + 1
Now gives me...
0 this
0 is
0 Annoying!
I THOUGHT, it would give me:
1 this
2 is
3 Annoying
I had other scripts that I was working on and it they all just broke - they all have the same line number when they print numerous iterations using the for statement - can someone PLEASE tell me what the heck is going on - very frustrated lol... did Python break? Do I need sleep? What is wrong here?
A:
While the other answers are correct, this is how you usually do this in python:
sample = ("this", "is", "Annoying!")
for i, line in enumerate(sample):
print i, line
The enumerate function does exactly what you want: Iterating through your tuple, while at the same time giving you (line) numbers.
A:
You are calculating i+1 but are not storing the result of that anywhere. Specifically you are not updating i to contain the new value. Use i = i + 1 or i += 1 instead.
A:
This works just fine for me:
>>> import sys
>>> i = 0
>>> sample = ("abc", "def", "ghi")
>>> for line in sample:
... i = i + 1
... print i, line
...
1 abc
2 def
3 ghi
Are you sure you're incrementing and storing the value i? (Your sample omits this, but in another answer you say you did put i = i + 1.) Remember, Python is whitespace-sensitive, so if you did something like this, the result won't be what you expect:
>>> for line in sample:
... print i, line
... i = i + 1 # <-- This is not part of the loop!
A:
I suspect you have an indentation problem, that perhaps the i = i + 1 statement is somehow not part of the for-loop.
But Instead of doing your own counter incrementing, better practice is to use enumerate:
for i,line in enumerate(sample):
print i,line
A:
The problem is you're doing "i + 1", not "i=i+1"
A:
You're not incrementing the variable i in your code, you'd need to do something like:
for line in sample:
i = i + 1
print i, line
A:
The result that you expect would be obtained by using enumerate:
sample = ("this", "is", "Annoying!")
for index, line in enumerate(sample):
print index, line
I don't see how the code that you posted ever would have worked in any version of Python.
A:
Just step through debugger to see the execution.
|
Iteration WAS working in my script, now I cant get python to iterate - what happened?
|
Did my python ide break or something?
import sys
i = 0
sample = ("this", "is", "Annoying!")
for line in sample:
print i, line
i + 1
Now gives me...
0 this
0 is
0 Annoying!
I THOUGHT, it would give me:
1 this
2 is
3 Annoying
I had other scripts that I was working on and it they all just broke - they all have the same line number when they print numerous iterations using the for statement - can someone PLEASE tell me what the heck is going on - very frustrated lol... did Python break? Do I need sleep? What is wrong here?
|
[
"While the other answers are correct, this is how you usually do this in python:\nsample = (\"this\", \"is\", \"Annoying!\")\n\nfor i, line in enumerate(sample):\n print i, line\n\nThe enumerate function does exactly what you want: Iterating through your tuple, while at the same time giving you (line) numbers.\n",
"You are calculating i+1 but are not storing the result of that anywhere. Specifically you are not updating i to contain the new value. Use i = i + 1 or i += 1 instead.\n",
"This works just fine for me:\n>>> import sys\n>>> i = 0\n>>> sample = (\"abc\", \"def\", \"ghi\")\n>>> for line in sample:\n... i = i + 1\n... print i, line\n... \n1 abc\n2 def\n3 ghi\n\nAre you sure you're incrementing and storing the value i? (Your sample omits this, but in another answer you say you did put i = i + 1.) Remember, Python is whitespace-sensitive, so if you did something like this, the result won't be what you expect:\n>>> for line in sample:\n... print i, line\n... i = i + 1 # <-- This is not part of the loop!\n\n",
"I suspect you have an indentation problem, that perhaps the i = i + 1 statement is somehow not part of the for-loop. \nBut Instead of doing your own counter incrementing, better practice is to use enumerate:\nfor i,line in enumerate(sample):\n print i,line\n\n",
"The problem is you're doing \"i + 1\", not \"i=i+1\"\n",
"You're not incrementing the variable i in your code, you'd need to do something like:\nfor line in sample:\n i = i + 1\n print i, line\n\n",
"The result that you expect would be obtained by using enumerate:\nsample = (\"this\", \"is\", \"Annoying!\")\nfor index, line in enumerate(sample):\n print index, line\n\nI don't see how the code that you posted ever would have worked in any version of Python.\n",
"Just step through debugger to see the execution.\n"
] |
[
10,
7,
4,
4,
3,
2,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001969937_python.txt
|
Q:
Is it a bad idea to design and develop a python applications backend and then once finished try to apply a GUI to it?
Is it better to do it all at once? I'm very new to wxPython and I'm thinking it would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied with the overall design of the app. Any advice?
A:
This is a viable approach. In fact, some programmers use it for the advantages it brings:
Modular non-GUI code can then be tied in with different GUIs, not just a single library
It can also be used for a command-line application (or a batch interface to a GUI one)
It can be reused for a web application
And most importantly: it can make unit-testing of the code easier.
However keep in mind that it requires some careful design. You'll want your "logic code" to be free from GUI constraints, and sometimes it is difficult (especially when the code relies on GUI idioms like an event loop).
A:
That depends on the problem domain. An image processing tool would be rather difficult to implement without reference to a GUI. For most apps, though, I would argue strongly in favour of separating the two parts. It is much, much easier to develop, test and evolve a UI-free back-end. The gains will vastly outweigh the cost of defining a clean API between the front and back end. In fact, the process of defining the API will yield a better design overall.
A:
Separation of the user interface from the engine code is the unixy way to do it and there's a lot of merit to doing it that way. It results in modular re-usable programs and code that can play nicely with other programs and fit into a larger tool chain.
Having said that, such an approach tends to discount the value of creating a really usable UI experience. It's very difficult and rare for a program's internal model to match the user model when you design your program's functionality first and then the user interface later. As a result, you need to impedance-match the two sides after creating them independently. This results in either creating a compromise in usability (your ui becomes nothing more than a front-end to the command line switches your program takes) or a large glue layer between the UI and the core program which tends to be messy and buggy.
If your program is primarily designed to be run through a user interface interactively with a user, then it probably makes sense to design the user interface in parallel with your actual functionality.
So:
it would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied with the overall design of the app
If your UI is the main means of operating your program, then that UI is part of the program design. Not something to be painted over the program when its done.
A:
IMHO, that would rather be a better idea. To keep the underlying business logic not tied down to the UI is a better approach that we can worry more about the underlying logic than bogging down too much about the interface.
At the same time, it is also important to have some basic design for your interface so that it helps you have an idea about what kind of inputs and outputs are involved, and making the underlying logic support a wide range of inputs/outputs or simply wide range of interfaces.
A:
Since you are new to GUI programming, your approach is perfectly valid. It will likely result in a less than optimal UI, but that's OK for now. And in fact, there are some very successful multi-million dollar commercial projects that are built this way.
Arguably a better approach is to first design the UI since that is the most important part. After that is completel you can then create a back-end that can support that UI. This approach still results in separate front- and back-ends but puts the emphasis on the needs of the user, where it should be.
|
Is it a bad idea to design and develop a python applications backend and then once finished try to apply a GUI to it?
|
Is it better to do it all at once? I'm very new to wxPython and I'm thinking it would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied with the overall design of the app. Any advice?
|
[
"This is a viable approach. In fact, some programmers use it for the advantages it brings:\n\nModular non-GUI code can then be tied in with different GUIs, not just a single library\nIt can also be used for a command-line application (or a batch interface to a GUI one)\nIt can be reused for a web application\nAnd most importantly: it can make unit-testing of the code easier.\n\nHowever keep in mind that it requires some careful design. You'll want your \"logic code\" to be free from GUI constraints, and sometimes it is difficult (especially when the code relies on GUI idioms like an event loop).\n",
"That depends on the problem domain. An image processing tool would be rather difficult to implement without reference to a GUI. For most apps, though, I would argue strongly in favour of separating the two parts. It is much, much easier to develop, test and evolve a UI-free back-end. The gains will vastly outweigh the cost of defining a clean API between the front and back end. In fact, the process of defining the API will yield a better design overall.\n",
"Separation of the user interface from the engine code is the unixy way to do it and there's a lot of merit to doing it that way. It results in modular re-usable programs and code that can play nicely with other programs and fit into a larger tool chain.\nHaving said that, such an approach tends to discount the value of creating a really usable UI experience. It's very difficult and rare for a program's internal model to match the user model when you design your program's functionality first and then the user interface later. As a result, you need to impedance-match the two sides after creating them independently. This results in either creating a compromise in usability (your ui becomes nothing more than a front-end to the command line switches your program takes) or a large glue layer between the UI and the core program which tends to be messy and buggy.\nIf your program is primarily designed to be run through a user interface interactively with a user, then it probably makes sense to design the user interface in parallel with your actual functionality. \nSo:\n\nit would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied with the overall design of the app\n\nIf your UI is the main means of operating your program, then that UI is part of the program design. Not something to be painted over the program when its done.\n",
"IMHO, that would rather be a better idea. To keep the underlying business logic not tied down to the UI is a better approach that we can worry more about the underlying logic than bogging down too much about the interface. \nAt the same time, it is also important to have some basic design for your interface so that it helps you have an idea about what kind of inputs and outputs are involved, and making the underlying logic support a wide range of inputs/outputs or simply wide range of interfaces.\n",
"Since you are new to GUI programming, your approach is perfectly valid. It will likely result in a less than optimal UI, but that's OK for now. And in fact, there are some very successful multi-million dollar commercial projects that are built this way.\nArguably a better approach is to first design the UI since that is the most important part. After that is completel you can then create a back-end that can support that UI. This approach still results in separate front- and back-ends but puts the emphasis on the needs of the user, where it should be.\n"
] |
[
16,
2,
1,
0,
0
] |
[
"What level of interactivity do you need? If you need rich feedback and interaction, then you need an OO program model, then you can ad the GUI on top of the objects.\nIf you just have filters and functions (no real feedback, or just a results window) than a library or component model would be better.\nEither way, you are better off coding your logic separate to the GUI, so you can test it more easily.\n",
"If you're used to a more command line approach, this would be a bad idea. Responding to user input is a completely different paradigm, and you're not likely to get it right the first time.\nIf you're just talking about the difference between wxPython and another GUI, don't worry about it.\n"
] |
[
-1,
-1
] |
[
"python",
"wxpython"
] |
stackoverflow_0001967888_python_wxpython.txt
|
Q:
Python regexp find two keywords in a line
I'm having a hard time understanding this regex stuff...
I have a string like this:
<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">
I want to use findall() and groups to get this:
['56242','saddelmageri']
I can match the number with something like "synset-[0-9]" and the word with something like "{(.*?)}" but how do I write it to get the above result?
And here's a follow-up question - some lines look like this:
<wn20schema:NounSynset rdf:about="&dn;synset-2589" rdfs:label="**{cykel_3: trehjulet cykel; tricykel,1_1}**">
In this case I want to extract the stuff between the {} with this result:
['2589', ['cykel', 'trehjulet cykel', 'tricykel']]
so that I can drop it in a dictionary later as a key(2589) : value(['cykel', 'trehjulet cykel', 'tricykel']) pair.
Any thoughts?
A:
Please see the top answer to this question. It is generally a terrible idea to parse xml with regular expressions. XML parsers are built for this purpose.
The quickest way to do this would probably be python's built-in minidom
A:
Since this appears to be xml data, you would be better off using an xml parser, since parsing xml with regular expressions is very, very difficult to do right.
However, since you specifically asked for a regular expression...
Your specifications are a bit imprecise, and with regular expressions you need to be very precise in what constitutes a match. For example, will the rdfs:label value always have a _1 that you want to strip off? Will there always only be one of these blocks of data per line, or multiple per line? Also, is the order of the result important?
Here's a quick hack that might give you close to what you want:
import re
data=r'<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">"'
matches=re.findall('synset-([0-9]+).*label="{(.*)_1}"', data)
print "matches:", matches
When I run the above, I get the following output, which is a list of two-tuples containing the two strings you wanted (though in a different order):
matches: [('56242', 'saddelmageri')]
A:
If you do a lot with this data, consider even a specialized RDF library (e.g. RDFLib).
If not, an XML parser is definitely the way to go!
What if tomorrow it won't be on a single line?
What if tomorrow the label will come before the about?
There are at a least a dozen more ways in which it can remain valid XML but break your regexp!
Anyway, I tried applying an XML parser, but I'm getting an "undefined entity error" for the &dn; there. Can you post the top of the file (doctype, namespace definitions, and the like)?
A:
You're doing two different kinds of parsing here, and you'll need to use two different tools.
First, you're parsing XML. For that, you're going to need to use an XML parser, not regular expressions. Because these elements are functionally identical XML:
<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">
</wn20schema:NounSysnset>
<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}"/>
<wn20schema:NounSynset rdfs:label="{saddelmageri_1}" rdf:about="&dn;synset-56242"/>
and conceivably even:
<NounSynset xmlns="my_wn20schema_namespace_urn" C:label='not_of_interest' A:label='{saddelmageri_1}' B:about='&dn;synset-56242'/>
To parse that element, you need to know the names of the namespaces that the element and the attributes you're interested in belong to, and then use an XML parser to find them - specifically, an XML parser that properly supports XML namespaces and XPath, like lxml.
You'll end up with something like this to find the attributes you're looking for (assuming that doc is the parsed XML document, and that variables ending in _urn are strings containing the various namespace URNs):
def find_attributes(doc):
for elm in doc.xpath('//x:NounSynset', namespaces={'x': wn20schema_namespace_urn}):
yield (elm.get(rdf_namespace_urn + "about"), elm.get(rdfs_namespace_urn + "label"))
Now you can look at the second part of the problem, which is parsing the values you need out of the attribute values you have. For that, you would use regular expressions. To parse the about attribute, this might work:
re.match(r'[^\d]*(\d*)', about).groups()[0]
which returns the first series of digit characters found. And to parse the label attribute, you might use:
re.match(r'{([^_]*)', label).groups()[0]
which returns all characters in label after a leading left brace and up to but not including the first underscore. (As far as parsing the second form of label that you posted, you haven't posted enough information for me to guess what a regular expression to parse that would look like.)
|
Python regexp find two keywords in a line
|
I'm having a hard time understanding this regex stuff...
I have a string like this:
<wn20schema:NounSynset rdf:about="&dn;synset-56242" rdfs:label="{saddelmageri_1}">
I want to use findall() and groups to get this:
['56242','saddelmageri']
I can match the number with something like "synset-[0-9]" and the word with something like "{(.*?)}" but how do I write it to get the above result?
And here's a follow-up question - some lines look like this:
<wn20schema:NounSynset rdf:about="&dn;synset-2589" rdfs:label="**{cykel_3: trehjulet cykel; tricykel,1_1}**">
In this case I want to extract the stuff between the {} with this result:
['2589', ['cykel', 'trehjulet cykel', 'tricykel']]
so that I can drop it in a dictionary later as a key(2589) : value(['cykel', 'trehjulet cykel', 'tricykel']) pair.
Any thoughts?
|
[
"Please see the top answer to this question. It is generally a terrible idea to parse xml with regular expressions. XML parsers are built for this purpose.\nThe quickest way to do this would probably be python's built-in minidom\n",
"Since this appears to be xml data, you would be better off using an xml parser, since parsing xml with regular expressions is very, very difficult to do right.\nHowever, since you specifically asked for a regular expression...\nYour specifications are a bit imprecise, and with regular expressions you need to be very precise in what constitutes a match. For example, will the rdfs:label value always have a _1 that you want to strip off? Will there always only be one of these blocks of data per line, or multiple per line? Also, is the order of the result important?\nHere's a quick hack that might give you close to what you want:\nimport re\ndata=r'<wn20schema:NounSynset rdf:about=\"&dn;synset-56242\" rdfs:label=\"{saddelmageri_1}\">\"'\n\nmatches=re.findall('synset-([0-9]+).*label=\"{(.*)_1}\"', data)\nprint \"matches:\", matches\n\nWhen I run the above, I get the following output, which is a list of two-tuples containing the two strings you wanted (though in a different order):\nmatches: [('56242', 'saddelmageri')]\n\n",
"If you do a lot with this data, consider even a specialized RDF library (e.g. RDFLib).\nIf not, an XML parser is definitely the way to go!\n\nWhat if tomorrow it won't be on a single line?\nWhat if tomorrow the label will come before the about?\nThere are at a least a dozen more ways in which it can remain valid XML but break your regexp!\n\nAnyway, I tried applying an XML parser, but I'm getting an \"undefined entity error\" for the &dn; there. Can you post the top of the file (doctype, namespace definitions, and the like)?\n",
"You're doing two different kinds of parsing here, and you'll need to use two different tools.\nFirst, you're parsing XML. For that, you're going to need to use an XML parser, not regular expressions. Because these elements are functionally identical XML:\n<wn20schema:NounSynset rdf:about=\"&dn;synset-56242\" rdfs:label=\"{saddelmageri_1}\">\n</wn20schema:NounSysnset>\n\n<wn20schema:NounSynset rdf:about=\"&dn;synset-56242\" rdfs:label=\"{saddelmageri_1}\"/>\n\n<wn20schema:NounSynset rdfs:label=\"{saddelmageri_1}\" rdf:about=\"&dn;synset-56242\"/>\n\nand conceivably even:\n<NounSynset xmlns=\"my_wn20schema_namespace_urn\" C:label='not_of_interest' A:label='{saddelmageri_1}' B:about='&dn;synset-56242'/>\n\nTo parse that element, you need to know the names of the namespaces that the element and the attributes you're interested in belong to, and then use an XML parser to find them - specifically, an XML parser that properly supports XML namespaces and XPath, like lxml.\nYou'll end up with something like this to find the attributes you're looking for (assuming that doc is the parsed XML document, and that variables ending in _urn are strings containing the various namespace URNs):\ndef find_attributes(doc):\n for elm in doc.xpath('//x:NounSynset', namespaces={'x': wn20schema_namespace_urn}):\n yield (elm.get(rdf_namespace_urn + \"about\"), elm.get(rdfs_namespace_urn + \"label\"))\n\nNow you can look at the second part of the problem, which is parsing the values you need out of the attribute values you have. For that, you would use regular expressions. To parse the about attribute, this might work:\nre.match(r'[^\\d]*(\\d*)', about).groups()[0]\n\nwhich returns the first series of digit characters found. And to parse the label attribute, you might use:\nre.match(r'{([^_]*)', label).groups()[0]\n\nwhich returns all characters in label after a leading left brace and up to but not including the first underscore. (As far as parsing the second form of label that you posted, you haven't posted enough information for me to guess what a regular expression to parse that would look like.)\n"
] |
[
2,
1,
1,
1
] |
[] |
[] |
[
"findall",
"python",
"regex"
] |
stackoverflow_0001970028_findall_python_regex.txt
|
Q:
Enumerations in python
Duplicate:
What’s the best way to implement an ‘enum’ in Python?
Whats the recognised way of doing enumerations in python?
For example, at the moment I'm writing a game and want to be able to move "up", "down", "left" and "right". I'm using strings because I haven't yet figured out how enumerations work in python, and so my logic is littered with things like this:
def move(self, direction):
if direction == "up":
# Do something
I want to replace "up" with something like Directions.up
A:
UPDATE 1: Python 3.4 will have a built-in well designed enum library. The values always know their name and type; there is an integer-compatible mode but the recommended default for new uses are singletons, unequal to any other object.
UPDATE 2: Since writing this I realized the critical test for enums is serialization. Other aspects can be refactored later, but if your enum goes into files / onto the wire, ask yourself up front what should happen if it's deserialized by an older/newer version (that might support a different set of values)...
If you are sure that you need an enum, others have answered how to do it.
But let's see why you want them? Understanding the motivation will help with choosing the solution.
Atomic values - in C, small numbers are easy to pass around, strings aren't.
In Python, strings like "up" are perfectly good for many uses.
Moreover, any solution that ends up with just a number is worse for debugging!
Meaningful values - in C, you frequently have to deal with existing magic
numbers, and just want some syntax sugar for that. That's not the case here.
However, there is other meaningful information you might want to associate with
directions, e.g. the (dx,dy) vector - more on that below.
Type checking - in C, enums help catching invalid values at compile time.
But Python generally prefers sacrificing compiler checking for less typing.
Introspection (doesn't exist in C enums) - you want to know all the valid values.
Completion - the editor can show you the possible values and help you type them.
Strings Redeemed (aka Symbols)
So, on the light side of Pythonic solutions, just use strings, and maybe have a list/set of all valid values:
DIRECTIONS = set(['up', 'down', 'left', 'right'])
def move(self, direction):
# only if you feel like checking
assert direction in DIRECTIONS
# you can still just use the strings!
if direction == 'up':
# Do something
Note that the debugger would tell you that the function was called with 'up' as its argument. Any solution where direction is actually 0 is much worse than this!
In the LISP family of languages, this usage is dubbed symbols - atomic objects usable as easily as numbers would be, but carrying a textual value. (To be precise, symbols are string-like but a separate type. However, Python routinely uses regular strings where LISP would use symbols.)
Namespaced Strings
You can combine the idea that 'up' is better than 0 with the other solutions.
If you want to catch mispellings (at run time):
UP = 'up'
...
RIGHT = 'right'
And if you want to insist on typing a prefix to get completion, put the above in a class:
class Directions:
UP = "up"
...
RIGHT = "right"
or just in a separate file, making it a module.
A module allows lazy users to do from directions import * to skip the prefix - up to you whether you consider this a plus or minus... (I personally would hate to be forced to type Directions.UP if I'm using it frequently).
Objects with functionality
What if there is useful information/functionality associated with each value?
"right" is not just one of 4 arbitrary values, it's the positive direction on the X axis!
If what you are doing in that if is something like:
def move(self, direction):
if direction == 'up':
self.y += STEP
elif direction == 'down':
self.y -= STEP
elif direction == 'left':
self.x -= STEP
elif direction == 'right':
self.x += STEP
than what you'd really like to write is:
def move(self, direction):
self.x += direction.dx * STEP
self.y += direction.dy * STEP
and that's it!
So you want to stuff this into either instances:
# Written in full to give the idea.
# Consider using collections.namedtuple
class Direction(object):
def __init__(self, dx, dy, name):
self.dx = dx
self.dy = dy
self.name = name
def __str__(self):
return self.name
UP = Direction(0, 1, "up")
DOWN = Direction(0, -1, "down")
LEFT = Direction(-1, 0, "left")
RIGHT = Direction(1, 0, "right")
or just classes:
class Direction(object):
pass
class Up(Direction):
dx = 0
dy = 1
...
class Right(Direction):
dx = 1
dy = 0
Remember that in Python, classes are also objects (distinct from any other object), and you can compare them: direction == Up etc.
Generally, instances are probably cleaner, but if your enumerated concepts have some hierarchical relationship, sometimes modeling them directly with classes is very nice.
A:
class Directions:
up = 0
down = 1
left = 2
right =3
A:
I gave a +1 to Kugel, but another leaner option is
dirUp, dirDown, dirLeft, dirRight = range(4)
(Some time passes)
So I was thinking...we have an obvious DRY violation here in that we already specify four items on the LHS, and then again specify four on the RHS. What happens if we add items in the future? What happens when someone else adds them, and maybe they are more sloppy than ourselves? One obvious way to remove the DRY violation is to use the list of enums themselves to assign their values:
>>> enums = ['dirUp', 'dirDown']
>>> for v, k in enumerate(enums):
... exec(k + '=' + str(v))
...
>>> print dirDown
1
>>> print dirUp
0
If you can stomach using exec() for this, then fine. If not, then use the other approach. This current discussion is all academic anyway. However, there is still a problem here. What if the enums are used throughout a great body of source code, and some other programmer comes along and inserts a new value between dirUp and dirDown? This will cause misery because the mapping between the names of the enums and the enums themselves will be wrong. Bear in mind that that remains a problem even in the original simple solution.
Here, we have the novel idea of using the builtin hash() function to determine our enum value as an int, and we use the text name of the enum itself to determine the hash:
>>> for k in enums:
... exec(k + '=' + str(hash(k)))
...
>>> dirUp
-1147857581
>>> dirDown
453592598
>>> enums = ['dirUp', 'dirLeft', 'dirDown']
>>> for k in enums:
... exec(k + '=' + str(hash(k)))
...
>>> dirUp
-1147857581
>>> dirDown
453592598
>>> dirLeft
-300839747
>>>
Notice that we inserted a new value between dirUp and dirDown, i.e. dirLeft, and our original mapping values for the first two did not change.
I may actually use this in my own code. Thanks to the OP for posting the question.
(Some more time passes)
Beni Cherniavsky-Paskin made some very good comments:
Python's default hash() is not stable across platforms (dangerous for persistence applications)
The possibility of collisions is always present.
I tend to agree with both observations. His suggestion is to use the strings themselves (I really like the self-documenting behaviour of using the values) as the hash, and so the code becomes the following (note we use a set instead of a list, to enforce uniqueness):
>>> items=('dirUp','dirDown','dirLeft','dirRight')
>>> for i in items:
exec('{}="{}"'.format(i,i))
>>> dirDown
'dirDown'
It is also trivial to put these in a namespace, so as to avoid collisions with other code:
>>> class Direction():
for i in ('dirUp','dirDown','dirLeft','dirRight'):
exec('{}="{}"'.format(i,i))
>>> Direction.dirUp
'dirUp'
The length of the cryptographic hash he mentions can be seen here:
>>> from hashlib import md5
>>> crypthash = md5('dirDown'.encode('utf8'))
>>> crypthash.hexdigest()
'6a65fd3cd318166a1cc30b3e5e666d8f'
A:
The collections.namedtuple object can provide such a namespace:
>>> import collections
>>> dircoll=collections.namedtuple('directions', ('UP', 'DOWN', 'LEFT', 'RIGHT'))
>>> directions=dircoll(0,1,2,3)
>>> directions
directions(UP=0, DOWN=1, LEFT=2, RIGHT=3)
>>> directions.DOWN
1
>>>
A:
This is simple and effective:
class Enum(object):
def __init__(self, *keys):
self.__dict__.update(zip(keys, range(len(keys))))
Usage:
>>> x = Enum('foo', 'bar', 'baz', 'bat')
>>> x.baz
2
>>> x.bat
3
A:
If you are using Python 2.6+ then you can use namedtuple. They have the advantage having fixed number of properties, and when you need all enum values, you can use it like a tuple.
For more control over enum values, you may create your own enumeration class.
def enum(args, start=0):
class Enum(object):
__slots__ = args.split()
def __init__(self):
for i, key in enumerate(Enum.__slots__, start):
setattr(self, key, i)
return Enum()
>>> e_dir = enum('up down left right')
>>> e_dir.up
0
>>> e_dir = enum('up down left right', start=1)
>>> e_dir.up
1
Declaring __slots__ seals your Enum class, no more attributes can be set to an object which was created from a class with __slots__ property.
Your Enum class can also be namedtuple based, in that case you also get the features of a tuple. See namedtuple docs on subclassing namedtuple
|
Enumerations in python
|
Duplicate:
What’s the best way to implement an ‘enum’ in Python?
Whats the recognised way of doing enumerations in python?
For example, at the moment I'm writing a game and want to be able to move "up", "down", "left" and "right". I'm using strings because I haven't yet figured out how enumerations work in python, and so my logic is littered with things like this:
def move(self, direction):
if direction == "up":
# Do something
I want to replace "up" with something like Directions.up
|
[
"UPDATE 1: Python 3.4 will have a built-in well designed enum library. The values always know their name and type; there is an integer-compatible mode but the recommended default for new uses are singletons, unequal to any other object.\nUPDATE 2: Since writing this I realized the critical test for enums is serialization. Other aspects can be refactored later, but if your enum goes into files / onto the wire, ask yourself up front what should happen if it's deserialized by an older/newer version (that might support a different set of values)...\n\nIf you are sure that you need an enum, others have answered how to do it.\nBut let's see why you want them? Understanding the motivation will help with choosing the solution.\n\nAtomic values - in C, small numbers are easy to pass around, strings aren't.\nIn Python, strings like \"up\" are perfectly good for many uses.\nMoreover, any solution that ends up with just a number is worse for debugging!\n\nMeaningful values - in C, you frequently have to deal with existing magic\nnumbers, and just want some syntax sugar for that. That's not the case here.\nHowever, there is other meaningful information you might want to associate with\ndirections, e.g. the (dx,dy) vector - more on that below.\n\nType checking - in C, enums help catching invalid values at compile time.\nBut Python generally prefers sacrificing compiler checking for less typing.\n\nIntrospection (doesn't exist in C enums) - you want to know all the valid values.\n\nCompletion - the editor can show you the possible values and help you type them.\n\n\nStrings Redeemed (aka Symbols)\nSo, on the light side of Pythonic solutions, just use strings, and maybe have a list/set of all valid values:\nDIRECTIONS = set(['up', 'down', 'left', 'right'])\n\ndef move(self, direction):\n # only if you feel like checking\n assert direction in DIRECTIONS\n # you can still just use the strings!\n if direction == 'up':\n # Do something\n\nNote that the debugger would tell you that the function was called with 'up' as its argument. Any solution where direction is actually 0 is much worse than this!\nIn the LISP family of languages, this usage is dubbed symbols - atomic objects usable as easily as numbers would be, but carrying a textual value. (To be precise, symbols are string-like but a separate type. However, Python routinely uses regular strings where LISP would use symbols.)\nNamespaced Strings\nYou can combine the idea that 'up' is better than 0 with the other solutions.\nIf you want to catch mispellings (at run time):\nUP = 'up'\n...\nRIGHT = 'right'\n\nAnd if you want to insist on typing a prefix to get completion, put the above in a class:\nclass Directions:\n UP = \"up\"\n ...\n RIGHT = \"right\"\n\nor just in a separate file, making it a module.\nA module allows lazy users to do from directions import * to skip the prefix - up to you whether you consider this a plus or minus... (I personally would hate to be forced to type Directions.UP if I'm using it frequently).\nObjects with functionality\nWhat if there is useful information/functionality associated with each value?\n\"right\" is not just one of 4 arbitrary values, it's the positive direction on the X axis!\nIf what you are doing in that if is something like:\ndef move(self, direction):\n if direction == 'up':\n self.y += STEP\n elif direction == 'down':\n self.y -= STEP\n elif direction == 'left':\n self.x -= STEP\n elif direction == 'right':\n self.x += STEP\n\nthan what you'd really like to write is:\ndef move(self, direction):\n self.x += direction.dx * STEP\n self.y += direction.dy * STEP\n\nand that's it!\nSo you want to stuff this into either instances:\n# Written in full to give the idea.\n# Consider using collections.namedtuple\nclass Direction(object):\n def __init__(self, dx, dy, name):\n self.dx = dx\n self.dy = dy\n self.name = name\n def __str__(self):\n return self.name\n\nUP = Direction(0, 1, \"up\")\nDOWN = Direction(0, -1, \"down\")\nLEFT = Direction(-1, 0, \"left\")\nRIGHT = Direction(1, 0, \"right\")\n\nor just classes:\nclass Direction(object):\n pass\n\nclass Up(Direction):\n dx = 0\n dy = 1\n\n...\n\nclass Right(Direction):\n dx = 1\n dy = 0\n\nRemember that in Python, classes are also objects (distinct from any other object), and you can compare them: direction == Up etc.\nGenerally, instances are probably cleaner, but if your enumerated concepts have some hierarchical relationship, sometimes modeling them directly with classes is very nice.\n",
"class Directions:\n up = 0\n down = 1\n left = 2\n right =3\n\n",
"I gave a +1 to Kugel, but another leaner option is\ndirUp, dirDown, dirLeft, dirRight = range(4)\n\n\n\n\n(Some time passes)\n\n\n\nSo I was thinking...we have an obvious DRY violation here in that we already specify four items on the LHS, and then again specify four on the RHS. What happens if we add items in the future? What happens when someone else adds them, and maybe they are more sloppy than ourselves? One obvious way to remove the DRY violation is to use the list of enums themselves to assign their values:\n>>> enums = ['dirUp', 'dirDown']\n>>> for v, k in enumerate(enums):\n... exec(k + '=' + str(v))\n... \n>>> print dirDown\n1\n>>> print dirUp\n0\n\nIf you can stomach using exec() for this, then fine. If not, then use the other approach. This current discussion is all academic anyway. However, there is still a problem here. What if the enums are used throughout a great body of source code, and some other programmer comes along and inserts a new value between dirUp and dirDown? This will cause misery because the mapping between the names of the enums and the enums themselves will be wrong. Bear in mind that that remains a problem even in the original simple solution.\nHere, we have the novel idea of using the builtin hash() function to determine our enum value as an int, and we use the text name of the enum itself to determine the hash:\n>>> for k in enums:\n... exec(k + '=' + str(hash(k)))\n... \n>>> dirUp\n-1147857581\n>>> dirDown\n453592598\n>>> enums = ['dirUp', 'dirLeft', 'dirDown']\n>>> for k in enums:\n... exec(k + '=' + str(hash(k)))\n... \n>>> dirUp\n-1147857581\n>>> dirDown\n453592598\n>>> dirLeft\n-300839747\n>>> \n\nNotice that we inserted a new value between dirUp and dirDown, i.e. dirLeft, and our original mapping values for the first two did not change.\nI may actually use this in my own code. Thanks to the OP for posting the question.\n\n\n\n(Some more time passes)\n\n\n\nBeni Cherniavsky-Paskin made some very good comments:\n\nPython's default hash() is not stable across platforms (dangerous for persistence applications)\nThe possibility of collisions is always present.\n\nI tend to agree with both observations. His suggestion is to use the strings themselves (I really like the self-documenting behaviour of using the values) as the hash, and so the code becomes the following (note we use a set instead of a list, to enforce uniqueness):\n>>> items=('dirUp','dirDown','dirLeft','dirRight')\n>>> for i in items:\n exec('{}=\"{}\"'.format(i,i))\n>>> dirDown\n'dirDown'\n\nIt is also trivial to put these in a namespace, so as to avoid collisions with other code:\n>>> class Direction():\n for i in ('dirUp','dirDown','dirLeft','dirRight'):\n exec('{}=\"{}\"'.format(i,i))\n\n>>> Direction.dirUp\n'dirUp'\n\nThe length of the cryptographic hash he mentions can be seen here:\n>>> from hashlib import md5\n>>> crypthash = md5('dirDown'.encode('utf8'))\n>>> crypthash.hexdigest()\n'6a65fd3cd318166a1cc30b3e5e666d8f'\n\n",
"The collections.namedtuple object can provide such a namespace:\n>>> import collections\n>>> dircoll=collections.namedtuple('directions', ('UP', 'DOWN', 'LEFT', 'RIGHT'))\n>>> directions=dircoll(0,1,2,3)\n>>> directions\ndirections(UP=0, DOWN=1, LEFT=2, RIGHT=3)\n>>> directions.DOWN\n1\n>>> \n\n",
"This is simple and effective:\nclass Enum(object):\n def __init__(self, *keys):\n self.__dict__.update(zip(keys, range(len(keys))))\n\nUsage:\n>>> x = Enum('foo', 'bar', 'baz', 'bat')\n>>> x.baz\n2\n>>> x.bat\n3\n\n",
"If you are using Python 2.6+ then you can use namedtuple. They have the advantage having fixed number of properties, and when you need all enum values, you can use it like a tuple. \nFor more control over enum values, you may create your own enumeration class.\ndef enum(args, start=0):\n class Enum(object):\n __slots__ = args.split()\n\n def __init__(self):\n for i, key in enumerate(Enum.__slots__, start):\n setattr(self, key, i)\n\n return Enum()\n\n>>> e_dir = enum('up down left right')\n>>> e_dir.up\n0\n>>> e_dir = enum('up down left right', start=1)\n>>> e_dir.up\n1\n\nDeclaring __slots__ seals your Enum class, no more attributes can be set to an object which was created from a class with __slots__ property.\nYour Enum class can also be namedtuple based, in that case you also get the features of a tuple. See namedtuple docs on subclassing namedtuple\n"
] |
[
69,
48,
17,
14,
13,
7
] |
[] |
[] |
[
"enums",
"python"
] |
stackoverflow_0001969005_enums_python.txt
|
Q:
django's UserCreationForm problem
I have got problem with django's UserCreationForm. It's very strange because ween I:
view:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
form = UserCreationForm()
context = {'form' : form}
render_to_response('something.html', context)
template:
...
{% block content %}
{{form}}
{% endblock %}
I get:
<class 'django.contrib.auth.forms.UserCreationForm'>
Stuff like {{form.as_table}} or similar doesn't work. "For" tags scream that:
aught an exception while rendering: 'ModelFormMetaclass' object is not iterable
I don't know where is the problem. I simply can't view in template labels and fields. HELP:p
A:
You should have missed something in the code.
What must had lead you to this error is:
form = UserCreationForm
{% for field in form1 %}{{ field }}{% endfor %}
Here the error is that you missed the parentheses after UserCreationForm
A:
Could you post the code of the view you're actually trying? It seems as if you've written:
form = UserCreationForm
rather than
form = UserCreationForm()
|
django's UserCreationForm problem
|
I have got problem with django's UserCreationForm. It's very strange because ween I:
view:
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
form = UserCreationForm()
context = {'form' : form}
render_to_response('something.html', context)
template:
...
{% block content %}
{{form}}
{% endblock %}
I get:
<class 'django.contrib.auth.forms.UserCreationForm'>
Stuff like {{form.as_table}} or similar doesn't work. "For" tags scream that:
aught an exception while rendering: 'ModelFormMetaclass' object is not iterable
I don't know where is the problem. I simply can't view in template labels and fields. HELP:p
|
[
"You should have missed something in the code.\nWhat must had lead you to this error is:\nform = UserCreationForm\n\n{% for field in form1 %}{{ field }}{% endfor %}\n\nHere the error is that you missed the parentheses after UserCreationForm\n",
"Could you post the code of the view you're actually trying? It seems as if you've written:\nform = UserCreationForm\n\nrather than\nform = UserCreationForm()\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"authentication",
"django",
"django_forms",
"python"
] |
stackoverflow_0001970218_authentication_django_django_forms_python.txt
|
Q:
Imported functioning is not iterating "TypeError: 'NoneType' object > is not iterable"... how do I make this work?
This is a snip-it of python I am working on right now - I did not list all of this code, so I apologize if something you need is "missing" - I think I can explain it well enough without the rest of it...
Below there is a function main() - this is not explicitly defined in my script - it is imported from another script made by someone else. When it is called, it outputs a very long list of every single available module python has available to call. I am trying to add line numbers to each module. So when it outputs it's a very long list of module names (I assume the function main() is putting "\n" breaks after each module because it prints one module, then a new line, then another module name). What I am TRYING to do is take those values, and add a line number in front of each module name.
elif x == "list" or x == "1":
print "\n loading... please wait"
time.sleep(2)
counter=0
lnumber = 0
all_mods = (main())
for x in all_mods:
print lnumber, x
lnumber = lnumber + 1
counter = counter + 1
print "-" * 30, "\nTotal number of modules detected: ", counter
**I understand the lnumber and counter are reporting the same thing, however I did this on purpose because it is consistent with the code I have elsewhere in the document which did not use this setup.
When this snippet of code is ran (with the other parts of the script) it reports back:
Traceback (most recent call last):
File "C:\Users\jc\Documents\Python Projects\Projects\myOwnfns\helpwiz.py", line 131, in <module>
main_loop()
File "C:\Users\jc\Documents\Python Projects\Projects\myOwnfns\helpwiz.py", line 90, in main_loop
for x in all_mods: #this variable comes from "list_all_mods" - an external script taken from another author.
TypeError: 'NoneType' object is not iterable
A:
The function main prints the lines to standard output; it doesn't return anything. More precisely it returns the None object, so all_mods is None. That's the cause for "'NoneType' object is not iterable", because you're trying to iterate over it with for x in all_mods.
Here's a terribly hackish solution that will work:
import sys, StringIO
buffer = StringIO.StringIO()
sys.stdout = buffer
main()
buffer.seek(0)
all_mods = buffer.read().splitlines()
sys.stdout = sys.__stdout__
A:
I'd recommend refactoring list_all_mods(), if at all possible. In particular, change it to return a list of values, rather than printing them; or turn it into a new function find_all_mods() that returns a list, and redefine list_all_mods():
def list_all_mods():
print '\n'.join(find_all_mods())
I know it's not your code, so this might not be an option. If not, then balpha's hack is probably the best you can do. After that, to print modules with line numbers, you can do:
for (i, module_name) in enumerate(all_mods):
# n.b.: we use i+1 because we want numbering to start from 1.
print "%4d %s" % (i+1, module_name)
p.s., I'm not sure what counts as "all modules" to you, but if it's the modules that are currently imported, you can get this by just looking at sys.modules.keys().
A:
The nl command does this for you.
python the_existing_program.py | nl
Should do what you want.
If you're working in windows, then you can write a version of nl very easily.
import fileinput
for n, line in enumerate( fileinput.input() ):
print "%d %s" % ( n, line )
Let's say you called that nl.py.
python the_existing_program.py | python nl.py
This will work and doesn't require modifications to the original program.
|
Imported functioning is not iterating "TypeError: 'NoneType' object > is not iterable"... how do I make this work?
|
This is a snip-it of python I am working on right now - I did not list all of this code, so I apologize if something you need is "missing" - I think I can explain it well enough without the rest of it...
Below there is a function main() - this is not explicitly defined in my script - it is imported from another script made by someone else. When it is called, it outputs a very long list of every single available module python has available to call. I am trying to add line numbers to each module. So when it outputs it's a very long list of module names (I assume the function main() is putting "\n" breaks after each module because it prints one module, then a new line, then another module name). What I am TRYING to do is take those values, and add a line number in front of each module name.
elif x == "list" or x == "1":
print "\n loading... please wait"
time.sleep(2)
counter=0
lnumber = 0
all_mods = (main())
for x in all_mods:
print lnumber, x
lnumber = lnumber + 1
counter = counter + 1
print "-" * 30, "\nTotal number of modules detected: ", counter
**I understand the lnumber and counter are reporting the same thing, however I did this on purpose because it is consistent with the code I have elsewhere in the document which did not use this setup.
When this snippet of code is ran (with the other parts of the script) it reports back:
Traceback (most recent call last):
File "C:\Users\jc\Documents\Python Projects\Projects\myOwnfns\helpwiz.py", line 131, in <module>
main_loop()
File "C:\Users\jc\Documents\Python Projects\Projects\myOwnfns\helpwiz.py", line 90, in main_loop
for x in all_mods: #this variable comes from "list_all_mods" - an external script taken from another author.
TypeError: 'NoneType' object is not iterable
|
[
"The function main prints the lines to standard output; it doesn't return anything. More precisely it returns the None object, so all_mods is None. That's the cause for \"'NoneType' object is not iterable\", because you're trying to iterate over it with for x in all_mods.\nHere's a terribly hackish solution that will work:\nimport sys, StringIO\nbuffer = StringIO.StringIO()\nsys.stdout = buffer\nmain()\nbuffer.seek(0)\nall_mods = buffer.read().splitlines()\nsys.stdout = sys.__stdout__\n\n",
"I'd recommend refactoring list_all_mods(), if at all possible. In particular, change it to return a list of values, rather than printing them; or turn it into a new function find_all_mods() that returns a list, and redefine list_all_mods():\ndef list_all_mods(): \n print '\\n'.join(find_all_mods())\n\nI know it's not your code, so this might not be an option. If not, then balpha's hack is probably the best you can do. After that, to print modules with line numbers, you can do:\nfor (i, module_name) in enumerate(all_mods):\n # n.b.: we use i+1 because we want numbering to start from 1.\n print \"%4d %s\" % (i+1, module_name)\n\np.s., I'm not sure what counts as \"all modules\" to you, but if it's the modules that are currently imported, you can get this by just looking at sys.modules.keys().\n",
"The nl command does this for you. \npython the_existing_program.py | nl\n\nShould do what you want.\nIf you're working in windows, then you can write a version of nl very easily.\nimport fileinput\nfor n, line in enumerate( fileinput.input() ):\n print \"%d %s\" % ( n, line )\n\nLet's say you called that nl.py.\npython the_existing_program.py | python nl.py\n\nThis will work and doesn't require modifications to the original program.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001970317_python.txt
|
Q:
Should I use Celery or Carrot for a Django project?
I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?
http://github.com/ask/carrot/tree/master
http://github.com/ask/celery/tree/master
A:
If you need to send/receive messages to/from AMQP message queues, use carrot.
If you want to run scheduled tasks on a number of machines, use celery.
If you're making soup, use both ;-)
A:
May you should see this http://www.slideshare.net/idangazit/an-introduction-to-celery
|
Should I use Celery or Carrot for a Django project?
|
I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?
http://github.com/ask/carrot/tree/master
http://github.com/ask/celery/tree/master
|
[
"If you need to send/receive messages to/from AMQP message queues, use carrot.\nIf you want to run scheduled tasks on a number of machines, use celery.\nIf you're making soup, use both ;-)\n",
"May you should see this http://www.slideshare.net/idangazit/an-introduction-to-celery\n"
] |
[
70,
6
] |
[] |
[] |
[
"amqp",
"django",
"message_queue",
"python",
"rabbitmq"
] |
stackoverflow_0001102254_amqp_django_message_queue_python_rabbitmq.txt
|
Q:
Measure time of a function with arguments in Python
I am trying to measure the time of raw_queries(...), unsuccessfully so far. I found that I should use the timeit module. The problem is that I can't (= I don't know how) pass the arguments to the function from the environment.
Important note: Before calling raw_queries, we have to execute phase2() (environment initialization).
Side note: The code is in Python 3.
def raw_queries(queries, nlp):
""" Submit queries without getting visual response """
for q in queries:
nlp.query(q)
def evaluate_queries(queries, nlp):
""" Measure the time that the queries need to return their results """
t = Timer("raw_queries(queries, nlp)", "?????")
print(t.timeit())
def phase2():
""" Load dictionary to memory and subsequently submit queries """
# prepare Linguistic Processor to submit it the queries
all_files = get_files()
b = LinguisticProcessor(all_files)
b.loadDictionary()
# load the queries
queries_file = 'queries.txt'
queries = load_queries(queries_file)
if __name__ == '__main__':
phase2()
Thanks for any help.
UPDATE: We can call phase2() using the second argument of Timer. The problem is that we need the arguments (queries, nlp) from the environment.
UPDATE: The best solution so far, with unutbu's help (only what has changed):
def evaluate_queries():
""" Measure the time that the queries need to return their results """
t = Timer("main.raw_queries(queries, nlp)", "import main;\
(queries,nlp)=main.phase2()")
sf = 'Execution time: {} ms'
print(sf.format(t.timeit(number=1000)))
def phase2():
...
return queries, b
def main():
evaluate_queries()
if __name__ == '__main__':
main()
A:
First, never use the time module to time functions. It can easily lead to wrong conclusions. See timeit versus timing decorator for an example.
The easiest way to time a function call is to use IPython's %timeit command.
There, you simply start an interactive IPython session, call phase2(), define queries,
and then run
%timeit raw_queries(queries,nlp)
The second easiest way that I know to use timeit is to call it from the command-line:
python -mtimeit -s"import test; queries=test.phase2()" "test.raw_queries(queries)"
(In the command above, I assume the script is called test.py)
The idiom here is
python -mtimeit -s"SETUP_COMMANDS" "COMMAND_TO_BE_TIMED"
To be able to pass queries to the raw_queries function call, you have to define the queries variable. In the code you posted queries is defined in phase2(), but only locally. So to setup queries as a global variable, you need to do something like have phase2 return queries:
def phase2():
...
return queries
If you don't want to mess up phase2 this way, create a dummy function:
def phase3():
# Do stuff like phase2() but return queries
return queries
A:
Custom timer function may be a solution:
import time
def timer(fun,*args):
start = time.time()
ret = fun(*args)
end = time.time()
return (ret, end-start)
Using like this:
>>> from math import sin
>>> timer(sin, 0.5)
(0.47942553860420301, 6.9141387939453125e-06)
It means that sin returned 0.479... and it took 6.9e-6 seconds. Make sure your functions run long enough if you want to obtain reliable numbers (not like in the example above).
A:
Normally, you would use timeit.
Examples are here and here.
Also Note:
By default, timeit() temporarily turns
off garbage collection during the
timing. The advantage of this approach
is that it makes independent timings
more comparable. This disadvantage is
that GC may be an important component
of the performance of the function
being measured
Or you can write your own custom timer using the time module.
If you go with a custom timer, remember that you should use time.clock() on windows and time.time() on other platforms. (timeit chooses internally)
import sys
import time
# choose timer to use
if sys.platform.startswith('win'):
default_timer = time.clock
else:
default_timer = time.time
start = default_timer()
# do something
finish = default_timer()
elapsed = (finish - start)
A:
I'm not sure about this, I've never used it, but from what I've read it should be something like this:
....
t = Timer("raw_queries(queries, nlp)", "from __main__ import raw_queries")
print t.timeit()
I took this from http://docs.python.org/library/timeit.html (if this helps).
A:
You don't say so, but are you by any chance trying to make the code go faster? If so, I suggest you not focus in on a particular routine and try to time it. Even if you get a number, it won't really tell you what to fix. If you can pause the program under the IDE several times and examine it's state, including the call stack, it will tell you what is taking the time and why. Here is a link that gives a brief explanation of how and why it works.*
*When you follow the link, you may have to go the the bottom of the previous page of answers. SO is having trouble following a link to an answer.
|
Measure time of a function with arguments in Python
|
I am trying to measure the time of raw_queries(...), unsuccessfully so far. I found that I should use the timeit module. The problem is that I can't (= I don't know how) pass the arguments to the function from the environment.
Important note: Before calling raw_queries, we have to execute phase2() (environment initialization).
Side note: The code is in Python 3.
def raw_queries(queries, nlp):
""" Submit queries without getting visual response """
for q in queries:
nlp.query(q)
def evaluate_queries(queries, nlp):
""" Measure the time that the queries need to return their results """
t = Timer("raw_queries(queries, nlp)", "?????")
print(t.timeit())
def phase2():
""" Load dictionary to memory and subsequently submit queries """
# prepare Linguistic Processor to submit it the queries
all_files = get_files()
b = LinguisticProcessor(all_files)
b.loadDictionary()
# load the queries
queries_file = 'queries.txt'
queries = load_queries(queries_file)
if __name__ == '__main__':
phase2()
Thanks for any help.
UPDATE: We can call phase2() using the second argument of Timer. The problem is that we need the arguments (queries, nlp) from the environment.
UPDATE: The best solution so far, with unutbu's help (only what has changed):
def evaluate_queries():
""" Measure the time that the queries need to return their results """
t = Timer("main.raw_queries(queries, nlp)", "import main;\
(queries,nlp)=main.phase2()")
sf = 'Execution time: {} ms'
print(sf.format(t.timeit(number=1000)))
def phase2():
...
return queries, b
def main():
evaluate_queries()
if __name__ == '__main__':
main()
|
[
"First, never use the time module to time functions. It can easily lead to wrong conclusions. See timeit versus timing decorator for an example.\nThe easiest way to time a function call is to use IPython's %timeit command.\nThere, you simply start an interactive IPython session, call phase2(), define queries,\nand then run\n%timeit raw_queries(queries,nlp)\n\nThe second easiest way that I know to use timeit is to call it from the command-line:\npython -mtimeit -s\"import test; queries=test.phase2()\" \"test.raw_queries(queries)\"\n\n(In the command above, I assume the script is called test.py)\nThe idiom here is \npython -mtimeit -s\"SETUP_COMMANDS\" \"COMMAND_TO_BE_TIMED\"\n\nTo be able to pass queries to the raw_queries function call, you have to define the queries variable. In the code you posted queries is defined in phase2(), but only locally. So to setup queries as a global variable, you need to do something like have phase2 return queries:\ndef phase2():\n ...\n return queries\n\nIf you don't want to mess up phase2 this way, create a dummy function:\ndef phase3():\n # Do stuff like phase2() but return queries\n return queries\n\n",
"Custom timer function may be a solution:\nimport time\n\ndef timer(fun,*args):\n start = time.time()\n ret = fun(*args)\n end = time.time()\n return (ret, end-start)\n\nUsing like this:\n>>> from math import sin\n>>> timer(sin, 0.5)\n(0.47942553860420301, 6.9141387939453125e-06)\n\nIt means that sin returned 0.479... and it took 6.9e-6 seconds. Make sure your functions run long enough if you want to obtain reliable numbers (not like in the example above).\n",
"Normally, you would use timeit.\nExamples are here and here.\nAlso Note:\n\nBy default, timeit() temporarily turns\n off garbage collection during the\n timing. The advantage of this approach\n is that it makes independent timings\n more comparable. This disadvantage is\n that GC may be an important component\n of the performance of the function\n being measured\n\nOr you can write your own custom timer using the time module.\nIf you go with a custom timer, remember that you should use time.clock() on windows and time.time() on other platforms. (timeit chooses internally)\nimport sys\nimport time\n\n# choose timer to use\nif sys.platform.startswith('win'):\n default_timer = time.clock\nelse:\n default_timer = time.time\n\nstart = default_timer()\n# do something\nfinish = default_timer()\nelapsed = (finish - start)\n\n",
"I'm not sure about this, I've never used it, but from what I've read it should be something like this:\n....\nt = Timer(\"raw_queries(queries, nlp)\", \"from __main__ import raw_queries\")\nprint t.timeit()\n\nI took this from http://docs.python.org/library/timeit.html (if this helps).\n",
"You don't say so, but are you by any chance trying to make the code go faster? If so, I suggest you not focus in on a particular routine and try to time it. Even if you get a number, it won't really tell you what to fix. If you can pause the program under the IDE several times and examine it's state, including the call stack, it will tell you what is taking the time and why. Here is a link that gives a brief explanation of how and why it works.*\n*When you follow the link, you may have to go the the bottom of the previous page of answers. SO is having trouble following a link to an answer.\n"
] |
[
6,
2,
2,
1,
0
] |
[] |
[] |
[
"arguments",
"performance",
"python",
"time",
"timeit"
] |
stackoverflow_0001966750_arguments_performance_python_time_timeit.txt
|
Q:
Crash reporting in Python
Is there a crash reporting framework that can be used for pure Python Tkinter applications? Ideally, it should work cross-platform.
Practically speaking, this is more of 'exception reporting' since the Python interpreter itself hardly crashes.
Here's a sample crash reporter:
A:
Rather than polluting your code with try..except everywhere, you should just implement your own except hook by setting sys.excepthook. Here is an example:
import sys
import traceback
def install_excepthook():
def my_excepthook(exctype, value, tb):
s = ''.join(traceback.format_exception(exctype, value, tb))
dialog = ErrorReportDialog(None, s)
dialog.exec_()
sys.excepthook = my_excepthook
Call install_exception() when your application starts.
ErrorReportDialog is a Qt dialog I've made. traceback.format_exception() will format argument passed to the except hook in the same way it does in Python's interpreter.
EDIT: I forgot to mention a little gotcha with that. It doesn't work with threads (well, at least it didn't last time I checked). For code running in another thread, you will need to wrap it in a try..except block.
A:
Stick try excepts everywhere your application can crash (I/O, networking etc.). Whenever an except is called, call a function that will kill the old window, spawn a new tkinter notification window, or a custom one with your error message.
Do a root.after to the new window and send your error report (urllib).
Put a restart button if you wish.
There is no crash reporting framework - as tkinter is not that type of GUI. It's pretty much a wrapper for simple command line apps.
Go pyqt/gtk or wxpython if you want the features seen in the screen-shot above. But I'm pretty sure that where ever you go, you'll have to write your own reporter.
|
Crash reporting in Python
|
Is there a crash reporting framework that can be used for pure Python Tkinter applications? Ideally, it should work cross-platform.
Practically speaking, this is more of 'exception reporting' since the Python interpreter itself hardly crashes.
Here's a sample crash reporter:
|
[
"Rather than polluting your code with try..except everywhere, you should just implement your own except hook by setting sys.excepthook. Here is an example:\nimport sys\nimport traceback\n\ndef install_excepthook():\n def my_excepthook(exctype, value, tb):\n s = ''.join(traceback.format_exception(exctype, value, tb))\n dialog = ErrorReportDialog(None, s)\n dialog.exec_()\n\n sys.excepthook = my_excepthook\n\nCall install_exception() when your application starts.\nErrorReportDialog is a Qt dialog I've made. traceback.format_exception() will format argument passed to the except hook in the same way it does in Python's interpreter.\nEDIT: I forgot to mention a little gotcha with that. It doesn't work with threads (well, at least it didn't last time I checked). For code running in another thread, you will need to wrap it in a try..except block.\n",
"Stick try excepts everywhere your application can crash (I/O, networking etc.). Whenever an except is called, call a function that will kill the old window, spawn a new tkinter notification window, or a custom one with your error message. \nDo a root.after to the new window and send your error report (urllib). \nPut a restart button if you wish.\nThere is no crash reporting framework - as tkinter is not that type of GUI. It's pretty much a wrapper for simple command line apps.\nGo pyqt/gtk or wxpython if you want the features seen in the screen-shot above. But I'm pretty sure that where ever you go, you'll have to write your own reporter.\n"
] |
[
7,
2
] |
[] |
[] |
[
"crash_reports",
"python",
"tkinter"
] |
stackoverflow_0001964336_crash_reports_python_tkinter.txt
|
Q:
Django specific sql query
how can I execute such query in django:
SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)
In the latest SVN release we can use:
keywords = Keyword.objects.raw('SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)')
But RawQuerySet doesn't support filter(), count(), indexing and other things. Is there another way?
A:
Keyword.objects.exclude(id__in=PageKeyword.objects.all()
Keyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))
For future reference, exclude is documented here.
Edit: Yes, you are right; I corrected my answer. See above.
Edit: Even more readable:
Keyword.objects.exclude(pagekeyword__in=PageKeyword.objects.all())
A:
I've tested your code and it works not as expected,
here is the right solution for my task:
Keyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))
|
Django specific sql query
|
how can I execute such query in django:
SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)
In the latest SVN release we can use:
keywords = Keyword.objects.raw('SELECT * FROM keywords_keyword WHERE id not in (SELECT keyword_id FROM sites_pagekeyword)')
But RawQuerySet doesn't support filter(), count(), indexing and other things. Is there another way?
|
[
"\nKeyword.objects.exclude(id__in=PageKeyword.objects.all()\n\nKeyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))\n\nFor future reference, exclude is documented here.\n\nEdit: Yes, you are right; I corrected my answer. See above.\n\nEdit: Even more readable:\nKeyword.objects.exclude(pagekeyword__in=PageKeyword.objects.all())\n\n",
"I've tested your code and it works not as expected,\nhere is the right solution for my task:\nKeyword.objects.exclude(id__in=PageKeyword.objects.values('keyword_id'))\n\n"
] |
[
8,
1
] |
[] |
[] |
[
"django",
"django_models",
"python",
"sql"
] |
stackoverflow_0001970718_django_django_models_python_sql.txt
|
Q:
Open a new browser window from a Python script in Google App Engine
A Python script at Google App Engine fetches data into a HTML page.
What is the best way to open a new browser window from the script or HTML page?
JavaScript doesn't work.
A:
The only way to automatically open a new window in a browser is JavaScript (using window.open()).
If you can't use JavaScript, you can simply add a link to your html page with a _blank target that will open a new window (or sometimes a new tab if the user has configured this browser to do so) :
<a href="newPage.html" target="_blank">Link text</a>
This won't be automatic, ie the user will have to manually click on the link, whereas you could have the window opened without user interaction using javascript (but be aware that window.open() is sometimes blocked by popup blockers).
A:
I tried for testing purposes to insert this code:
<SCRIPT LANGUAGE="JavaScript">
function openindex()
{
OpenWindow=window.open("", "newwin", "height=250, width=250,toolbar=no,scrollbars="+scroll+",menubar=no");
OpenWindow.document.write("<TITLE>Title Goes Here</TITLE>")
OpenWindow.document.write("<BODY BGCOLOR=pink>")
OpenWindow.document.write("<h1>Hello!</h1>")
OpenWindow.document.write("This text will appear in the window!")
OpenWindow.document.write("</BODY>")
OpenWindow.document.write("</HTML>")
OpenWindow.document.close()
self.name="main"
}
</SCRIPT>
The code is stolen from here:
http://www.htmlgoodies.com/beyond/javascript/article.php/3471221
The whole code including the SCRIPT tags was inside the HTML-Page but no new browser window was created.
I tried with Opera and Firefox and I have no popup blocker installed.
A:
Regarding the above code posted by Neverland: the code that you stole simply defines a JavaScript function. The function still needs to be called somewhere in order to run. You could put it in the onLoad handler of the BODY tag or in an onClick handler of a button or link.
The answer to your question has nothing to do with Python or AppEngine. This is basic JavaScript programming.
A:
This code did work, maybe you need call the function, or checkout the contents settings tab, enabling the javascript checkbox (in firefox)
<SCRIPT LANGUAGE="JavaScript">
function openindex(){
OpenWindow=window.open("", "newwin", "height=250,width=250,toolbar=no,scrollbars="+scroll+",menubar=no");
OpenWindow.document.write("<TITLE>Title Goes Here</TITLE>")
OpenWindow.document.write("<BODY BGCOLOR=pink>")
OpenWindow.document.write("<h1>Hello!</h1>")
OpenWindow.document.write("This text will appear in the window!")
OpenWindow.document.write("</BODY>")
OpenWindow.document.write("</HTML>")
OpenWindow.document.close()
self.name="main"
}
</SCRIPT>
<button onclick="openindex()">open window</button>
|
Open a new browser window from a Python script in Google App Engine
|
A Python script at Google App Engine fetches data into a HTML page.
What is the best way to open a new browser window from the script or HTML page?
JavaScript doesn't work.
|
[
"The only way to automatically open a new window in a browser is JavaScript (using window.open()).\nIf you can't use JavaScript, you can simply add a link to your html page with a _blank target that will open a new window (or sometimes a new tab if the user has configured this browser to do so) :\n<a href=\"newPage.html\" target=\"_blank\">Link text</a>\n\nThis won't be automatic, ie the user will have to manually click on the link, whereas you could have the window opened without user interaction using javascript (but be aware that window.open() is sometimes blocked by popup blockers).\n",
"I tried for testing purposes to insert this code:\n<SCRIPT LANGUAGE=\"JavaScript\">\n\nfunction openindex()\n {\nOpenWindow=window.open(\"\", \"newwin\", \"height=250, width=250,toolbar=no,scrollbars=\"+scroll+\",menubar=no\");\nOpenWindow.document.write(\"<TITLE>Title Goes Here</TITLE>\")\nOpenWindow.document.write(\"<BODY BGCOLOR=pink>\")\nOpenWindow.document.write(\"<h1>Hello!</h1>\")\nOpenWindow.document.write(\"This text will appear in the window!\")\nOpenWindow.document.write(\"</BODY>\")\nOpenWindow.document.write(\"</HTML>\")\n\nOpenWindow.document.close()\nself.name=\"main\"\n }\n</SCRIPT>\n\nThe code is stolen from here:\nhttp://www.htmlgoodies.com/beyond/javascript/article.php/3471221\nThe whole code including the SCRIPT tags was inside the HTML-Page but no new browser window was created.\nI tried with Opera and Firefox and I have no popup blocker installed.\n",
"Regarding the above code posted by Neverland: the code that you stole simply defines a JavaScript function. The function still needs to be called somewhere in order to run. You could put it in the onLoad handler of the BODY tag or in an onClick handler of a button or link.\nThe answer to your question has nothing to do with Python or AppEngine. This is basic JavaScript programming.\n",
"This code did work, maybe you need call the function, or checkout the contents settings tab, enabling the javascript checkbox (in firefox)\n<SCRIPT LANGUAGE=\"JavaScript\">\nfunction openindex(){\n OpenWindow=window.open(\"\", \"newwin\", \"height=250,width=250,toolbar=no,scrollbars=\"+scroll+\",menubar=no\");\n OpenWindow.document.write(\"<TITLE>Title Goes Here</TITLE>\")\n OpenWindow.document.write(\"<BODY BGCOLOR=pink>\")\n OpenWindow.document.write(\"<h1>Hello!</h1>\")\n OpenWindow.document.write(\"This text will appear in the window!\")\n OpenWindow.document.write(\"</BODY>\")\n OpenWindow.document.write(\"</HTML>\")\n\n OpenWindow.document.close()\n self.name=\"main\"\n}\n </SCRIPT>\n <button onclick=\"openindex()\">open window</button>\n\n"
] |
[
3,
0,
0,
-1
] |
[] |
[] |
[
"google_app_engine",
"javascript",
"open_source",
"python"
] |
stackoverflow_0001930511_google_app_engine_javascript_open_source_python.txt
|
Q:
How do I sudo the current process?
Is it possible to use a sudo frontend (like gksudo) to elevate the privileges of the current process? I know I can do the following:
sudo cat /etc/passwd-
But I'm interested in doing this:
sudo-become-root # magic function/command
cat /etc/passwd-
I'm writing in Python. My usecase is that I have a program that runs as the user, but may encounter files to read/write that are root-owned. I'd like to prompt for password, gain root privileges, do what I need, and then optionally drop privileges again.
I know I could separate admin logic and non-admin logic into separate processes, and then just run the admin process as root (with some communication -- policykit/dbus would be a good fit here). But I was hoping for a much simpler (though admittedly more risky) solution.
I'm thinking something like running Solaris's ppriv through sudo to then modify the current process's privileges. Which seems like a hacky-but-workable roundtrip. But as far as I know, linux doesn't offer ppriv.
(I'm surprised this isn't obvious already; it seems like a not-uncommon thing to want and doesn't seem to be a security hole to allow escalation in-process over escalation of a new process.)
A:
Aptitude has a "become root" option. You may wish to see what the author did there.
A:
If you want to deal cleanly with administrative rights inside a program, you might want to use PolicyKit rather than sudo, depending on the OS you plan to run your program on.
For PolicyKit for Python, see python-slip.
Otherwise, there are two ways to call sudo to become root:
sudo -s
will make you root and keep your current environment (equivalent to sudo su)
sudo -i
will make you root and give you root's environment, too (equivalent to sudo su -)
Another way of dealing with the problem is to consider that you have the rights you need, and let the user of the program choose how to give the rights to your program (using sudo/setuid/unix groups/whatever else).
See also this question on ServerFault on the same subject.
A:
Unfortunately, I'm not aware of a way to do what you want to do cleanly. I think your best bet is to make the program setuid (or run it under sudo) and then either do your dirty work and drop permissions, or fork() and drop permissions from one process and keep the other one around to do your root work.
What you're looking for are the setuid(2) / setreuid(2) / setregid(2) / setgroups(2) calls, but they are all hard wired to not allow you to gain privileges mid-invocation. You can only use them to "give away" privileges, as far as I know.
A:
Your magic function/command could be
sudo su
A:
echo 'echo tee; echo hee'|sudo -s
The output is:
tee
hee
A:
I don't like the idea of being able to run arbitrary commands as root from a lower privileged process. However, since you want it, one of the ideas that comes to mind is to keep a setuid restricted shell which can only execute the commands you're interested in allowing. You can then use the subprocess.Popen functions to run your command using this restricted shell that will run it with elevated privileges.
A:
I wonder if this would work:
Add another group to your system, install the script as a root program and have the sudoers file contain a line that allows the script to be executed by this group. Finally add the group to the list of accounts that need to run the script.
Then the script can only be run by root or any account that has the special group in the group set after supplying the account password at the start.
See Sudo Manual for other options.
A:
You want to authenticate with PAM. There's an example here.
|
How do I sudo the current process?
|
Is it possible to use a sudo frontend (like gksudo) to elevate the privileges of the current process? I know I can do the following:
sudo cat /etc/passwd-
But I'm interested in doing this:
sudo-become-root # magic function/command
cat /etc/passwd-
I'm writing in Python. My usecase is that I have a program that runs as the user, but may encounter files to read/write that are root-owned. I'd like to prompt for password, gain root privileges, do what I need, and then optionally drop privileges again.
I know I could separate admin logic and non-admin logic into separate processes, and then just run the admin process as root (with some communication -- policykit/dbus would be a good fit here). But I was hoping for a much simpler (though admittedly more risky) solution.
I'm thinking something like running Solaris's ppriv through sudo to then modify the current process's privileges. Which seems like a hacky-but-workable roundtrip. But as far as I know, linux doesn't offer ppriv.
(I'm surprised this isn't obvious already; it seems like a not-uncommon thing to want and doesn't seem to be a security hole to allow escalation in-process over escalation of a new process.)
|
[
"Aptitude has a \"become root\" option. You may wish to see what the author did there.\n",
"If you want to deal cleanly with administrative rights inside a program, you might want to use PolicyKit rather than sudo, depending on the OS you plan to run your program on.\nFor PolicyKit for Python, see python-slip.\nOtherwise, there are two ways to call sudo to become root:\nsudo -s\n\nwill make you root and keep your current environment (equivalent to sudo su)\nsudo -i\n\nwill make you root and give you root's environment, too (equivalent to sudo su -)\nAnother way of dealing with the problem is to consider that you have the rights you need, and let the user of the program choose how to give the rights to your program (using sudo/setuid/unix groups/whatever else).\nSee also this question on ServerFault on the same subject.\n",
"Unfortunately, I'm not aware of a way to do what you want to do cleanly. I think your best bet is to make the program setuid (or run it under sudo) and then either do your dirty work and drop permissions, or fork() and drop permissions from one process and keep the other one around to do your root work.\nWhat you're looking for are the setuid(2) / setreuid(2) / setregid(2) / setgroups(2) calls, but they are all hard wired to not allow you to gain privileges mid-invocation. You can only use them to \"give away\" privileges, as far as I know.\n",
"Your magic function/command could be\nsudo su\n\n",
"echo 'echo tee; echo hee'|sudo -s\n\nThe output is:\ntee\nhee\n\n",
"I don't like the idea of being able to run arbitrary commands as root from a lower privileged process. However, since you want it, one of the ideas that comes to mind is to keep a setuid restricted shell which can only execute the commands you're interested in allowing. You can then use the subprocess.Popen functions to run your command using this restricted shell that will run it with elevated privileges.\n",
"I wonder if this would work:\nAdd another group to your system, install the script as a root program and have the sudoers file contain a line that allows the script to be executed by this group. Finally add the group to the list of accounts that need to run the script.\nThen the script can only be run by root or any account that has the special group in the group set after supplying the account password at the start.\nSee Sudo Manual for other options.\n",
"You want to authenticate with PAM. There's an example here.\n"
] |
[
3,
1,
1,
0,
0,
0,
0,
0
] |
[] |
[] |
[
"gksudo",
"linux",
"python",
"root"
] |
stackoverflow_0001970329_gksudo_linux_python_root.txt
|
Q:
how to "export CFLAGS='my -flags -here' from python script
I'm writing a python program that needs to set the environment CFLAGS as needed.
I'm using the subprocess module to perform some operations, but, I'm not sure this is the correct way of doing this.
The script will first set the CFLAGS and then compile some code, so the cflags need to stay put while the code is compiled.
I know there is the os.environ['CXXFLAGS'] which defaults to "" in my system. So my question is, do I just need to set the os.environ['CXXFLAGS'] value before compiling the code, or do I need to do it some other way?
Please advise
A:
You can do this without modifying the python process's environment.
# Make a copy of the environment and modify that.
myenv = dict(os.environ)
myenv["CXXFLAGS"] = "-DFOO"
# Pass the modified environment to the subprocess.
subprocess.check_call(["make", "install"], env=myenv)
See the documentation for Python's subprocess module.
A:
Setting it in the environment by modifying os.environ['CXXFLAGS'] should work. However, the way I've always passed extra CXXFLAGS to ./configure is by passing it on the command line, e.g.:
cmd = [
'./configure',
'CXXFLAGS=-O2 -march=i586 -mtune=i686',
]
subprocess.Popen(cmd)
When done this way, you shouldn't need to set CXXFLAGS in the environment or explicitly pass it to make (autotools will create the Makefiles so that they include your custom CXXFLAGS).
|
how to "export CFLAGS='my -flags -here' from python script
|
I'm writing a python program that needs to set the environment CFLAGS as needed.
I'm using the subprocess module to perform some operations, but, I'm not sure this is the correct way of doing this.
The script will first set the CFLAGS and then compile some code, so the cflags need to stay put while the code is compiled.
I know there is the os.environ['CXXFLAGS'] which defaults to "" in my system. So my question is, do I just need to set the os.environ['CXXFLAGS'] value before compiling the code, or do I need to do it some other way?
Please advise
|
[
"You can do this without modifying the python process's environment.\n# Make a copy of the environment and modify that.\nmyenv = dict(os.environ)\nmyenv[\"CXXFLAGS\"] = \"-DFOO\"\n\n# Pass the modified environment to the subprocess.\nsubprocess.check_call([\"make\", \"install\"], env=myenv)\n\nSee the documentation for Python's subprocess module.\n",
"Setting it in the environment by modifying os.environ['CXXFLAGS'] should work. However, the way I've always passed extra CXXFLAGS to ./configure is by passing it on the command line, e.g.:\ncmd = [\n './configure',\n 'CXXFLAGS=-O2 -march=i586 -mtune=i686',\n]\nsubprocess.Popen(cmd)\n\nWhen done this way, you shouldn't need to set CXXFLAGS in the environment or explicitly pass it to make (autotools will create the Makefiles so that they include your custom CXXFLAGS).\n"
] |
[
1,
0
] |
[] |
[] |
[
"compiler_flags",
"python"
] |
stackoverflow_0001971344_compiler_flags_python.txt
|
Q:
convert byte array to string without interpreting the bytes?
I have a GSM date/time stamp from a PDU encoded SMS it is formatted as so
\x90,\x21,\x51,\x91,\x40,\x33
format yy,mm,dd,hh,mm,ss
I have read them from a binary file into a byte array. I want to convert them to a string but without doing any decoding I want to end up with a string that contains 902151914033. I then need to reverse each 2 characters in the string.
Can anyone give me some pointers?
Many Thanks
A:
This should get you started:
>>> s = b'\x90\x21\x51\x91\x40\x33'
>>> lst = [hex(z)[2:] for z in s]
>>> lst
['90', '21', '51', '91', '40', '33']
>>> string = ''.join(hex(z)[3:1:-1] for z in s)
>>> string
'091215190433'
A:
To convert to hex:
hexdata = ''.join('%02x' % ord(byte) for byte in bindata)
To reverse every other hex character (if I'm understanding correctly):
hexdata = ''.join(('%02x' % ord(byte))[::-1] for byte in bindata)
A:
What you mean is that you do want to do some processing! The unprocessed bytes are most easily represented as characters.
I think what you want is something along the lines of:
r = ''
for num in array:
r += '%2X' % num
return r
Which I'm sure could be wrapped up in an anonymous function, if necessary.
A:
If, in your question, the string you have provided is the literal set of bytes (as ascii) including the \ and , and you wish to strip them out you could use the binascii module and str.replace:
import binascii
qp = binascii.b2a_qp( bunchabytes )
plainstring = qp.replace( '\\x', '' ).replace( ',', '' )
The resultant plainstring will consist of only the digits.
A:
switcher= dict(
(n1*16 + n2, n2*16 + n1)
for n1 in range(16)
for n2 in range(16)
)
def nibble_switcher(bindata):
return type(bindata)(switcher[i] for i in bindata)
# will work with many types, not only bytearray
def nibble_switcher_as_hex_string(bindata):
return ''.join("%02x" % i for i in nibble_switcher(bindata))
|
convert byte array to string without interpreting the bytes?
|
I have a GSM date/time stamp from a PDU encoded SMS it is formatted as so
\x90,\x21,\x51,\x91,\x40,\x33
format yy,mm,dd,hh,mm,ss
I have read them from a binary file into a byte array. I want to convert them to a string but without doing any decoding I want to end up with a string that contains 902151914033. I then need to reverse each 2 characters in the string.
Can anyone give me some pointers?
Many Thanks
|
[
"This should get you started:\n>>> s = b'\\x90\\x21\\x51\\x91\\x40\\x33'\n>>> lst = [hex(z)[2:] for z in s]\n>>> lst\n['90', '21', '51', '91', '40', '33']\n\n>>> string = ''.join(hex(z)[3:1:-1] for z in s)\n>>> string\n'091215190433'\n\n",
"To convert to hex:\nhexdata = ''.join('%02x' % ord(byte) for byte in bindata)\nTo reverse every other hex character (if I'm understanding correctly):\nhexdata = ''.join(('%02x' % ord(byte))[::-1] for byte in bindata)\n",
"What you mean is that you do want to do some processing! The unprocessed bytes are most easily represented as characters.\nI think what you want is something along the lines of:\nr = ''\nfor num in array:\n r += '%2X' % num\nreturn r\n\nWhich I'm sure could be wrapped up in an anonymous function, if necessary.\n",
"If, in your question, the string you have provided is the literal set of bytes (as ascii) including the \\ and , and you wish to strip them out you could use the binascii module and str.replace:\nimport binascii\nqp = binascii.b2a_qp( bunchabytes )\nplainstring = qp.replace( '\\\\x', '' ).replace( ',', '' )\n\nThe resultant plainstring will consist of only the digits.\n",
"switcher= dict(\n (n1*16 + n2, n2*16 + n1)\n for n1 in range(16)\n for n2 in range(16)\n)\n\ndef nibble_switcher(bindata):\n return type(bindata)(switcher[i] for i in bindata)\n # will work with many types, not only bytearray\n\ndef nibble_switcher_as_hex_string(bindata):\n return ''.join(\"%02x\" % i for i in nibble_switcher(bindata))\n\n"
] |
[
5,
5,
1,
0,
0
] |
[] |
[] |
[
"bytearray",
"decode",
"python"
] |
stackoverflow_0001916928_bytearray_decode_python.txt
|
Q:
Python, Huge Iteration Performance Problem
I'm doing an iteration through 3 words, each about 5 million characters long, and I want to find sequences of 20 characters that identifies each word. That is, I want to find all sequences of length 20 in one word that is unique for that word. My problem is that the code I've written takes an extremely long time to run. I've never even completed one word running my program over night.
The function below takes a list containing dictionaries where each dictionary contains each possible word of 20 and its location from one of the 5 million long words.
If anybody has an idea how to optimize this I would be really thankful, I don't have a clue how to continue...
here's a sample of my code:
def findUnique(list):
# Takes a list with dictionaries and compairs each element in the dictionaries
# with the others and puts all unique element in new dictionaries and finally
# puts the new dictionaries in a list.
# The result is a list with (in this case) 3 dictionaries containing all unique
# sequences and their locations from each string.
dicList=[]
listlength=len(list)
s=0
valuelist=[]
for i in list:
j=i.values()
valuelist.append(j)
while s<listlength:
currdic=list[s]
dic={}
for key in currdic:
currval=currdic[key]
test=True
n=0
while n<listlength:
if n!=s:
if currval in valuelist[n]: #this is where it takes to much time
n=listlength
test=False
else:
n+=1
else:
n+=1
if test:
dic[key]=currval
dicList.append(dic)
s+=1
return dicList
A:
def slices(seq, length, prefer_last=False):
unique = {}
if prefer_last: # this doesn't have to be a parameter, just choose one
for start in xrange(len(seq) - length + 1):
unique[seq[start:start+length]] = start
else: # prefer first
for start in xrange(len(seq) - length, -1, -1):
unique[seq[start:start+length]] = start
return unique
# or find all locations for each slice:
import collections
def slices(seq, length):
unique = collections.defaultdict(list)
for start in xrange(len(seq) - length + 1):
unique[seq[start:start+length]].append(start)
return unique
This function (currently in my iter_util module) is O(n) (n being the length of each word) and you would use set(slices(..)) (with set operations such as difference) to get slices unique across all words (example below). You could also write the function to return a set, if you don't want to track locations. Memory usage will be high (though still O(n), just a large factor), possibly mitigated (though not by much if length is only 20) with a special "lazy slice" class that stores the base sequence (the string) plus start and stop (or start and length).
Printing unique slices:
a = set(slices("aab", 2)) # {"aa", "ab"}
b = set(slices("abb", 2)) # {"ab", "bb"}
c = set(slices("abc", 2)) # {"ab", "bc"}
all = [a, b, c]
import operator
a_unique = reduce(operator.sub, (x for x in all if x is not a), a)
print a_unique # {"aa"}
Including locations:
a = slices("aab", 2)
b = slices("abb", 2)
c = slices("abc", 2)
all = [a, b, c]
import operator
a_unique = reduce(operator.sub, (set(x) for x in all if x is not a), set(a))
# a_unique is only the keys so far
a_unique = dict((k, a[k]) for k in a_unique)
# now it's a dict of slice -> location(s)
print a_unique # {"aa": 0} or {"aa": [0]}
# (depending on which slices function used)
In a test script closer to your conditions, using randomly generated words of 5m characters and a slice length of 20, memory usage was so high that my test script quickly hit my 1G main memory limit and started thrashing virtual memory. At that point Python spent very little time on the CPU and I killed it. Reducing either the slice length or word length (since I used completely random words that reduces duplicates and increases memory use) to fit within main memory and it ran under a minute. This situation plus O(n**2) in your original code will take forever, and is why algorithmic time and space complexity are both important.
import operator
import random
import string
def slices(seq, length):
unique = {}
for start in xrange(len(seq) - length, -1, -1):
unique[seq[start:start+length]] = start
return unique
def sample_with_repeat(population, length, choice=random.choice):
return "".join(choice(population) for _ in xrange(length))
word_length = 5*1000*1000
words = [sample_with_repeat(string.lowercase, word_length) for _ in xrange(3)]
slice_length = 20
words_slices_sets = [set(slices(x, slice_length)) for x in words]
unique_words_slices = [reduce(operator.sub,
(x for x in words_slices_sets if x is not n),
n)
for n in words_slices_sets]
print [len(x) for x in unique_words_slices]
A:
You say you have a "word" 5 million characters long, but I find it hard to believe this is a word in the usual sense.
If you can provide more information about your input data, a specific solution might be available.
For example, English text (or any other written language) might be sufficiently repetitive that a trie would be useable. In the worst case however, it would run out of memory constructing all 256^20 keys. Knowing your inputs makes all the difference.
edit
I took a look at some genome data to see how this idea stacked up, using a hardcoded [acgt]->[0123] mapping and 4 children per trie node.
adenovirus 2: 35,937bp -> 35,899 distinct 20-base sequences using 469,339 trie nodes
enterobacteria phage lambda: 48,502bp -> 40,921 distinct 20-base sequences using 529,384 trie nodes.
I didn't get any collisions, either within or between the two data sets, although maybe there is more redundancy and/or overlap in your data. You'd have to try it to see.
If you do get a useful number of collisions, you could try walking the three inputs together, building a single trie, recording the origin of each leaf and pruning collisions from the trie as you go.
If you can't find some way to prune the keys, you could try using a more compact representation. For example you only need 2 bits to store [acgt]/[0123], which might save you space at the cost of slightly more complex code.
I don't think you can just brute force this though - you need to find some way to reduce the scale of the problem, and that depends on your domain knowledge.
A:
Let me build off Roger Pate's answer. If memory is an issue, I'd suggest instead of using the strings as the keys to the dictionary, you could use a hashed value of the string. This would save the cost of the storing the extra copy of the strings as the keys (at worst, 20 times the storage of an individual "word").
import collections
def hashed_slices(seq, length, hasher=None):
unique = collections.defaultdict(list)
for start in xrange(len(seq) - length + 1):
unique[hasher(seq[start:start+length])].append(start)
return unique
(If you really want to get fancy, you can use a rolling hash, though you'll need to change the function.)
Now, we can combine all the hashes :
unique = [] # Unique words in first string
# create a dictionary of hash values -> word index -> start position
hashed_starts = [hashed_slices(word, 20, hashing_fcn) for word in words]
all_hashed = collections.defaultdict(dict)
for i, hashed in enumerate(hashed_starts) :
for h, starts in hashed.iteritems() :
# We only care about the first word
if h in hashed_starts[0] :
all_hashed[h][i]=starts
# Now check all hashes
for starts_by_word in all_hashed.itervalues() :
if len(starts_by_word) == 1 :
# if there's only one word for the hash, it's obviously valid
unique.extend(words[0][i:i+20] for i in starts_by_word.values())
else :
# we might have a hash collision
candidates = {}
for word_idx, starts in starts_by_word.iteritems() :
candidates[word_idx] = set(words[word_idx][j:j+20] for j in starts)
# Now go that we have the candidate slices, find the unique ones
valid = candidates[0]
for word_idx, candidate_set in candidates.iteritems() :
if word_idx != 0 :
valid -= candidate_set
unique.extend(valid)
(I tried extending it to do all three. It's possible, but the complications would detract from the algorithm.)
Be warned, I haven't tested this. Also, there's probably a lot you can do to simplify the code, but the algorithm makes sense. The hard part is choosing the hash. Too many collisions and you'll won't gain anything. Too few and you'll hit the memory problems. If you are dealing with just DNA base codes, you can hash the 20-character string to a 40-bit number, and still have no collisions. So the slices will take up nearly a fourth of the memory. That would save roughly 250 MB of memory in Roger Pate's answer.
The code is still O(N^2), but the constant should be much lower.
A:
Let's attempt to improve on Roger Pate's excellent answer.
Firstly, let's keep sets instead of dictionaries - they manage uniqueness anyway.
Secondly, since we are likely to run out of memory faster than we run out of CPU time (and patience), we can sacrifice CPU efficiency for the sake of memory efficiency. So perhaps try only the 20s starting with one particular letter. For DNA, this cuts the requirements down by 75%.
seqlen = 20
maxlength = max([len(word) for word in words])
for startletter in letters:
for letterid in range(maxlength):
for wordid,word in words:
if (letterid < len(word)):
letter = word[letterid]
if letter is startletter:
seq = word[letterid:letterid+seqlen]
if seq in seqtrie and not wordid in seqtrie[seq]:
seqtrie[seq].append(wordid)
Or, if that's still too much memory, we can go through for each possible starting pair (16 passes instead of 4 for DNA), or every 3 (64 passes) etc.
|
Python, Huge Iteration Performance Problem
|
I'm doing an iteration through 3 words, each about 5 million characters long, and I want to find sequences of 20 characters that identifies each word. That is, I want to find all sequences of length 20 in one word that is unique for that word. My problem is that the code I've written takes an extremely long time to run. I've never even completed one word running my program over night.
The function below takes a list containing dictionaries where each dictionary contains each possible word of 20 and its location from one of the 5 million long words.
If anybody has an idea how to optimize this I would be really thankful, I don't have a clue how to continue...
here's a sample of my code:
def findUnique(list):
# Takes a list with dictionaries and compairs each element in the dictionaries
# with the others and puts all unique element in new dictionaries and finally
# puts the new dictionaries in a list.
# The result is a list with (in this case) 3 dictionaries containing all unique
# sequences and their locations from each string.
dicList=[]
listlength=len(list)
s=0
valuelist=[]
for i in list:
j=i.values()
valuelist.append(j)
while s<listlength:
currdic=list[s]
dic={}
for key in currdic:
currval=currdic[key]
test=True
n=0
while n<listlength:
if n!=s:
if currval in valuelist[n]: #this is where it takes to much time
n=listlength
test=False
else:
n+=1
else:
n+=1
if test:
dic[key]=currval
dicList.append(dic)
s+=1
return dicList
|
[
"def slices(seq, length, prefer_last=False):\n unique = {}\n if prefer_last: # this doesn't have to be a parameter, just choose one\n for start in xrange(len(seq) - length + 1):\n unique[seq[start:start+length]] = start\n else: # prefer first\n for start in xrange(len(seq) - length, -1, -1):\n unique[seq[start:start+length]] = start\n return unique\n\n# or find all locations for each slice:\nimport collections\ndef slices(seq, length):\n unique = collections.defaultdict(list)\n for start in xrange(len(seq) - length + 1):\n unique[seq[start:start+length]].append(start)\n return unique\n\nThis function (currently in my iter_util module) is O(n) (n being the length of each word) and you would use set(slices(..)) (with set operations such as difference) to get slices unique across all words (example below). You could also write the function to return a set, if you don't want to track locations. Memory usage will be high (though still O(n), just a large factor), possibly mitigated (though not by much if length is only 20) with a special \"lazy slice\" class that stores the base sequence (the string) plus start and stop (or start and length).\nPrinting unique slices:\na = set(slices(\"aab\", 2)) # {\"aa\", \"ab\"}\nb = set(slices(\"abb\", 2)) # {\"ab\", \"bb\"}\nc = set(slices(\"abc\", 2)) # {\"ab\", \"bc\"}\nall = [a, b, c]\nimport operator\na_unique = reduce(operator.sub, (x for x in all if x is not a), a)\nprint a_unique # {\"aa\"}\n\nIncluding locations:\na = slices(\"aab\", 2)\nb = slices(\"abb\", 2)\nc = slices(\"abc\", 2)\nall = [a, b, c]\nimport operator\na_unique = reduce(operator.sub, (set(x) for x in all if x is not a), set(a))\n# a_unique is only the keys so far\na_unique = dict((k, a[k]) for k in a_unique)\n# now it's a dict of slice -> location(s)\nprint a_unique # {\"aa\": 0} or {\"aa\": [0]}\n # (depending on which slices function used)\n\n\nIn a test script closer to your conditions, using randomly generated words of 5m characters and a slice length of 20, memory usage was so high that my test script quickly hit my 1G main memory limit and started thrashing virtual memory. At that point Python spent very little time on the CPU and I killed it. Reducing either the slice length or word length (since I used completely random words that reduces duplicates and increases memory use) to fit within main memory and it ran under a minute. This situation plus O(n**2) in your original code will take forever, and is why algorithmic time and space complexity are both important.\nimport operator\nimport random\nimport string\n\ndef slices(seq, length):\n unique = {}\n for start in xrange(len(seq) - length, -1, -1):\n unique[seq[start:start+length]] = start\n return unique\n\ndef sample_with_repeat(population, length, choice=random.choice):\n return \"\".join(choice(population) for _ in xrange(length))\n\nword_length = 5*1000*1000\nwords = [sample_with_repeat(string.lowercase, word_length) for _ in xrange(3)]\nslice_length = 20\nwords_slices_sets = [set(slices(x, slice_length)) for x in words]\nunique_words_slices = [reduce(operator.sub,\n (x for x in words_slices_sets if x is not n),\n n)\n for n in words_slices_sets]\nprint [len(x) for x in unique_words_slices]\n\n",
"You say you have a \"word\" 5 million characters long, but I find it hard to believe this is a word in the usual sense.\nIf you can provide more information about your input data, a specific solution might be available.\nFor example, English text (or any other written language) might be sufficiently repetitive that a trie would be useable. In the worst case however, it would run out of memory constructing all 256^20 keys. Knowing your inputs makes all the difference.\n\nedit\nI took a look at some genome data to see how this idea stacked up, using a hardcoded [acgt]->[0123] mapping and 4 children per trie node.\n\nadenovirus 2: 35,937bp -> 35,899 distinct 20-base sequences using 469,339 trie nodes\nenterobacteria phage lambda: 48,502bp -> 40,921 distinct 20-base sequences using 529,384 trie nodes.\n\nI didn't get any collisions, either within or between the two data sets, although maybe there is more redundancy and/or overlap in your data. You'd have to try it to see.\nIf you do get a useful number of collisions, you could try walking the three inputs together, building a single trie, recording the origin of each leaf and pruning collisions from the trie as you go.\nIf you can't find some way to prune the keys, you could try using a more compact representation. For example you only need 2 bits to store [acgt]/[0123], which might save you space at the cost of slightly more complex code.\nI don't think you can just brute force this though - you need to find some way to reduce the scale of the problem, and that depends on your domain knowledge.\n",
"Let me build off Roger Pate's answer. If memory is an issue, I'd suggest instead of using the strings as the keys to the dictionary, you could use a hashed value of the string. This would save the cost of the storing the extra copy of the strings as the keys (at worst, 20 times the storage of an individual \"word\").\nimport collections\ndef hashed_slices(seq, length, hasher=None):\n unique = collections.defaultdict(list)\n for start in xrange(len(seq) - length + 1):\n unique[hasher(seq[start:start+length])].append(start)\n return unique\n\n(If you really want to get fancy, you can use a rolling hash, though you'll need to change the function.)\nNow, we can combine all the hashes :\nunique = [] # Unique words in first string\n\n# create a dictionary of hash values -> word index -> start position\nhashed_starts = [hashed_slices(word, 20, hashing_fcn) for word in words]\nall_hashed = collections.defaultdict(dict)\nfor i, hashed in enumerate(hashed_starts) :\n for h, starts in hashed.iteritems() :\n # We only care about the first word\n if h in hashed_starts[0] :\n all_hashed[h][i]=starts\n\n# Now check all hashes\nfor starts_by_word in all_hashed.itervalues() :\n if len(starts_by_word) == 1 :\n # if there's only one word for the hash, it's obviously valid\n unique.extend(words[0][i:i+20] for i in starts_by_word.values())\n else :\n # we might have a hash collision\n candidates = {}\n for word_idx, starts in starts_by_word.iteritems() :\n candidates[word_idx] = set(words[word_idx][j:j+20] for j in starts)\n # Now go that we have the candidate slices, find the unique ones\n valid = candidates[0]\n for word_idx, candidate_set in candidates.iteritems() :\n if word_idx != 0 :\n valid -= candidate_set\n unique.extend(valid)\n\n(I tried extending it to do all three. It's possible, but the complications would detract from the algorithm.)\nBe warned, I haven't tested this. Also, there's probably a lot you can do to simplify the code, but the algorithm makes sense. The hard part is choosing the hash. Too many collisions and you'll won't gain anything. Too few and you'll hit the memory problems. If you are dealing with just DNA base codes, you can hash the 20-character string to a 40-bit number, and still have no collisions. So the slices will take up nearly a fourth of the memory. That would save roughly 250 MB of memory in Roger Pate's answer.\nThe code is still O(N^2), but the constant should be much lower.\n",
"Let's attempt to improve on Roger Pate's excellent answer.\nFirstly, let's keep sets instead of dictionaries - they manage uniqueness anyway.\nSecondly, since we are likely to run out of memory faster than we run out of CPU time (and patience), we can sacrifice CPU efficiency for the sake of memory efficiency. So perhaps try only the 20s starting with one particular letter. For DNA, this cuts the requirements down by 75%. \nseqlen = 20\nmaxlength = max([len(word) for word in words])\nfor startletter in letters:\n for letterid in range(maxlength):\n for wordid,word in words:\n if (letterid < len(word)):\n letter = word[letterid]\n if letter is startletter:\n seq = word[letterid:letterid+seqlen]\n if seq in seqtrie and not wordid in seqtrie[seq]:\n seqtrie[seq].append(wordid)\n\nOr, if that's still too much memory, we can go through for each possible starting pair (16 passes instead of 4 for DNA), or every 3 (64 passes) etc.\n"
] |
[
10,
0,
0,
0
] |
[] |
[] |
[
"bioinformatics",
"iteration",
"python"
] |
stackoverflow_0001941712_bioinformatics_iteration_python.txt
|
Q:
In python is there any way I can obtain the arguments passed to a function as object?
I don't want to use *args or **kwargs since I can't change function declaration.
For example:
def foo( a, b, c ) """Lets say values passed to a, b and c are 1,2 and 3 respectively"""
...
...
""" I would like to generate an object preferably a dictionary such as {'a':1, 'b':2, 'c':3} """
...
...
Can anyone suggest a way to do this?
Thanks in advance.
A:
If you can't change the function "declaration" (why not?) but you can change the contents of the function, then just create the dictionary as you want it:
def foo(a, b, c):
mydict = {'a': a, 'b': b, 'c': c}
If that doesn't work, I think you need a better explanation of what you want and what the constraints are in your case.
This is also going to give similar results in the above case (where you don't show any local variables other than the arguments), but be warned that you should not try to modify locals():
def foo(a, b, c):
mydict = locals()
A:
@Rohit, we do not understand what you mean when you say "the function declaration". If you mean you don't want to change the API of the function (the documented way the function is called), perhaps because you have existing code already calling an existing function, then you can still use the **kwargs notation, and the callers will never know:
def foo(a, b, c):
return a + b + c
def foo(**kwargs):
total = 0
for x in ("a", "b", "c"):
assert x in kwargs
total += kwargs[x]
return total
def bar():
foo(3, 5, 7)
bar() cannot tell which version of foo() it is calling, and does not care.
Perhaps you are looking for a "wrapper" you can wrap around existing function objects, without changing the actual source code of the function object?
def make_wrapper(fn, *arg_names):
def wrapped_fn(*args):
mydict = dict(tup for tup in zip(arg_names, args))
print("TEST: mydict: %s" % str(mydict))
return fn(*args)
return wrapped_fn
def foo(a, b, c):
return a + b + c
foo = make_wrapper(foo, "a", "b", "c")
foo(3, 5, 7)
The new wrapped function gathers the arguments into mydict and prints mydict before calling the function.
A:
By diligent searching of StackOverflow, I found out how to do this. You use the inspect module.
import inspect
def make_wrapper(fn):
arg_names = inspect.getargspec(fn)[0]
def wrapped_fn(*args, **kwargs):
# mydict now gets all expected positional arguments:
mydict = dict(tup for tup in zip(arg_names, args))
# special name "__args" gets list of all positional arguments
mydict["__args"] = args
# mydict now updated with all keyword arguments
mydict.update(kwargs)
# mydict now has full information on all arguments of any sort
print("TEST: mydict: %s" % str(mydict))
return fn(*args, **kwargs)
return wrapped_fn
def foo(a, b, c, *args, **kwargs):
# a, b, and c must be set; extra, unexpected args will go in args list
return a + b + c
foo = make_wrapper(foo)
foo(3, 5, 7, 1, 2)
# prints: TEST: mydict: {'a': 3, 'c': 7, 'b': 5, '__args': (3, 5, 7, 1, 2)}
# returns: 15
There you go, a perfect solution to the problem you stated. It is a wrapper, you don't need to pass in the arguments, and it should work for any function. If you need it to work with class objects or something you can read the docs for inspect and see how to do it.
Note, of course order is not preserved in dictionaries, so you may not see the exact order I saw when I tested this. But the same values should be in the dict.
A:
def foo(a, b, c):
args = {"a": a, "b": b, "c": c}
|
In python is there any way I can obtain the arguments passed to a function as object?
|
I don't want to use *args or **kwargs since I can't change function declaration.
For example:
def foo( a, b, c ) """Lets say values passed to a, b and c are 1,2 and 3 respectively"""
...
...
""" I would like to generate an object preferably a dictionary such as {'a':1, 'b':2, 'c':3} """
...
...
Can anyone suggest a way to do this?
Thanks in advance.
|
[
"If you can't change the function \"declaration\" (why not?) but you can change the contents of the function, then just create the dictionary as you want it:\ndef foo(a, b, c):\n mydict = {'a': a, 'b': b, 'c': c}\n\nIf that doesn't work, I think you need a better explanation of what you want and what the constraints are in your case.\nThis is also going to give similar results in the above case (where you don't show any local variables other than the arguments), but be warned that you should not try to modify locals():\ndef foo(a, b, c):\n mydict = locals()\n\n",
"@Rohit, we do not understand what you mean when you say \"the function declaration\". If you mean you don't want to change the API of the function (the documented way the function is called), perhaps because you have existing code already calling an existing function, then you can still use the **kwargs notation, and the callers will never know:\ndef foo(a, b, c):\n return a + b + c\n\ndef foo(**kwargs):\n total = 0\n for x in (\"a\", \"b\", \"c\"):\n assert x in kwargs\n total += kwargs[x]\n return total\n\ndef bar():\n foo(3, 5, 7)\n\nbar() cannot tell which version of foo() it is calling, and does not care.\nPerhaps you are looking for a \"wrapper\" you can wrap around existing function objects, without changing the actual source code of the function object?\ndef make_wrapper(fn, *arg_names):\n def wrapped_fn(*args):\n mydict = dict(tup for tup in zip(arg_names, args))\n print(\"TEST: mydict: %s\" % str(mydict))\n return fn(*args)\n return wrapped_fn\n\n\ndef foo(a, b, c):\n return a + b + c\n\nfoo = make_wrapper(foo, \"a\", \"b\", \"c\")\n\nfoo(3, 5, 7)\n\nThe new wrapped function gathers the arguments into mydict and prints mydict before calling the function.\n",
"By diligent searching of StackOverflow, I found out how to do this. You use the inspect module.\nimport inspect\n\ndef make_wrapper(fn):\n arg_names = inspect.getargspec(fn)[0]\n def wrapped_fn(*args, **kwargs):\n # mydict now gets all expected positional arguments:\n mydict = dict(tup for tup in zip(arg_names, args))\n # special name \"__args\" gets list of all positional arguments\n mydict[\"__args\"] = args\n # mydict now updated with all keyword arguments\n mydict.update(kwargs)\n # mydict now has full information on all arguments of any sort\n print(\"TEST: mydict: %s\" % str(mydict))\n return fn(*args, **kwargs)\n return wrapped_fn\n\ndef foo(a, b, c, *args, **kwargs):\n # a, b, and c must be set; extra, unexpected args will go in args list\n return a + b + c\n\nfoo = make_wrapper(foo)\n\nfoo(3, 5, 7, 1, 2)\n# prints: TEST: mydict: {'a': 3, 'c': 7, 'b': 5, '__args': (3, 5, 7, 1, 2)}\n# returns: 15\n\nThere you go, a perfect solution to the problem you stated. It is a wrapper, you don't need to pass in the arguments, and it should work for any function. If you need it to work with class objects or something you can read the docs for inspect and see how to do it.\nNote, of course order is not preserved in dictionaries, so you may not see the exact order I saw when I tested this. But the same values should be in the dict.\n",
"def foo(a, b, c):\n args = {\"a\": a, \"b\": b, \"c\": c}\n\n"
] |
[
5,
1,
1,
0
] |
[] |
[] |
[
"arguments",
"function",
"object",
"python"
] |
stackoverflow_0001966715_arguments_function_object_python.txt
|
Q:
Start and capture GUI's output from same Python script and transfer variables?
I have to start a GUI from an existing Python application. The GUI is actually separate Python GUI that can run alone. Right now, I am starting the GUI using something like:
res=Popen(['c:\python26\pythonw.exe',
full_filename,
str(RESULTs),
str(context)], stdout=PIPE).communicate()[0]
where full_filename is the full path to the python GUI. As you can see, the problem is that I have to communicate the RESULTS variable to the GUI via the commandline. This works fine until the commandline get too long and I have to pickle the variables to a separate file and then re-load them when the GUI starts. This works but it is slow.
Thus, what I want to do is somehow start the GUI from within my python script, transfer the variables in question to the GUI for it to process, and then capture the GUI's results back in the calling script. As you can see above, this currently happens through the res variable since the GUI can be configured to write its output to the standard output which is captured in this variable.
Any ideas? I'm hoping someone can suggest a more elegant way of doing this. This all happens on a winXP machine.
A:
From the sounds of it, unless Nazarius' excellent suggestion for a first step is infeasible, a program like pyWinAuto would do what you need. We use it to control our own wxPython-based application for use in automated testing, with a Python script controlling the program by entering text into GUI fields, clicking buttons, and so on. The general term for this is "GUI automation" and you can find lots of other information about that by searching. pyWinAuto is only one option available in the Python world for this, but it's a pretty good one.
A:
Is the python application opensource? You can look at how the GUI itself hooks up into the back end, and directly import the relative modules into your application, then call it as the GUI would, bypassing this messy hack.
|
Start and capture GUI's output from same Python script and transfer variables?
|
I have to start a GUI from an existing Python application. The GUI is actually separate Python GUI that can run alone. Right now, I am starting the GUI using something like:
res=Popen(['c:\python26\pythonw.exe',
full_filename,
str(RESULTs),
str(context)], stdout=PIPE).communicate()[0]
where full_filename is the full path to the python GUI. As you can see, the problem is that I have to communicate the RESULTS variable to the GUI via the commandline. This works fine until the commandline get too long and I have to pickle the variables to a separate file and then re-load them when the GUI starts. This works but it is slow.
Thus, what I want to do is somehow start the GUI from within my python script, transfer the variables in question to the GUI for it to process, and then capture the GUI's results back in the calling script. As you can see above, this currently happens through the res variable since the GUI can be configured to write its output to the standard output which is captured in this variable.
Any ideas? I'm hoping someone can suggest a more elegant way of doing this. This all happens on a winXP machine.
|
[
"From the sounds of it, unless Nazarius' excellent suggestion for a first step is infeasible, a program like pyWinAuto would do what you need. We use it to control our own wxPython-based application for use in automated testing, with a Python script controlling the program by entering text into GUI fields, clicking buttons, and so on. The general term for this is \"GUI automation\" and you can find lots of other information about that by searching. pyWinAuto is only one option available in the Python world for this, but it's a pretty good one.\n",
"Is the python application opensource? You can look at how the GUI itself hooks up into the back end, and directly import the relative modules into your application, then call it as the GUI would, bypassing this messy hack.\n"
] |
[
1,
0
] |
[] |
[] |
[
"automation",
"python",
"subprocess",
"user_interface"
] |
stackoverflow_0001972176_automation_python_subprocess_user_interface.txt
|
Q:
MySQLdb connection issue
I am writing a server which provide a service by query MySQL database.
Everything goes fine, except when run one or two days the connection will go away.
The error code is (2600, MySQL has gone away)
I try to wrap the cursor object by:
def cursor(self):
try:
return self.connection.cursor()
except:
self.connection = MySQLdb.connect(**self.kwargs)
return self.connection.cursor()
This seems not work, I still got error while I the cursor from this wrapper class when I call cursor.execute(..).
Any idea that I can keep consistent connection?
A:
@duffymo's idea about not keeping connections open too long is viable, but so is your original idea about catching the exception and retrying (I'm not so sure about which one is better).
Since the exception is raised by cursor.execute, that's where you must catch and remedy it (by renewing the connection and cursor and repeating the attempt to execute). I would do it via a simple class wrapper, holding the connection (and parameters needed to establish or re-establish it) and cursor as members, and exposing methods for executing and fetching.
Note that by encapsulating connection and cursor that way, you could then keep exactly the same interface (with a completely different implementation that gets the connection from a pool and returns it there when done with it) if you do decide to switch to @duffymo's strategy instead (an explicit method "done with fetching from this execute" will help;-).
A:
You would be better served by a connection pool and minimizing the length of time that a connection stays open. It'll be more scalable, and you won't suffer from this issue.
|
MySQLdb connection issue
|
I am writing a server which provide a service by query MySQL database.
Everything goes fine, except when run one or two days the connection will go away.
The error code is (2600, MySQL has gone away)
I try to wrap the cursor object by:
def cursor(self):
try:
return self.connection.cursor()
except:
self.connection = MySQLdb.connect(**self.kwargs)
return self.connection.cursor()
This seems not work, I still got error while I the cursor from this wrapper class when I call cursor.execute(..).
Any idea that I can keep consistent connection?
|
[
"@duffymo's idea about not keeping connections open too long is viable, but so is your original idea about catching the exception and retrying (I'm not so sure about which one is better).\nSince the exception is raised by cursor.execute, that's where you must catch and remedy it (by renewing the connection and cursor and repeating the attempt to execute). I would do it via a simple class wrapper, holding the connection (and parameters needed to establish or re-establish it) and cursor as members, and exposing methods for executing and fetching.\nNote that by encapsulating connection and cursor that way, you could then keep exactly the same interface (with a completely different implementation that gets the connection from a pool and returns it there when done with it) if you do decide to switch to @duffymo's strategy instead (an explicit method \"done with fetching from this execute\" will help;-).\n",
"You would be better served by a connection pool and minimizing the length of time that a connection stays open. It'll be more scalable, and you won't suffer from this issue.\n"
] |
[
2,
1
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0001972562_mysql_python.txt
|
Q:
Python-Challenge Level 3
The questions is: One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
I wrote this code and get an answer. I thougt it would be correct, but it doesn't work. Can anybody help me? My answer: KWGtIDC
import urllib, sys, string
from string import maketrans
bbb = 0
f = urllib.urlopen("http://www.pythonchallenge.com/pc/def/equality.html")
while 1:
buf = f.read(200000)
if not len(buf):
break
for x in range(len(buf)):
if buf[x] in string.ascii_lowercase:
if buf[x+1] in string.ascii_uppercase:
if buf[x-1] in string.ascii_uppercase:
if buf[x+2] in string.ascii_uppercase:
if buf[x-2] in string.ascii_uppercase:
if buf[x+3] in string.ascii_uppercase:
if buf[x-3] in string.ascii_uppercase:
if buf[x+4] in string.ascii_lowercase:
if buf[x-4] in string.ascii_lowercase:
bbb = x
sys.stdout.write(buf)
print(buf[bbb-3:bbb+4])
A:
A couple of points:
You need to operate on the comment block in the source of the html page, not the entire page itself. I'm not sure if the rest of the page makes a difference, but still. I'd copy the comment block to another file locally, and go from there.
The title of the page is "re". Does that ring any bells?
There may be more than one occurrence of the pattern that fits your requirement, and your program overwrites it each time bbb = x. You need all of them, IIRC.
A:
In your code
if buf[x+4] in string.ascii_lowercase:
will only work if there is a fouth (lowercase) character, but did you consider the case that there is no fourth character, such as the end of sring (for instanceL: "ABCdEFG")?
Without ruining the puzzle, have you try creating a regular expression? A regex avoids the nested loops and requires a lot less lines.
|
Python-Challenge Level 3
|
The questions is: One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
I wrote this code and get an answer. I thougt it would be correct, but it doesn't work. Can anybody help me? My answer: KWGtIDC
import urllib, sys, string
from string import maketrans
bbb = 0
f = urllib.urlopen("http://www.pythonchallenge.com/pc/def/equality.html")
while 1:
buf = f.read(200000)
if not len(buf):
break
for x in range(len(buf)):
if buf[x] in string.ascii_lowercase:
if buf[x+1] in string.ascii_uppercase:
if buf[x-1] in string.ascii_uppercase:
if buf[x+2] in string.ascii_uppercase:
if buf[x-2] in string.ascii_uppercase:
if buf[x+3] in string.ascii_uppercase:
if buf[x-3] in string.ascii_uppercase:
if buf[x+4] in string.ascii_lowercase:
if buf[x-4] in string.ascii_lowercase:
bbb = x
sys.stdout.write(buf)
print(buf[bbb-3:bbb+4])
|
[
"A couple of points:\n\nYou need to operate on the comment block in the source of the html page, not the entire page itself. I'm not sure if the rest of the page makes a difference, but still. I'd copy the comment block to another file locally, and go from there.\nThe title of the page is \"re\". Does that ring any bells?\nThere may be more than one occurrence of the pattern that fits your requirement, and your program overwrites it each time bbb = x. You need all of them, IIRC.\n\n",
"In your code\nif buf[x+4] in string.ascii_lowercase:\n\nwill only work if there is a fouth (lowercase) character, but did you consider the case that there is no fourth character, such as the end of sring (for instanceL: \"ABCdEFG\")?\nWithout ruining the puzzle, have you try creating a regular expression? A regex avoids the nested loops and requires a lot less lines.\n"
] |
[
8,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001972693_python.txt
|
Q:
python permission error
I have a file a.txt in Mac OS, which has write perms to everybody:
sh-3.2# ls -hal a.txt
-rw-rw-rw- 1 root wheel 0B Dec 8 11:34 a.txt
sh-3.2# pwd
/var/root
however in python it gives me an error:
>>> fob=open("/var/root/a.txt","w")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
fob=open("/var/root/a.txt","w")
IOError: [Errno 13] Permission denied: '/var/root/a.txt'
question: why?
A:
I'm going to guess that the permissions on the /var/root directory are too strict for the user you are running as.
A:
It's likely that you don't have write permission on the directory that the file is in.
A:
Just a wild guess: since the file already exists there, is it possible that opening with mode "w+" or "r+" instead of "w" allows you to write to the file?
I don't have an OS X computer available, and it's most probable that it's an issue of the directory permissions, however I'd try the mode change, just in case.
|
python permission error
|
I have a file a.txt in Mac OS, which has write perms to everybody:
sh-3.2# ls -hal a.txt
-rw-rw-rw- 1 root wheel 0B Dec 8 11:34 a.txt
sh-3.2# pwd
/var/root
however in python it gives me an error:
>>> fob=open("/var/root/a.txt","w")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
fob=open("/var/root/a.txt","w")
IOError: [Errno 13] Permission denied: '/var/root/a.txt'
question: why?
|
[
"I'm going to guess that the permissions on the /var/root directory are too strict for the user you are running as.\n",
"It's likely that you don't have write permission on the directory that the file is in.\n",
"Just a wild guess: since the file already exists there, is it possible that opening with mode \"w+\" or \"r+\" instead of \"w\" allows you to write to the file?\nI don't have an OS X computer available, and it's most probable that it's an issue of the directory permissions, however I'd try the mode change, just in case.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"permissions",
"python"
] |
stackoverflow_0001868213_permissions_python.txt
|
Q:
Get the position of the windows start menu
I'm writing an app in Python that automatically moves stuff around. How do I get the position of the windows start menu bar, so I can account for it in my calculations?
A:
When you ask for the work area, the taskbar area is automatically excluded.
System.Parameters.WorkArea
or Use interop to
SystemParametersInfo(SPI_GETWORKAREA, ...)`
and you are done.
A:
Ah, found it. GetMonitorInfo: http://msdn.microsoft.com/en-us/library/dd144901(VS.85).aspx . Here is an example: http://msdn.microsoft.com/en-us/library/dd162826(VS.85).aspx .
A:
To get the rectangle use SHAppBarMessage(). You would do the following in C++:
APPBARDATA abd = {0};
SHAppBarMessage(ABM_GETTASKBARPOS, &abd);
And then abd.rc would contain the rectangle. You just have to do the pywin32 equivilent.
Please note that GetMonitorInfo() will give you the working area, which is desktop - appbars, but the Task Bar is not the only appbar that might exist.
|
Get the position of the windows start menu
|
I'm writing an app in Python that automatically moves stuff around. How do I get the position of the windows start menu bar, so I can account for it in my calculations?
|
[
"When you ask for the work area, the taskbar area is automatically excluded. \nSystem.Parameters.WorkArea\n\nor Use interop to \nSystemParametersInfo(SPI_GETWORKAREA, ...)` \n\nand you are done.\n",
"Ah, found it. GetMonitorInfo: http://msdn.microsoft.com/en-us/library/dd144901(VS.85).aspx . Here is an example: http://msdn.microsoft.com/en-us/library/dd162826(VS.85).aspx .\n",
"To get the rectangle use SHAppBarMessage(). You would do the following in C++:\nAPPBARDATA abd = {0};\nSHAppBarMessage(ABM_GETTASKBARPOS, &abd);\n\nAnd then abd.rc would contain the rectangle. You just have to do the pywin32 equivilent.\nPlease note that GetMonitorInfo() will give you the working area, which is desktop - appbars, but the Task Bar is not the only appbar that might exist.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"python",
"pywin32",
"winapi"
] |
stackoverflow_0001972709_python_pywin32_winapi.txt
|
Q:
delete a line based on logic
I have a file where i have multiple records with such data
F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89
now i want to search for the line where if i find length<=50 then delete this line and the next line in the file and write to another file.
Thanks everyone
A:
From the top of my head:
for every line in file
split by spaces
get last token
split by equal
verify length
write line to another file
delete line and the next
Hope this is what you need to start working.
A:
Assuming Python 2.6 (let us know if it's another version you need!), and that you want to skip every line with length <= 50 (and ignore the next line in each case), if any:
import re
def weirdtask(infname, oufname):
inf = open(infname, 'r')
ouf = open(oufname, 'w')
rle = re.compile(r'length=\s*(\d+)')
for line in inf:
mo = re.search(line)
if mo:
thelen = int(mo.group(1))
if thelen <= 50:
next(inf)
continue
ouf.write(line)
ouf.close()
If that's not exactly your specs, please clarify.
inf.close()
A:
If the columns are always in the same order and there are always the same number, you can just use the .split() method on the string, and find the one you want with an index:
words = line.split()
l = words[4]
temp = l.split("=")[2]
if int(temp) <= 50:
# found the line, handle it
do_something_here()
If the columns might be in any order, you could use regular expressions.
s_pat = "length\s*=\s*(\d+)"
pat = re.compile(s_pat)
m = pat.search(line)
if m:
temp = m.group(1)
if int(temp) <= 50:
# found the line, handle it
do_something_here()
This uses the "match group" from the regular expression to grab the number.
P.S. Two answers appeared while I was writing this. I am not the fastest gun in the west.
|
delete a line based on logic
|
I have a file where i have multiple records with such data
F00DY4302B8JRQ rank=0000030 x=800.0 y=1412.0 length=89
now i want to search for the line where if i find length<=50 then delete this line and the next line in the file and write to another file.
Thanks everyone
|
[
"From the top of my head:\nfor every line in file\nsplit by spaces\nget last token\nsplit by equal\nverify length\nwrite line to another file\ndelete line and the next\n\nHope this is what you need to start working.\n",
"Assuming Python 2.6 (let us know if it's another version you need!), and that you want to skip every line with length <= 50 (and ignore the next line in each case), if any:\nimport re\n\ndef weirdtask(infname, oufname):\n inf = open(infname, 'r')\n ouf = open(oufname, 'w')\n rle = re.compile(r'length=\\s*(\\d+)')\n for line in inf:\n mo = re.search(line)\n if mo:\n thelen = int(mo.group(1))\n if thelen <= 50:\n next(inf)\n continue\n ouf.write(line)\n ouf.close()\n\nIf that's not exactly your specs, please clarify.\n inf.close()\n\n",
"If the columns are always in the same order and there are always the same number, you can just use the .split() method on the string, and find the one you want with an index:\nwords = line.split()\nl = words[4]\ntemp = l.split(\"=\")[2]\nif int(temp) <= 50:\n # found the line, handle it\n do_something_here()\n\nIf the columns might be in any order, you could use regular expressions.\ns_pat = \"length\\s*=\\s*(\\d+)\"\npat = re.compile(s_pat)\n\nm = pat.search(line)\nif m:\n temp = m.group(1)\n if int(temp) <= 50:\n # found the line, handle it\n do_something_here()\n\nThis uses the \"match group\" from the regular expression to grab the number.\nP.S. Two answers appeared while I was writing this. I am not the fastest gun in the west.\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python",
"text_processing"
] |
stackoverflow_0001972817_python_text_processing.txt
|
Q:
Apache: Download files getting a CR inserted before every LF (even spreadsheets)
I am using Apache 2.2.14 and Python 2.6 for CGI on Windows XP. Files sent through CGI get corrupted. A CR gets inserted before every LF. Firefox, IE, and Curl clients give the same result. The file is the correct size, but CR's are inserted throughout, and the data is shifted down and truncated. I can look at the file on the server, and it's fine.
Is there some switch in Apache I am missing?
Here is the python code to write the HTTP header and send the file:
outsize = os.path.getsize(outfile)
mheader = "Content-type: application/octet-stream\n"
mheader = mheader + "Content-Length: "+str(outsize) + "\n"
mheader = mheader + "Content-Disposition: attachment; filename=\"product.xls\"\n\n"
sys.stdout.write(mheader)
sys.stdout.write(file(outfile, "rb").read())
The header looks like this:
Content-type: application/octet-stream
Content-Length: 84210
Content-Disposition: attachment; filename="product.xls"
A:
Use msvcrt.setmode(1, os.O_BINARY) (after you write the headers and sys.stdout.flush them) to set standard output to binary mode -- poor Apache is innocent, it's a Windows thing;-).
|
Apache: Download files getting a CR inserted before every LF (even spreadsheets)
|
I am using Apache 2.2.14 and Python 2.6 for CGI on Windows XP. Files sent through CGI get corrupted. A CR gets inserted before every LF. Firefox, IE, and Curl clients give the same result. The file is the correct size, but CR's are inserted throughout, and the data is shifted down and truncated. I can look at the file on the server, and it's fine.
Is there some switch in Apache I am missing?
Here is the python code to write the HTTP header and send the file:
outsize = os.path.getsize(outfile)
mheader = "Content-type: application/octet-stream\n"
mheader = mheader + "Content-Length: "+str(outsize) + "\n"
mheader = mheader + "Content-Disposition: attachment; filename=\"product.xls\"\n\n"
sys.stdout.write(mheader)
sys.stdout.write(file(outfile, "rb").read())
The header looks like this:
Content-type: application/octet-stream
Content-Length: 84210
Content-Disposition: attachment; filename="product.xls"
|
[
"Use msvcrt.setmode(1, os.O_BINARY) (after you write the headers and sys.stdout.flush them) to set standard output to binary mode -- poor Apache is innocent, it's a Windows thing;-).\n"
] |
[
4
] |
[] |
[] |
[
"apache",
"cgi",
"python"
] |
stackoverflow_0001972849_apache_cgi_python.txt
|
Q:
How to use pyparsing to parse and hash strings enclosed by special characters?
The majority of pyparsing examples that I have seen have dealt with linear expressions.
a = 1 + 2
I'd like to parse mediawiki headlines, and hash them to their sections.
e.g.
Introduction goes here
==Hello==
foo
foo
===World===
bar
bar
Dict would look like:
{'Introduction':'Whoot introduction goes here', 'Hello':"foo\nfoo", 'World':"bar\nbar"}
If I could just see one example of this "enclosed" (==HEADLINE==) parsing, I'd be able to move on to links/images/files etc.
A:
Did you miss this wiki-like language parser in the pyParsing web site examples?
h2 = QuotedString("==")
A:
Also, this format is not unlike a .INI file:
[section1]
a = 1
b = 3
[section2]
blah=a
Which can be parsed into a nested dictionary using this example code.
|
How to use pyparsing to parse and hash strings enclosed by special characters?
|
The majority of pyparsing examples that I have seen have dealt with linear expressions.
a = 1 + 2
I'd like to parse mediawiki headlines, and hash them to their sections.
e.g.
Introduction goes here
==Hello==
foo
foo
===World===
bar
bar
Dict would look like:
{'Introduction':'Whoot introduction goes here', 'Hello':"foo\nfoo", 'World':"bar\nbar"}
If I could just see one example of this "enclosed" (==HEADLINE==) parsing, I'd be able to move on to links/images/files etc.
|
[
"Did you miss this wiki-like language parser in the pyParsing web site examples?\nh2 = QuotedString(\"==\")\n\n",
"Also, this format is not unlike a .INI file:\n[section1]\na = 1\nb = 3\n[section2]\nblah=a\n\nWhich can be parsed into a nested dictionary using this example code.\n"
] |
[
3,
1
] |
[] |
[] |
[
"dictionary",
"mediawiki",
"parsing",
"pyparsing",
"python"
] |
stackoverflow_0001972781_dictionary_mediawiki_parsing_pyparsing_python.txt
|
Q:
Python code optimization
I'm building a online font previewer, with following architecture. I wrapped preview creation function in a standalone .py file and making system calls to it in a Django view in order to run them in parallel and maximum performance on multi-core CPU system.
preview.py
....
def make_preview(text, fontfile, imagefile, fontsize=30):
try:
font = ImageFont.truetype(fontfile, fontsize)
text_width, text_height = font.getsize(text)
img = Image.new('RGBA', (text_width, text_height))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, font=font, fill=(0, 0, 0))
return True
except:
return False
if __name__=='__main__':
make_preview(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
views.py
...
def ajax_preview(resquest):
ttf_file_list = [construct a list of .ttf files]
image_list = []
for ttf_file in ttf_file_list:
image_file = ttf_file.replace('.ttf', '.png')
image_list.append(image_file)
subprocess.Popen(['python', 'preview.py', text, ttf_file, image_file, 30)
return HttpResponse(image_list)
Is it possible to make above code even faster? Maybe there is a better architecture to do this job or any optimization I can do for the code?
A:
You should look into the multiprocessing module. You could create a pool of workers equal to your number of CPU cores and then send jobs to your make_preview function.
A:
If this is a font chooser, where you can reasonably display the same text every time you show it, you can pre-render the font samples and save the results as .PNG or .GIF files. (You don't want to use JPEG images because they will make your fonts blurry; JPEGs use lossy compression.)
Then you can make your font chooser a block of pre-rendered HTML that refers to the pre-rendered preview images.
You would only need to re-generate your previews when you install or remove fonts from your system.
|
Python code optimization
|
I'm building a online font previewer, with following architecture. I wrapped preview creation function in a standalone .py file and making system calls to it in a Django view in order to run them in parallel and maximum performance on multi-core CPU system.
preview.py
....
def make_preview(text, fontfile, imagefile, fontsize=30):
try:
font = ImageFont.truetype(fontfile, fontsize)
text_width, text_height = font.getsize(text)
img = Image.new('RGBA', (text_width, text_height))
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, font=font, fill=(0, 0, 0))
return True
except:
return False
if __name__=='__main__':
make_preview(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])
views.py
...
def ajax_preview(resquest):
ttf_file_list = [construct a list of .ttf files]
image_list = []
for ttf_file in ttf_file_list:
image_file = ttf_file.replace('.ttf', '.png')
image_list.append(image_file)
subprocess.Popen(['python', 'preview.py', text, ttf_file, image_file, 30)
return HttpResponse(image_list)
Is it possible to make above code even faster? Maybe there is a better architecture to do this job or any optimization I can do for the code?
|
[
"You should look into the multiprocessing module. You could create a pool of workers equal to your number of CPU cores and then send jobs to your make_preview function.\n",
"If this is a font chooser, where you can reasonably display the same text every time you show it, you can pre-render the font samples and save the results as .PNG or .GIF files. (You don't want to use JPEG images because they will make your fonts blurry; JPEGs use lossy compression.)\nThen you can make your font chooser a block of pre-rendered HTML that refers to the pre-rendered preview images.\nYou would only need to re-generate your previews when you install or remove fonts from your system.\n"
] |
[
2,
0
] |
[] |
[] |
[
"optimization",
"python"
] |
stackoverflow_0001972699_optimization_python.txt
|
Q:
Interpolating a scalar field in a 3D space
I have a 3D space (x, y, z) with an additional parameter at each point (energy), giving 4 dimensions of data in total.
I would like to find a set of x, y, z points which correspond to an iso-energy surface found by interpolating between the known points.
The spacial mesh has constant spacing and surrounds the iso-energy surface entirely, however, it does not occupy a cubic space (the mesh occupies a roughly cylindrical space)
Speed is not crucial, I can leave this number crunching for a while. Although I'm coding in Python and NumPy, I can write portions of the code in FORTRAN. I can also wrap existing C/C++/FORTRAN libraries for use in the scripts, if such libraries exist.
All examples and algorithms that I have so far found online (and in Numerical Recipes) stop short of 4D data.
A:
There are quite a few options here...
In order to get your energy into your mesh, you'll need to use some form of interpolation. Shepard's method is a common, and reasonably simple, method to implement, and tends to work well if your data distribution is reasonable.
Once you have that done, you'll need to do some form of isosurface generation.
There are some libraries out there to make this easy. Most notably, VTK includes python wrappers and has all of the tools required to do both of these steps.
For details on how this could be done in VTK, you can check vtkShepardMethod and vtkContourFilter.
A:
Since you have a spatial mesh with constant spacing, you can identify all neighbors on opposite sides of the isosurface. Choose some form of interpolation (q.v. Reed Copsey's answer) and do root-finding along the line between each such neighbor.
A:
Why not try quadlinear interpolation?
extend Trilinear interpolation by another dimension. As long as a linear interpolation model fits your data, it should work.
|
Interpolating a scalar field in a 3D space
|
I have a 3D space (x, y, z) with an additional parameter at each point (energy), giving 4 dimensions of data in total.
I would like to find a set of x, y, z points which correspond to an iso-energy surface found by interpolating between the known points.
The spacial mesh has constant spacing and surrounds the iso-energy surface entirely, however, it does not occupy a cubic space (the mesh occupies a roughly cylindrical space)
Speed is not crucial, I can leave this number crunching for a while. Although I'm coding in Python and NumPy, I can write portions of the code in FORTRAN. I can also wrap existing C/C++/FORTRAN libraries for use in the scripts, if such libraries exist.
All examples and algorithms that I have so far found online (and in Numerical Recipes) stop short of 4D data.
|
[
"There are quite a few options here...\nIn order to get your energy into your mesh, you'll need to use some form of interpolation. Shepard's method is a common, and reasonably simple, method to implement, and tends to work well if your data distribution is reasonable.\nOnce you have that done, you'll need to do some form of isosurface generation.\nThere are some libraries out there to make this easy. Most notably, VTK includes python wrappers and has all of the tools required to do both of these steps.\nFor details on how this could be done in VTK, you can check vtkShepardMethod and vtkContourFilter.\n",
"Since you have a spatial mesh with constant spacing, you can identify all neighbors on opposite sides of the isosurface. Choose some form of interpolation (q.v. Reed Copsey's answer) and do root-finding along the line between each such neighbor.\n",
"Why not try quadlinear interpolation?\nextend Trilinear interpolation by another dimension. As long as a linear interpolation model fits your data, it should work.\n"
] |
[
8,
2,
1
] |
[] |
[] |
[
"algorithm",
"interpolation",
"python"
] |
stackoverflow_0001972172_algorithm_interpolation_python.txt
|
Q:
Why does this happen with Python's list.sort?
Given the code:
a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c
It prints:
['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]
Why does [('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')] change to [('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]?
Similarly, given:
c.sort(key=lambda x:3)#
print c
It prints:
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
Nothing changes - why?
A:
because x[1] means second
use
c.sort(key=lambda x:x[0])
A:
You've sorted c using the second item as the key, and the second item does indeed go up, just as you asked for it to go up. What's so surprising?!
A:
from operator import itemgetter
c.sort(key=itemgetter(0))
A:
As the others have said, [1] refers to the second element, so the elements in the first part are sorted that way.
As for the second part, list.sort() is stable, so elements that evaluate to the same key will maintain their relative position in the sequence. This is why using .sort(reverse=True) can give different results from .sort() followed by .reverse().
A:
You've sorted the list using the second element of each tuple as a key so you get the tuples ordered by their second element (Notice the 'a', 'b', 'c', 'd' in increasing order). What's the problem?
|
Why does this happen with Python's list.sort?
|
Given the code:
a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c
It prints:
['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]
Why does [('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')] change to [('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]?
Similarly, given:
c.sort(key=lambda x:3)#
print c
It prints:
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
Nothing changes - why?
|
[
"because x[1] means second\nuse\nc.sort(key=lambda x:x[0])\n\n",
"You've sorted c using the second item as the key, and the second item does indeed go up, just as you asked for it to go up. What's so surprising?!\n",
"from operator import itemgetter \nc.sort(key=itemgetter(0))\n\n",
"As the others have said, [1] refers to the second element, so the elements in the first part are sorted that way.\nAs for the second part, list.sort() is stable, so elements that evaluate to the same key will maintain their relative position in the sequence. This is why using .sort(reverse=True) can give different results from .sort() followed by .reverse().\n",
"You've sorted the list using the second element of each tuple as a key so you get the tuples ordered by their second element (Notice the 'a', 'b', 'c', 'd' in increasing order). What's the problem?\n"
] |
[
7,
3,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001973164_python.txt
|
Q:
Why does it do this ? if - __name__ == '__main__'
Duplicate of:
What does if __name__== "__main__" do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()\n")
What does the following line mean?
if(__name__=='__main__')
I fainted.
A:
__name__ is a variable automatically set in an executing python program. If you import your module from another program, __name__ will be set to the name of the module. If you run your program directly, __name__ will be set to __main__.
Therefore, if you want some things to happen only if you're running your program from the command line and not when imported (eg. unit tests for a library), you can use the
if __name__ == "__main__":
# will run only if module directly run
print "I am being run directly"
else:
# will run only if module imported
print "I am being imported"
trick. It's a common Python idiom.
A:
This will be true if this module is being run as a standalone program. That way, something can act either as a module imported by another program, or a standalone program, but only execute the code in the if statement if executed as a program.
A:
That is a check to see if you are directly running the script or if it is included in a library.
When you run a python script like this:
python myScript.py
It sends a parameter, telling you to run the programs first method, which is widely called "main", so when __name__ is __main__ you know that the program was executed from a command line or double clicked.
A:
He has written a python module, intended to be used via import.
If the module is passed to the interpreter as the main python script, the code you quote will run. This will invoke the interact() method under the python debugger.
|
Why does it do this ? if - __name__ == '__main__'
|
Duplicate of:
What does if __name__== "__main__" do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()\n")
What does the following line mean?
if(__name__=='__main__')
I fainted.
|
[
"__name__ is a variable automatically set in an executing python program. If you import your module from another program, __name__ will be set to the name of the module. If you run your program directly, __name__ will be set to __main__. \nTherefore, if you want some things to happen only if you're running your program from the command line and not when imported (eg. unit tests for a library), you can use the \nif __name__ == \"__main__\":\n # will run only if module directly run\n print \"I am being run directly\"\nelse:\n # will run only if module imported\n print \"I am being imported\"\n\ntrick. It's a common Python idiom.\n",
"This will be true if this module is being run as a standalone program. That way, something can act either as a module imported by another program, or a standalone program, but only execute the code in the if statement if executed as a program.\n",
"That is a check to see if you are directly running the script or if it is included in a library.\nWhen you run a python script like this:\npython myScript.py\n\nIt sends a parameter, telling you to run the programs first method, which is widely called \"main\", so when __name__ is __main__ you know that the program was executed from a command line or double clicked.\n",
"He has written a python module, intended to be used via import.\nIf the module is passed to the interpreter as the main python script, the code you quote will run. This will invoke the interact() method under the python debugger.\n"
] |
[
14,
10,
4,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001973373_python.txt
|
Q:
How can I insert a new Event for non primary Calendar? Using python gdata
def addEvent(calendar_service):
event = gdata.calendar.CalendarEventEntry()
event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')
event.quick_add = gdata.calendar.QuickAdd(value='true')
new_event = calendar_service.InsertEvent(event, '/calendar/feeds/default/private/full')
This write to primary Calendar. How can i write/InsertEvent to my "foo" calendar?
Thanks!
A:
Ok, i found the url in a_calendar.content.src it show like "http://www.google.com/calendar/feeds/"+id+"/private/full"
def addEvent(calendar_service):
event = gdata.calendar.CalendarEventEntry()
event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')
event.quick_add = gdata.calendar.QuickAdd(value='true')
feed = calendar_service.GetOwnCalendarsFeed()
calurl=[a_calendar.content.src for i, a_calendar in enumerate(feed.entry)]
new_event = calendar_service.InsertEvent(event, calurl[1]) #calurl[1] select the 2. cal of own's cals
A:
Try specifying a different URL for InsertEvent. See the docs on retrieving calendars or just try hitting the listed URL with a GET. Use a retrieved calendar's URL instead of '/calendar/feeds/default/private/full' in the InsertEvent call.
|
How can I insert a new Event for non primary Calendar? Using python gdata
|
def addEvent(calendar_service):
event = gdata.calendar.CalendarEventEntry()
event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')
event.quick_add = gdata.calendar.QuickAdd(value='true')
new_event = calendar_service.InsertEvent(event, '/calendar/feeds/default/private/full')
This write to primary Calendar. How can i write/InsertEvent to my "foo" calendar?
Thanks!
|
[
"Ok, i found the url in a_calendar.content.src it show like \"http://www.google.com/calendar/feeds/\"+id+\"/private/full\"\ndef addEvent(calendar_service):\n event = gdata.calendar.CalendarEventEntry()\n event.content = atom.Content(text='Tennis with John 30.12.2009 15:00-16:00')\n event.quick_add = gdata.calendar.QuickAdd(value='true')\n feed = calendar_service.GetOwnCalendarsFeed()\n calurl=[a_calendar.content.src for i, a_calendar in enumerate(feed.entry)]\n new_event = calendar_service.InsertEvent(event, calurl[1]) #calurl[1] select the 2. cal of own's cals\n\n",
"Try specifying a different URL for InsertEvent. See the docs on retrieving calendars or just try hitting the listed URL with a GET. Use a retrieved calendar's URL instead of '/calendar/feeds/default/private/full' in the InsertEvent call.\n\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"gdata",
"gdata_api",
"python"
] |
stackoverflow_0001972096_django_gdata_gdata_api_python.txt
|
Q:
django:error with the custom inclusiong_tag, error info:Invalid block tag
I'm trying to write a custom inclusion_tag in django.
Following the example on http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I'm just writing
from django import template
from libmas import models
register = template.Library()
@register.inclusion_tag('records.html')
def display_records(book_id):
book = models.book.objects.get(id__exact=book_id)
records = models.objects.filter(books=book)[0:10]
return {'records':records}
But I'm getting a
Invalid block tag: 'libmas_tags'
error in ie .
'records.html' file:
{% for record in records %}
<blockquote>{{record.id}}</blockquote>
{% endfor %}
my other html file is :
{% extends "admin/change_form.html" %}
{% libmas_tags %}
{% block after_field_sets %}
{% if object_id %}
{% display_records object_id %}
{% endif %}
{% endlock %}
A:
The problem lies in your template. Its calling {% libmas_tags %}. Have you created template tags called libmas_tags? If so you might need to change it to
{% load libmas_tags %}
A:
What is libmas_tags? The tag you have defined is called display_records, and that's what you should be calling in your template. If the tags file is called libmas_tags, you'll need to load that first as czarchaic points out.
|
django:error with the custom inclusiong_tag, error info:Invalid block tag
|
I'm trying to write a custom inclusion_tag in django.
Following the example on http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I'm just writing
from django import template
from libmas import models
register = template.Library()
@register.inclusion_tag('records.html')
def display_records(book_id):
book = models.book.objects.get(id__exact=book_id)
records = models.objects.filter(books=book)[0:10]
return {'records':records}
But I'm getting a
Invalid block tag: 'libmas_tags'
error in ie .
'records.html' file:
{% for record in records %}
<blockquote>{{record.id}}</blockquote>
{% endfor %}
my other html file is :
{% extends "admin/change_form.html" %}
{% libmas_tags %}
{% block after_field_sets %}
{% if object_id %}
{% display_records object_id %}
{% endif %}
{% endlock %}
|
[
"The problem lies in your template. Its calling {% libmas_tags %}. Have you created template tags called libmas_tags? If so you might need to change it to \n{% load libmas_tags %}\n\n",
"What is libmas_tags? The tag you have defined is called display_records, and that's what you should be calling in your template. If the tags file is called libmas_tags, you'll need to load that first as czarchaic points out.\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001972844_django_python.txt
|
Q:
What arguments does Python sort() function have?
Is there any other argument than key, for example: value?
A:
Arguments of sort and sorted
Both sort and sorted have three keyword arguments: cmp, key and reverse.
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
Using key and reverse is preferred, because they work much faster than an equivalent cmp.
key should be a function which takes an item and returns a value to compare and sort by. reverse allows to reverse sort order.
Using key argument
You can use operator.itemgetter as a key argument to sort by second, third etc. item in a tuple.
Example
>>> from operator import itemgetter
>>> a = range(5)
>>> b = a[::-1]
>>> c = map(lambda x: chr(((x+3)%5)+97), a)
>>> sequence = zip(a,b,c)
# sort by first item in a tuple
>>> sorted(sequence, key = itemgetter(0))
[(0, 4, 'd'), (1, 3, 'e'), (2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c')]
# sort by second item in a tuple
>>> sorted(sequence, key = itemgetter(1))
[(4, 0, 'c'), (3, 1, 'b'), (2, 2, 'a'), (1, 3, 'e'), (0, 4, 'd')]
# sort by third item in a tuple
>>> sorted(sequence, key = itemgetter(2))
[(2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c'), (0, 4, 'd'), (1, 3, 'e')]
Explanation
Sequences can contain any objects, not even comparable, but if we can define a function which produces something we can compare for each of the items, we can pass this function in key argument to sort or sorted.
itemgetter, in particular, creates such a function that fetches the given item from its operand. An example from its documentation:
After, f=itemgetter(2), the call f(r) returns r[2].
Mini-benchmark, key vs cmp
Just out of curiosity, key and cmp performance compared, smaller is better:
>>> from timeit import Timer
>>> Timer(stmt="sorted(xs,key=itemgetter(1))",setup="from operator import itemgetter;xs=range(100);xs=zip(xs,xs);").timeit(300000)
6.7079150676727295
>>> Timer(stmt="sorted(xs,key=lambda x:x[1])",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)
11.609490871429443
>>> Timer(stmt="sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))",setup="xs=range(100);xs=zip(xs,xs);").timeit(300000)
22.335839986801147
So, sorting with key seems to be at least twice as fast as sorting with cmp. Using itemgetter instead of lambda x: x[1] makes sort even faster.
A:
Besides key=, the sort method of lists in Python 2.x could alternatively take a cmp= argument (not a good idea, it's been removed in Python 3); with either or none of these two, you can always pass reverse=True to have the sort go downwards (instead of upwards as is the default, and which you can also request explicitly with reverse=False if you're really keen to do that for some reason). I have no idea what that value argument you're mentioning is supposed to do.
A:
Yes, it takes other arguments, but no value.
>>> print list.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
What would a value argument even mean?
|
What arguments does Python sort() function have?
|
Is there any other argument than key, for example: value?
|
[
"Arguments of sort and sorted\nBoth sort and sorted have three keyword arguments: cmp, key and reverse.\nL.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1\n\nsorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list\n\nUsing key and reverse is preferred, because they work much faster than an equivalent cmp.\nkey should be a function which takes an item and returns a value to compare and sort by. reverse allows to reverse sort order.\nUsing key argument\nYou can use operator.itemgetter as a key argument to sort by second, third etc. item in a tuple.\nExample\n>>> from operator import itemgetter\n\n>>> a = range(5)\n>>> b = a[::-1]\n>>> c = map(lambda x: chr(((x+3)%5)+97), a)\n>>> sequence = zip(a,b,c)\n\n# sort by first item in a tuple\n>>> sorted(sequence, key = itemgetter(0))\n[(0, 4, 'd'), (1, 3, 'e'), (2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c')]\n\n# sort by second item in a tuple\n>>> sorted(sequence, key = itemgetter(1))\n[(4, 0, 'c'), (3, 1, 'b'), (2, 2, 'a'), (1, 3, 'e'), (0, 4, 'd')]\n\n# sort by third item in a tuple\n>>> sorted(sequence, key = itemgetter(2))\n[(2, 2, 'a'), (3, 1, 'b'), (4, 0, 'c'), (0, 4, 'd'), (1, 3, 'e')]\n\nExplanation\nSequences can contain any objects, not even comparable, but if we can define a function which produces something we can compare for each of the items, we can pass this function in key argument to sort or sorted.\nitemgetter, in particular, creates such a function that fetches the given item from its operand. An example from its documentation:\n\nAfter, f=itemgetter(2), the call f(r) returns r[2].\n\nMini-benchmark, key vs cmp\nJust out of curiosity, key and cmp performance compared, smaller is better:\n>>> from timeit import Timer\n>>> Timer(stmt=\"sorted(xs,key=itemgetter(1))\",setup=\"from operator import itemgetter;xs=range(100);xs=zip(xs,xs);\").timeit(300000)\n6.7079150676727295\n>>> Timer(stmt=\"sorted(xs,key=lambda x:x[1])\",setup=\"xs=range(100);xs=zip(xs,xs);\").timeit(300000)\n11.609490871429443\n>>> Timer(stmt=\"sorted(xs,cmp=lambda a,b: cmp(a[1],b[1]))\",setup=\"xs=range(100);xs=zip(xs,xs);\").timeit(300000)\n22.335839986801147\n\nSo, sorting with key seems to be at least twice as fast as sorting with cmp. Using itemgetter instead of lambda x: x[1] makes sort even faster.\n",
"Besides key=, the sort method of lists in Python 2.x could alternatively take a cmp= argument (not a good idea, it's been removed in Python 3); with either or none of these two, you can always pass reverse=True to have the sort go downwards (instead of upwards as is the default, and which you can also request explicitly with reverse=False if you're really keen to do that for some reason). I have no idea what that value argument you're mentioning is supposed to do.\n",
"Yes, it takes other arguments, but no value.\n>>> print list.sort.__doc__\nL.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;\ncmp(x, y) -> -1, 0, 1\n\nWhat would a value argument even mean?\n"
] |
[
41,
3,
1
] |
[] |
[] |
[
"key",
"python",
"python_2.x",
"python_3.x",
"sorting"
] |
stackoverflow_0001972672_key_python_python_2.x_python_3.x_sorting.txt
|
Q:
Infinite loop error in python code
I am learning how to code through this book called "Headfirst Programming", which I am really enjoying so far.
One of the projects in the book uses the following code:
def save_transaction(price, credit_card, description):
file = open("transactions.txt", "a")
file.write("%s%07d%s\n" % (credit_card, price * 100, description))
file.close()
items = ['Donut','Latte','Filter','Muffin']
prices = [1.50,2.0,1.80,1.20]`
running = true
while running:
option = 1
for choice in items:
print(str(option) + ". " + choice)
option = option + 1
print(str(option) + ". Quit"))
choice = int(input("choose an option: "))
if choice == option:
running = false
else:
credit_card = input("Credit card number: ")
save_transaction(prices[choice - 1], credit_card, items[choice - 1])
I can see the logic behind using the "if choice == option then running = false" code (it lets the user add an arbitrary number of items), but this code, as is, runs an infinite loop in the shell. This is strange because I copied it directly from the book and the author is using python 3.0, as am I.
Does anyone have a guess as to why this code runs an infinite loop and how to solve this problem, while keeping the code's core functionality intact?
Thanks
A:
As you've probably read, Python uses indentation to identify blocks of code.
So...
while running:
option = 1
for choice in items:
print(str(option) + ". " + choice)
option = option + 1
will run forever, and
print(str(option) + ". Quit"))
choice = int(input("choose an option: "))
if choice == option:
running = false
else:
credit_card = input("Credit card number: ")
save_transaction(prices[choice - 1], credit_card, items[choice - 1])
is never reached. Simply fix the indentation and you should be right.
A:
It's pretty clear that the indentation here is wrong -- since the whole body of the function should be indented relative to the def save_transaction(price, credit_card, description): line.
Hence, I suspect that there's also a problem with the indentation below the while running line, and that the lines which change the value of running should be inside the loop.
A:
You need to indent forward all the lines starting from print(str(option) + ". Quit")). Align them at the same level as for choice in items:.
|
Infinite loop error in python code
|
I am learning how to code through this book called "Headfirst Programming", which I am really enjoying so far.
One of the projects in the book uses the following code:
def save_transaction(price, credit_card, description):
file = open("transactions.txt", "a")
file.write("%s%07d%s\n" % (credit_card, price * 100, description))
file.close()
items = ['Donut','Latte','Filter','Muffin']
prices = [1.50,2.0,1.80,1.20]`
running = true
while running:
option = 1
for choice in items:
print(str(option) + ". " + choice)
option = option + 1
print(str(option) + ". Quit"))
choice = int(input("choose an option: "))
if choice == option:
running = false
else:
credit_card = input("Credit card number: ")
save_transaction(prices[choice - 1], credit_card, items[choice - 1])
I can see the logic behind using the "if choice == option then running = false" code (it lets the user add an arbitrary number of items), but this code, as is, runs an infinite loop in the shell. This is strange because I copied it directly from the book and the author is using python 3.0, as am I.
Does anyone have a guess as to why this code runs an infinite loop and how to solve this problem, while keeping the code's core functionality intact?
Thanks
|
[
"As you've probably read, Python uses indentation to identify blocks of code.\nSo...\nwhile running:\n option = 1\n for choice in items:\n print(str(option) + \". \" + choice)\n option = option + 1\n\nwill run forever, and\nprint(str(option) + \". Quit\"))\nchoice = int(input(\"choose an option: \"))\nif choice == option:\n running = false\nelse: \n credit_card = input(\"Credit card number: \")\n save_transaction(prices[choice - 1], credit_card, items[choice - 1])\n\nis never reached. Simply fix the indentation and you should be right.\n",
"It's pretty clear that the indentation here is wrong -- since the whole body of the function should be indented relative to the def save_transaction(price, credit_card, description): line.\nHence, I suspect that there's also a problem with the indentation below the while running line, and that the lines which change the value of running should be inside the loop.\n",
"You need to indent forward all the lines starting from print(str(option) + \". Quit\")). Align them at the same level as for choice in items:.\n"
] |
[
8,
0,
0
] |
[] |
[] |
[
"loops",
"python"
] |
stackoverflow_0001973822_loops_python.txt
|
Q:
Image library with advanced text effects?
What would be the best Python library to use when producing text-based images requiring things such as leading, kerning, outlines, drop-shadows, etc?
I've worked with PIL before for resizing images, but the methods for working with text seem rather limited. Is there a better alternative?
A:
What you seem to want to do is exactly what LaTeX was designed for. With plasTeX, you can convert LaTeX markup to an image. Here's an example of what you can do with this (from the plasTeX documentation)
(source: sourceforge.net)
.
Notice the shadows and text effects.
A:
Cairo is very capable, and there are Python bindings to Cairo. Though, when I used it, I had to look into C documentation too.
|
Image library with advanced text effects?
|
What would be the best Python library to use when producing text-based images requiring things such as leading, kerning, outlines, drop-shadows, etc?
I've worked with PIL before for resizing images, but the methods for working with text seem rather limited. Is there a better alternative?
|
[
"What you seem to want to do is exactly what LaTeX was designed for. With plasTeX, you can convert LaTeX markup to an image. Here's an example of what you can do with this (from the plasTeX documentation) \n(source: sourceforge.net)\n. \nNotice the shadows and text effects.\n",
"Cairo is very capable, and there are Python bindings to Cairo. Though, when I used it, I had to look into C documentation too.\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"python_imaging_library"
] |
stackoverflow_0001972044_python_python_imaging_library.txt
|
Q:
python - problem int/string and hash/array
f = open('transaction.log','r')
ClerkHash = dict()
arr = [0,0]
for line in f:
Tdate = line[0:12]
AccountKey = line[12:50]
TransType = line[22:2]
ClerkKey = line[24:10]
CurrencyCode = line[34:2]
Amount = line[36:45]
print line
print '\n'
print AccountKey
print '\n'
print Tdate print '\n'
if TransType=="04":
ClerkHash[ClerkKey+AccountKey] = arr; // is this line corrent ? i don't want to corrupt the array every time ? how should i do it ?
ClerkHash[ClerkKey+AccountKey][0]+=1
ClerkHash[ClerkKey+AccountKey][1]+= Amount
for Key in ClerkHash.keys():
if ClerkHash[key][0] >= 3 and ClerkHash[key][1] > 1000:
print Key
i want to have an hash name ClerkHash[ClerkKey+AccountKey]
which consistes of array of 2 int : first index is withdrawl num , and second is ammount
did i defined the array and hash well ?
in addition i want to sum the ammount...how can i do it ?
A:
Here is few issue I seen so far
Amount = line[36:45]
should be
Amount = int(line[36:45])
and
ClerkHash[ClerkKey+AccountKey] = arr[0,0]
should be
ClerkHash[ClerkKey+AccountKey] = [0,0]
A:
Check your slice intervals! The second argument is another index, NOT the number of steps to take from the first index. I guess
TransType = line[22:2]
should rather be
TransType = line[22:24]
You overwrite values if you set
ClerkHash[ClerkKey+AccountKey] = [0, 0]
each time you encounter TransType == "04". So change
if TransType=="04":
ClerkHash[ClerkKey+AccountKey] = arr[0,0]
ClerkHash[ClerkKey+AccountKey][0]+=1
ClerkHash[ClerkKey+AccountKey][1]+= Amount
to
if TransType=="04":
if not ClerkHash.has_key(ClerkKey+AccountKey):
ClerkHash[ClerkKey+AccountKey] = [1, Amount]
else:
ClerkHash[ClerkKey+AccountKey][0] += 1
ClerkHash[ClerkKey+AccountKey][1] += Amount
|
python - problem int/string and hash/array
|
f = open('transaction.log','r')
ClerkHash = dict()
arr = [0,0]
for line in f:
Tdate = line[0:12]
AccountKey = line[12:50]
TransType = line[22:2]
ClerkKey = line[24:10]
CurrencyCode = line[34:2]
Amount = line[36:45]
print line
print '\n'
print AccountKey
print '\n'
print Tdate print '\n'
if TransType=="04":
ClerkHash[ClerkKey+AccountKey] = arr; // is this line corrent ? i don't want to corrupt the array every time ? how should i do it ?
ClerkHash[ClerkKey+AccountKey][0]+=1
ClerkHash[ClerkKey+AccountKey][1]+= Amount
for Key in ClerkHash.keys():
if ClerkHash[key][0] >= 3 and ClerkHash[key][1] > 1000:
print Key
i want to have an hash name ClerkHash[ClerkKey+AccountKey]
which consistes of array of 2 int : first index is withdrawl num , and second is ammount
did i defined the array and hash well ?
in addition i want to sum the ammount...how can i do it ?
|
[
"Here is few issue I seen so far\nAmount = line[36:45]\n\nshould be\nAmount = int(line[36:45])\n\nand \nClerkHash[ClerkKey+AccountKey] = arr[0,0]\n\nshould be\nClerkHash[ClerkKey+AccountKey] = [0,0]\n\n",
"Check your slice intervals! The second argument is another index, NOT the number of steps to take from the first index. I guess\nTransType = line[22:2]\n\nshould rather be\nTransType = line[22:24]\n\nYou overwrite values if you set \nClerkHash[ClerkKey+AccountKey] = [0, 0]\n\neach time you encounter TransType == \"04\". So change\nif TransType==\"04\":\n ClerkHash[ClerkKey+AccountKey] = arr[0,0]\n ClerkHash[ClerkKey+AccountKey][0]+=1 \n ClerkHash[ClerkKey+AccountKey][1]+= Amount\n\nto\nif TransType==\"04\":\n if not ClerkHash.has_key(ClerkKey+AccountKey):\n ClerkHash[ClerkKey+AccountKey] = [1, Amount]\n else:\n ClerkHash[ClerkKey+AccountKey][0] += 1 \n ClerkHash[ClerkKey+AccountKey][1] += Amount\n\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"string"
] |
stackoverflow_0001974434_python_string.txt
|
Q:
Python sched alternative to cancel all events
I'm looking for an alternative to the sched module which would allow me to cancel all events at any time. sched only allows to cancel single events by id (which is returned from the scheduler when an event is scheduled).
Any pointers to Python alternatives to sched would be appreciated.
Thanks
Toni p
A:
In python 2.6, there is a read-only attribute called queue returning a list of upcoming events. So this will cancel all events:
s = sched.scheduler(time.time, time.sleep)
map(s.cancel, s.queue)
Update for Python 3:
Python 3 map() returns the iterator. Therefore, the object must be converted to the list.
s = sched.scheduler (time.time, time.sleep)
list(map(s.cancel, s.queue))
Check out https://stackoverflow.com/a/1303354/6523409 and https://stackoverflow.com/a/13623676/6523409
|
Python sched alternative to cancel all events
|
I'm looking for an alternative to the sched module which would allow me to cancel all events at any time. sched only allows to cancel single events by id (which is returned from the scheduler when an event is scheduled).
Any pointers to Python alternatives to sched would be appreciated.
Thanks
Toni p
|
[
"In python 2.6, there is a read-only attribute called queue returning a list of upcoming events. So this will cancel all events:\ns = sched.scheduler(time.time, time.sleep)\nmap(s.cancel, s.queue)\n\nUpdate for Python 3:\nPython 3 map() returns the iterator. Therefore, the object must be converted to the list.\ns = sched.scheduler (time.time, time.sleep)\nlist(map(s.cancel, s.queue))\n\nCheck out https://stackoverflow.com/a/1303354/6523409 and https://stackoverflow.com/a/13623676/6523409\n"
] |
[
12
] |
[] |
[] |
[
"events",
"python"
] |
stackoverflow_0001974571_events_python.txt
|
Q:
django double "extends", problem with login
Hi:) I have got a small problem with template double extends system. I have got a scheme:
base.html ---> index.html ---> something.html
When I log in to the site I have got access to all invisible blocks (invisible blocks for anonymous users) like:
{% if user.is_superuser %}
blabla
{% endif %}
So "blabla" is visible for me, because I am a superuser and I'm logged in. It works fine in base.html, index.html but it doesn't work in something.html. Why?? Simple it looks like user: 'superuser' is log out.
A:
Are you passing the request context to render_to_response (or HttpResponse)?
Information about logged in user must be stored in the context (see documentation), and you have to do it explicitly.
Generic views automatically do it, but if you are using your own view for something.html, with a direct call to render_to_response, then you do not have information about the user.
Therefore, the code in the view should look something like:
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_personalized_view(request):
return render_to_response('something.html',
{},
context_instance=RequestContext(request))
|
django double "extends", problem with login
|
Hi:) I have got a small problem with template double extends system. I have got a scheme:
base.html ---> index.html ---> something.html
When I log in to the site I have got access to all invisible blocks (invisible blocks for anonymous users) like:
{% if user.is_superuser %}
blabla
{% endif %}
So "blabla" is visible for me, because I am a superuser and I'm logged in. It works fine in base.html, index.html but it doesn't work in something.html. Why?? Simple it looks like user: 'superuser' is log out.
|
[
"Are you passing the request context to render_to_response (or HttpResponse)?\nInformation about logged in user must be stored in the context (see documentation), and you have to do it explicitly.\nGeneric views automatically do it, but if you are using your own view for something.html, with a direct call to render_to_response, then you do not have information about the user.\nTherefore, the code in the view should look something like:\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\n\ndef my_personalized_view(request):\n return render_to_response('something.html',\n {},\n context_instance=RequestContext(request))\n\n"
] |
[
1
] |
[] |
[] |
[
"authentication",
"django",
"python"
] |
stackoverflow_0001974478_authentication_django_python.txt
|
Q:
Is there a python-equivalent of the unix "file" utility?
I want to have different behavior in a python script, depending on the type of file. I cannot use the filename extension as it may not be present or misleading. I could call the file utility and parse the output, but I would rather use a python builtin for portability.
So is there anything in python that uses heuristics to deduce the type of the file from its contents?
A:
python-magic
pymagic
Probably others as well. "magic" is the magic keyword to search for. ;-)
|
Is there a python-equivalent of the unix "file" utility?
|
I want to have different behavior in a python script, depending on the type of file. I cannot use the filename extension as it may not be present or misleading. I could call the file utility and parse the output, but I would rather use a python builtin for portability.
So is there anything in python that uses heuristics to deduce the type of the file from its contents?
|
[
"\npython-magic\npymagic\n\nProbably others as well. \"magic\" is the magic keyword to search for. ;-)\n"
] |
[
18
] |
[] |
[] |
[
"python",
"unix"
] |
stackoverflow_0001974724_python_unix.txt
|
Q:
how to distribute python app with glade GUI?
I'm trying to distribute this app that I wrote in python. The application consists of 2 python scripts. 2 .glade files and 1 .png file.
Here is my dir structure on this project
vasm/
vasmcc.py
src/
vasm.py
gui/
vasm.glade
vasmset.glade
logo.png
vasmcc is just the python script for the gui... the real python module would be vasm.py.
My question is, how do I distribute this so that it includes the .glade and the .png files?
By distribute I mean provide an installable source package that can be installed on to another system.
A:
You should take a look at distutils. You can tell it to install all kinds of files, not just the source code itself. For the user, installing your program then comes down to
$ python setup.py install
and it's even pretty easy to, say, create RPM packages with distutils.
|
how to distribute python app with glade GUI?
|
I'm trying to distribute this app that I wrote in python. The application consists of 2 python scripts. 2 .glade files and 1 .png file.
Here is my dir structure on this project
vasm/
vasmcc.py
src/
vasm.py
gui/
vasm.glade
vasmset.glade
logo.png
vasmcc is just the python script for the gui... the real python module would be vasm.py.
My question is, how do I distribute this so that it includes the .glade and the .png files?
By distribute I mean provide an installable source package that can be installed on to another system.
|
[
"You should take a look at distutils. You can tell it to install all kinds of files, not just the source code itself. For the user, installing your program then comes down to\n$ python setup.py install\n\nand it's even pretty easy to, say, create RPM packages with distutils.\n"
] |
[
2
] |
[] |
[] |
[
"distutils",
"glade",
"python",
"user_interface"
] |
stackoverflow_0001974733_distutils_glade_python_user_interface.txt
|
Q:
Debug history of variable changing in python
I need magic tool, that helps me to understand where one my problem variable is changed in the code.
I know about perfect tool:
pdb.set_trace()
and I need something similar format, but about only one variable changing history.
For example, my current problem is strange value of context['request'] variable inside Django's tag template definition method. The value is string '<<request>>' and I don't understand where it modified from Django's Request object. I can't debug it, because problem is appearing not so often, but permanently. I only see it in error emails and I can't call it specially. The perfect solution will be to create a log with variable's assignment and any modifications.
A:
I'm not really familiar with django, so your mileage may vary. In general, you can override the __setitem__ method on objects to capture item assignment. However, this doesn't work on dictionaries, only on user-created classes, so first of all it depends on what this context object is.
As I get from a short look at the Django docs, it's indeed not a regular dict, so you can try something like this:
def log_setitem(obj):
class Logged(obj.__class__):
def __setitem__(self, item, val):
print "setting", item, "to", val, "on", self
super(Logged, self).__setitem__(item, val)
obj.__class__ = Logged
d = {}
try:
log_setitem(d) # throws an error
except:
print "doesn't work"
class Dict2(dict):
pass
d2 = Dict2()
log_setitem(d2) # this works
d2["hello"] = "world" # prints the log message before assigning
Even if this works, it of course only works if the assignment actually happens through the "standard" way, i.e. somewhere in the code there's a call like context['request'] = "something".
Might be worth a try, but I can't promise you anything.
|
Debug history of variable changing in python
|
I need magic tool, that helps me to understand where one my problem variable is changed in the code.
I know about perfect tool:
pdb.set_trace()
and I need something similar format, but about only one variable changing history.
For example, my current problem is strange value of context['request'] variable inside Django's tag template definition method. The value is string '<<request>>' and I don't understand where it modified from Django's Request object. I can't debug it, because problem is appearing not so often, but permanently. I only see it in error emails and I can't call it specially. The perfect solution will be to create a log with variable's assignment and any modifications.
|
[
"I'm not really familiar with django, so your mileage may vary. In general, you can override the __setitem__ method on objects to capture item assignment. However, this doesn't work on dictionaries, only on user-created classes, so first of all it depends on what this context object is.\nAs I get from a short look at the Django docs, it's indeed not a regular dict, so you can try something like this:\ndef log_setitem(obj):\n class Logged(obj.__class__):\n def __setitem__(self, item, val):\n print \"setting\", item, \"to\", val, \"on\", self\n super(Logged, self).__setitem__(item, val)\n\n obj.__class__ = Logged\n\nd = {}\ntry:\n log_setitem(d) # throws an error\nexcept:\n print \"doesn't work\"\n\nclass Dict2(dict):\n pass\n\nd2 = Dict2()\nlog_setitem(d2) # this works\n\nd2[\"hello\"] = \"world\" # prints the log message before assigning\n\nEven if this works, it of course only works if the assignment actually happens through the \"standard\" way, i.e. somewhere in the code there's a call like context['request'] = \"something\".\nMight be worth a try, but I can't promise you anything.\n"
] |
[
2
] |
[] |
[] |
[
"debugging",
"django",
"python"
] |
stackoverflow_0001974997_debugging_django_python.txt
|
Q:
epoch timestamp converter with millennia range, python
is there an epoch time converter that can deal with millennia?
time.gmtime(1000 * 365 * 24 * 60 * 60)
throws
ValueError: timestamp out of range for platform time_t
A:
Yes, at least on Windows (using Windows 7 here). What platform are you using?
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
>>> time.gmtime(1000*365*24*60*60)
time.struct_time(tm_year=2969, tm_mon=5, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=123, tm_isdst=0)
Also, even on Linux you should be able to do some processing of dates well beyond 2038 using the datetime module. The docs say MAXYEAR is 9999 for that module:
>>> dt = datetime.datetime.now().replace(year=1000+1971)
>>> dt
datetime.datetime(2971, 12, 29, 11, 43, 20, 727000)
>>> dt.timetuple()
time.struct_time(tm_year=2971, tm_mon=12, tm_mday=29, tm_hour=11, tm_min=41, tm_sec=16, tm_wday=6, tm_yday=363, tm_isdst=-1)
Of course, that last call probably won't work on Linux if the time.gmtime() call is failing, but since you haven't really said what you want to do with the date maybe this is sufficient for now.
|
epoch timestamp converter with millennia range, python
|
is there an epoch time converter that can deal with millennia?
time.gmtime(1000 * 365 * 24 * 60 * 60)
throws
ValueError: timestamp out of range for platform time_t
|
[
"Yes, at least on Windows (using Windows 7 here). What platform are you using?\nPython 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32\n>>> time.gmtime(1000*365*24*60*60)\ntime.struct_time(tm_year=2969, tm_mon=5, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=123, tm_isdst=0)\n\nAlso, even on Linux you should be able to do some processing of dates well beyond 2038 using the datetime module. The docs say MAXYEAR is 9999 for that module:\n>>> dt = datetime.datetime.now().replace(year=1000+1971)\n>>> dt\ndatetime.datetime(2971, 12, 29, 11, 43, 20, 727000)\n>>> dt.timetuple()\ntime.struct_time(tm_year=2971, tm_mon=12, tm_mday=29, tm_hour=11, tm_min=41, tm_sec=16, tm_wday=6, tm_yday=363, tm_isdst=-1)\n\nOf course, that last call probably won't work on Linux if the time.gmtime() call is failing, but since you haven't really said what you want to do with the date maybe this is sufficient for now.\n"
] |
[
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001975524_python.txt
|
Q:
Is there a platform agnostic implementation of time.gmtime?
on google appengine (http://shell.appspot.com/):
>>> time.gmtime(1000*365*24*60*60)
(2969, 5, 3, 0, 0, 0, 2, 123, 0)
on macosx:
>>> time.gmtime(1000*365*24*60*60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform time_t
is there a platform agnostic implementation of time.gmtime?
A:
The time module is defined to be platform-specific.
The functions in this module do not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for Unix, it is typically in 2038.
You can use the datetime type without timezone info ("naive datetimes"), understood by convention in your program to be GMT, or follow the (complicated) tzinfo instructions in the docs.
>>> import datetime
>>> datetime.datetime(2969, 5, 3).year
2969
>>> datetime.MINYEAR, datetime.MAXYEAR
(1, 9999)
|
Is there a platform agnostic implementation of time.gmtime?
|
on google appengine (http://shell.appspot.com/):
>>> time.gmtime(1000*365*24*60*60)
(2969, 5, 3, 0, 0, 0, 2, 123, 0)
on macosx:
>>> time.gmtime(1000*365*24*60*60)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: timestamp out of range for platform time_t
is there a platform agnostic implementation of time.gmtime?
|
[
"The time module is defined to be platform-specific.\n\nThe functions in this module do not handle dates and times before the epoch or far in the future. The cut-off point in the future is determined by the C library; for Unix, it is typically in 2038.\n\nYou can use the datetime type without timezone info (\"naive datetimes\"), understood by convention in your program to be GMT, or follow the (complicated) tzinfo instructions in the docs.\n>>> import datetime\n>>> datetime.datetime(2969, 5, 3).year\n2969\n>>> datetime.MINYEAR, datetime.MAXYEAR\n(1, 9999)\n\n"
] |
[
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001975693_python.txt
|
Q:
django, runserver_plus - admin media files served from wrong path
The configuration below works fine on my remote host (same dir structure, same django), all admin media are served properly
settings
MEDIA_ROOT = '%s/static/' % FS_ROOT
STATIC_DOC_ROOT = '%s/static/' % FS_ROOT
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '%smedia/' % MEDIA_URL
urls
(r'^admin/', include(admin.site.urls)),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/static' % FS_ROOT }),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/media' % FS_ROOT }),
django 1.2.0 @ ubuntu 9.10, http://127.0.0.1:8084/ via runserver_plus
Admin media files are stored under /static/media/ in my project root dir and every static files/dirs under /static/. All statics are served fine, only the admin media are taken from the default django's admin media files. What am I forgetting and why it does affect the project only on my localhost? I've tried to everride /static/media/ path in the urls in various ways, but still nothing.
A:
There are two solutions:
You can either set a hostname in ADMIN_MEDIA_PREFIX as suggested in this answer.
Or you can start the development server with the --adminmedia parameter as described in the django documentation.
|
django, runserver_plus - admin media files served from wrong path
|
The configuration below works fine on my remote host (same dir structure, same django), all admin media are served properly
settings
MEDIA_ROOT = '%s/static/' % FS_ROOT
STATIC_DOC_ROOT = '%s/static/' % FS_ROOT
MEDIA_URL = '/static/'
ADMIN_MEDIA_PREFIX = '%smedia/' % MEDIA_URL
urls
(r'^admin/', include(admin.site.urls)),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/static' % FS_ROOT }),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '%s/media' % FS_ROOT }),
django 1.2.0 @ ubuntu 9.10, http://127.0.0.1:8084/ via runserver_plus
Admin media files are stored under /static/media/ in my project root dir and every static files/dirs under /static/. All statics are served fine, only the admin media are taken from the default django's admin media files. What am I forgetting and why it does affect the project only on my localhost? I've tried to everride /static/media/ path in the urls in various ways, but still nothing.
|
[
"There are two solutions:\n\nYou can either set a hostname in ADMIN_MEDIA_PREFIX as suggested in this answer.\nOr you can start the development server with the --adminmedia parameter as described in the django documentation.\n\n"
] |
[
1
] |
[] |
[] |
[
"django",
"django_admin",
"file",
"media",
"python"
] |
stackoverflow_0001974697_django_django_admin_file_media_python.txt
|
Q:
Does Google Webapp framework for Google App Engine maintain a link to the database?
1) When a script gets data from the database using the db.Model.get_element_by_id("id") method, what id does it refer to, and how can you get it from the database.
2) If you get a result using this method, does that result maintain a link to the database so that any changes to the result are reflected on the database? If not, how would you update an entry in the database?
A:
As Jonathan Feinberg suggested, this is answered in the Google App Engine tutorial. The relevant piece of the tutorial is found here: http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html
On that page, this text specifically answers your question about "how would you update an entry in the database:
Finally, greeting.put() saves our new object to the datastore. If we acquired this object from a query, put() would update the existing object. Since we created this object with the model constructor, put() adds the new object to the datastore.
The explanation for keys and such is found on this documentation page: http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html
And as a final suggestion, don't worry about things like "maintaining a connection to the database". The entire premise of the Google App Engine is that they have abstracted away things like connection management, and such, so that you can benefit from the inherent scalability of the platform. Sticking to the documentation and learning about the libraries and frameworks that are available will be the best route to success.
A:
Every entity in the db can have either a numeric ID or a key name; the get_by_id class method can actually fetch by either, depending on whether you pass it a number (then it looks for that ID) or a string (then it looks for that key name). (You can also pass it a list which contains numbers, numbers and strings, etc).
Given an entity x, you can get a Key object k by k = x.key(), then k.id() returns the numeric ID of entity x (or None if the entity has no numeric ID), k.name() returns the name or None (you can also check if either is present by if k.has_id_or_name():, and get whichever of the two is present, or None if neither are, by k.id_or_name().
There is no "link"; the ID or key name can be thought of as the one and only "primary key" to the entity in the DB (actually it automatically gets mixed with some other bits of metadata like the app's name;-). When you put an existing entity (after getting it and changing something) that primary key lets the DB overwrite the existing entity rather than creating a new one.
|
Does Google Webapp framework for Google App Engine maintain a link to the database?
|
1) When a script gets data from the database using the db.Model.get_element_by_id("id") method, what id does it refer to, and how can you get it from the database.
2) If you get a result using this method, does that result maintain a link to the database so that any changes to the result are reflected on the database? If not, how would you update an entry in the database?
|
[
"As Jonathan Feinberg suggested, this is answered in the Google App Engine tutorial. The relevant piece of the tutorial is found here: http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html\nOn that page, this text specifically answers your question about \"how would you update an entry in the database:\n\nFinally, greeting.put() saves our new object to the datastore. If we acquired this object from a query, put() would update the existing object. Since we created this object with the model constructor, put() adds the new object to the datastore.\n\nThe explanation for keys and such is found on this documentation page: http://code.google.com/appengine/docs/python/datastore/keysandentitygroups.html\nAnd as a final suggestion, don't worry about things like \"maintaining a connection to the database\". The entire premise of the Google App Engine is that they have abstracted away things like connection management, and such, so that you can benefit from the inherent scalability of the platform. Sticking to the documentation and learning about the libraries and frameworks that are available will be the best route to success.\n",
"Every entity in the db can have either a numeric ID or a key name; the get_by_id class method can actually fetch by either, depending on whether you pass it a number (then it looks for that ID) or a string (then it looks for that key name). (You can also pass it a list which contains numbers, numbers and strings, etc).\nGiven an entity x, you can get a Key object k by k = x.key(), then k.id() returns the numeric ID of entity x (or None if the entity has no numeric ID), k.name() returns the name or None (you can also check if either is present by if k.has_id_or_name():, and get whichever of the two is present, or None if neither are, by k.id_or_name().\nThere is no \"link\"; the ID or key name can be thought of as the one and only \"primary key\" to the entity in the DB (actually it automatically gets mixed with some other bits of metadata like the app's name;-). When you put an existing entity (after getting it and changing something) that primary key lets the DB overwrite the existing entity rather than creating a new one.\n"
] |
[
2,
1
] |
[] |
[] |
[
"database",
"google_app_engine",
"python",
"reference",
"web_applications"
] |
stackoverflow_0001976254_database_google_app_engine_python_reference_web_applications.txt
|
Q:
TypeError: can't multiply sequence by non-int of type 'float'
I am a noob to Python and have not had any luck figuring this out. I want to be able to keep the tax variable in the code so it would be easily updated should it change. I have experimented with different means but was only able to get it to skip the print tax line and print the same values for the total and subtotal. How do I multiply the tax variable by sum(items_count)? Here is the code:
items_count = []
tax = float(.06)
y = 0
count = raw_input('How many items do you have? ')
while count > 0:
price = float(raw_input('Please enter the price of your item: '))
items_count.append(price)
count = int(count) - 1
print 'The subtotal of your items is: ' '$%.2f' % sum(items_count)
print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax
total = (sum(items_count) * tax) + sum(items_count)
print 'The total of your items is: ' '$%.2f' % total
A:
It would help if you provide the back-trace for the error. I ran your code, and got this back-trace:
Traceback (most recent call last):
File "t.py", line 13, in <module>
print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax
TypeError: can't multiply sequence by non-int of type 'float'
The answer is that this is a precedence problem. If you just did this:
sum(items_count) * tax
it would work, but because you have the expression with the string and the % operator, the call to sum() is tied to the string, and effectively you have:
<string_value> * tax
The solution is to add parentheses to force the precedence you want:
print 'The amount of sales tax is: ' '$%.2f' % (sum(items_count) * tax)
Here is documentation of operator precedence in Python.
http://docs.python.org/reference/expressions.html#summary
Note that % has the same precedence as *, so the order is then controlled by the left-to-right rule. Thus, the string and the call to sum() are connected with the % operator, and you are left with <string_value> * tax.
Note that instead of parentheses, you could also use an explicit temporary:
items_tax = sum(items_count) * tax
print 'The amount of sales tax is: ' '$%.2f' % items_tax
When you aren't sure what is going on, sometimes it's a good idea to start using explicit temporary variables, and check to see that each one is set to the value you were expecting.
P.S. You don't actually need all the calls to float(). The value 0.06 is already a float value, so it is sufficient to just say:
tax = 0.06
I like to put the initial zero on fractions, but you can use either of tax = 0.06 or tax = .06, it doesn't matter.
I like how you convert the prices to float by wrapping the raw_input() call in float(). I suggest that you should do the same thing for count, wrap the raw_input() call in int() to get an int value. Then the later expression can simply be
count -= 1
It's a bit tricky that count is initially set to a string and then re-bound later. If a silly or crazy user enters an invalid count, int() will raise an exception; it is better if the exception happens right away, right on the call to raw_input(), rather than later in a seemingly simple expression.
And of course you aren't using y for anything in your code sample.
A:
You need to use
'$%.2f' % (sum(items_count) * tax)
instead of
'$%.2f' % sum(items_count) * tax
The one you used will be evaluated as ('$%.2f' % sum(items_count)) * tax, which is an error (multiplying a string by a float).
A:
You need parentheses around the sum(items_count) * tax.
I took the liberty of cleaning up your code a bit as well :)
items_count = []
tax = float(.06)
count = int(raw_input('How many items do you have? '))
while count:
price = float(raw_input('Please enter the price of your item: '))
items_count.append(price)
count -= 1
print 'The subtotal of your items is: $%.2f' % sum(items_count)
print 'The amount of sales tax is: $%.2f' % (sum(items_count) * tax)
print 'The total of your items is: $%.2f' % ((sum(items_count) * tax) +
sum(items_count))
A:
Just add parens:
print 'The amount of sales tax is: ' '$%.2f' % (sum(items_count) * tax)
|
TypeError: can't multiply sequence by non-int of type 'float'
|
I am a noob to Python and have not had any luck figuring this out. I want to be able to keep the tax variable in the code so it would be easily updated should it change. I have experimented with different means but was only able to get it to skip the print tax line and print the same values for the total and subtotal. How do I multiply the tax variable by sum(items_count)? Here is the code:
items_count = []
tax = float(.06)
y = 0
count = raw_input('How many items do you have? ')
while count > 0:
price = float(raw_input('Please enter the price of your item: '))
items_count.append(price)
count = int(count) - 1
print 'The subtotal of your items is: ' '$%.2f' % sum(items_count)
print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax
total = (sum(items_count) * tax) + sum(items_count)
print 'The total of your items is: ' '$%.2f' % total
|
[
"It would help if you provide the back-trace for the error. I ran your code, and got this back-trace:\nTraceback (most recent call last):\n File \"t.py\", line 13, in <module>\n print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax\nTypeError: can't multiply sequence by non-int of type 'float'\n\nThe answer is that this is a precedence problem. If you just did this:\nsum(items_count) * tax\n\nit would work, but because you have the expression with the string and the % operator, the call to sum() is tied to the string, and effectively you have:\n<string_value> * tax\n\nThe solution is to add parentheses to force the precedence you want:\nprint 'The amount of sales tax is: ' '$%.2f' % (sum(items_count) * tax)\n\nHere is documentation of operator precedence in Python.\nhttp://docs.python.org/reference/expressions.html#summary\nNote that % has the same precedence as *, so the order is then controlled by the left-to-right rule. Thus, the string and the call to sum() are connected with the % operator, and you are left with <string_value> * tax.\nNote that instead of parentheses, you could also use an explicit temporary:\nitems_tax = sum(items_count) * tax\nprint 'The amount of sales tax is: ' '$%.2f' % items_tax\n\nWhen you aren't sure what is going on, sometimes it's a good idea to start using explicit temporary variables, and check to see that each one is set to the value you were expecting.\nP.S. You don't actually need all the calls to float(). The value 0.06 is already a float value, so it is sufficient to just say:\ntax = 0.06\n\nI like to put the initial zero on fractions, but you can use either of tax = 0.06 or tax = .06, it doesn't matter.\nI like how you convert the prices to float by wrapping the raw_input() call in float(). I suggest that you should do the same thing for count, wrap the raw_input() call in int() to get an int value. Then the later expression can simply be\ncount -= 1\n\nIt's a bit tricky that count is initially set to a string and then re-bound later. If a silly or crazy user enters an invalid count, int() will raise an exception; it is better if the exception happens right away, right on the call to raw_input(), rather than later in a seemingly simple expression.\nAnd of course you aren't using y for anything in your code sample.\n",
"You need to use\n'$%.2f' % (sum(items_count) * tax)\n\ninstead of\n'$%.2f' % sum(items_count) * tax\n\nThe one you used will be evaluated as ('$%.2f' % sum(items_count)) * tax, which is an error (multiplying a string by a float).\n",
"You need parentheses around the sum(items_count) * tax.\nI took the liberty of cleaning up your code a bit as well :)\nitems_count = []\ntax = float(.06)\n\ncount = int(raw_input('How many items do you have? '))\n\nwhile count:\n price = float(raw_input('Please enter the price of your item: '))\n items_count.append(price)\n count -= 1\n\nprint 'The subtotal of your items is: $%.2f' % sum(items_count)\nprint 'The amount of sales tax is: $%.2f' % (sum(items_count) * tax)\nprint 'The total of your items is: $%.2f' % ((sum(items_count) * tax) +\n sum(items_count))\n\n",
"Just add parens:\nprint 'The amount of sales tax is: ' '$%.2f' % (sum(items_count) * tax)\n\n"
] |
[
5,
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001976467_python.txt
|
Q:
semantic markup for Python's difflib.HtmlDiff
It appears Python's difflib.HtmlDiff, rather than using INS and DEL, uses SPAN elements with custom classes:
python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.make_table(txt1, txt2)'
Before I go about fixing this myself, has anyone looked into this already?
Is there perhaps a valid reason for not using POSH?
(Google wasn't a big help here... )
A:
This script by Aaron Swartz uses difflib to output ins/del.
A:
The python bug tracker is here: http://bugs.python.org/
There's no open bug on this issue, which I guess is because most people would not care what sort of html it is as long as it works. If it's important to you, file a bug and submit a patch.
|
semantic markup for Python's difflib.HtmlDiff
|
It appears Python's difflib.HtmlDiff, rather than using INS and DEL, uses SPAN elements with custom classes:
python -c 'import difflib; txt1 = "lorem ipsum\ndolor sit amet".splitlines(); txt2 = "lorem foo isum\ndolor amet".splitlines(); d = difflib.HtmlDiff(); print d.make_table(txt1, txt2)'
Before I go about fixing this myself, has anyone looked into this already?
Is there perhaps a valid reason for not using POSH?
(Google wasn't a big help here... )
|
[
"This script by Aaron Swartz uses difflib to output ins/del.\n",
"The python bug tracker is here: http://bugs.python.org/\nThere's no open bug on this issue, which I guess is because most people would not care what sort of html it is as long as it works. If it's important to you, file a bug and submit a patch.\n"
] |
[
3,
2
] |
[] |
[] |
[
"diff",
"python",
"semantics"
] |
stackoverflow_0000745600_diff_python_semantics.txt
|
Q:
Piecing together Django views
Is it good practice to treat individual app views as a blocks of HTML that can be pieced together to form a larger site? If not, what is the best way to reuse app views from project to project, assuming each one uses a different set of templates?
A:
A general good practice to define views with a template_name kwarg. This allows a the default template to be overridden. This is common in generic views.
#my reusable view
def list_items(request, template_name="items.html"):
items=Item.objects.all()
return render_to_response(template_name,
{'items': items},
context_instance=RequestContext(request))
#some other view
from my.reusable.views import list_items
def list_special(request, template_name="spectial_items.html"):
return list_items(request, template_name=template_name)
A:
Your question is little too generic.
The general way of doing it involves:
Extend templates of the reusable apps
Pass the new template name to the view (Reusable apps should accepts that argument)
Also pass extra_context to the reusable-generic-view
Use your own view to create an extra_context and return the reuse-able view, from your view.
A:
usually each application should provide views for the basic functionality - where the application takes full control over the user and the page.
functionality which can be displayed in the basic page layout (e.g. 'last 5 posts in my blog') would be a perfect use case for template tags - i usually use simple inclusion tags. so you wouldn't combine multiple views into one template, but always have one view which handles the request, and everything around can be aggregated using template tags.
|
Piecing together Django views
|
Is it good practice to treat individual app views as a blocks of HTML that can be pieced together to form a larger site? If not, what is the best way to reuse app views from project to project, assuming each one uses a different set of templates?
|
[
"A general good practice to define views with a template_name kwarg. This allows a the default template to be overridden. This is common in generic views.\n#my reusable view\ndef list_items(request, template_name=\"items.html\"):\n items=Item.objects.all()\n return render_to_response(template_name,\n {'items': items},\n context_instance=RequestContext(request))\n\n#some other view\nfrom my.reusable.views import list_items\n\ndef list_special(request, template_name=\"spectial_items.html\"):\n return list_items(request, template_name=template_name)\n\n",
"Your question is little too generic.\nThe general way of doing it involves:\n\nExtend templates of the reusable apps\nPass the new template name to the view (Reusable apps should accepts that argument)\nAlso pass extra_context to the reusable-generic-view\nUse your own view to create an extra_context and return the reuse-able view, from your view.\n\n",
"usually each application should provide views for the basic functionality - where the application takes full control over the user and the page.\nfunctionality which can be displayed in the basic page layout (e.g. 'last 5 posts in my blog') would be a perfect use case for template tags - i usually use simple inclusion tags. so you wouldn't combine multiple views into one template, but always have one view which handles the request, and everything around can be aggregated using template tags.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001975769_django_python.txt
|
Q:
Retrieving ORM properties with SQLAlchemy
I have three tables (users, articles, and tags) defined in SQLAlchemy and mapped with orm.mapper(). As you can see below, I'm adding a property "author" to each article which ties that article to the user that created it.
orm.mapper(User, t_users)
orm.mapper(Tag, t_tags)
orm.mapper(Article, t_articles, properties={
'author' : orm.relation(User),
'tags' : orm.relation(Tag, secondary=t_tags_articles),
})
I'm listing an index of articles, and each article will need to show its tags and its author. I'm trying to figure out the best way (minimal SQL queries, better performance) to retrieve the author and tags data.
If I do this:
results = Session.query(Article).all()
then I can pull the author and tags for each article in the index like this:
author = results[0].author
tags = results[0].tags
but this runs two new queries for each results[x] that I loop through (yikes). If I do this:
results = Session.query(Article, User).join('author').all()
then I can access the author data like this (because it's joined in):
firstname = results[0].firstname
but trying to get a list of tags doesn't work, and instead raises an AttributeError ('rowTuple' object has no attribute 'tags'):
tags = results[0].tags
What am I doing wrong, and what's the best way to access the data for this index?
A:
Considered eagerloading, as covered in Working with Related Objects?
Your join is also funky. You're mixing the ORM with the SQL-toolkit, so you're getting row-objects and not mapped objects back. See Querying with Joins
|
Retrieving ORM properties with SQLAlchemy
|
I have three tables (users, articles, and tags) defined in SQLAlchemy and mapped with orm.mapper(). As you can see below, I'm adding a property "author" to each article which ties that article to the user that created it.
orm.mapper(User, t_users)
orm.mapper(Tag, t_tags)
orm.mapper(Article, t_articles, properties={
'author' : orm.relation(User),
'tags' : orm.relation(Tag, secondary=t_tags_articles),
})
I'm listing an index of articles, and each article will need to show its tags and its author. I'm trying to figure out the best way (minimal SQL queries, better performance) to retrieve the author and tags data.
If I do this:
results = Session.query(Article).all()
then I can pull the author and tags for each article in the index like this:
author = results[0].author
tags = results[0].tags
but this runs two new queries for each results[x] that I loop through (yikes). If I do this:
results = Session.query(Article, User).join('author').all()
then I can access the author data like this (because it's joined in):
firstname = results[0].firstname
but trying to get a list of tags doesn't work, and instead raises an AttributeError ('rowTuple' object has no attribute 'tags'):
tags = results[0].tags
What am I doing wrong, and what's the best way to access the data for this index?
|
[
"Considered eagerloading, as covered in Working with Related Objects?\nYour join is also funky. You're mixing the ORM with the SQL-toolkit, so you're getting row-objects and not mapped objects back. See Querying with Joins\n"
] |
[
3
] |
[] |
[] |
[
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0001977008_orm_python_sqlalchemy.txt
|
Q:
security question: Changing system password via python
I'm working on a project aimed at system administration for a linux installation.
I need to perform some tasks like change the user password...
I was planning to use the subprocess module for this.
I'm concerned about security so, what are the 'best practices' when doing this via python?
is subprocess sufficient, or is there something better out there for the job?
[EDIT]
I should add that this is not an interactive script, it will parse the values to the system's passwd program
[/EDIT]
A:
I believe the pexpect module would be the easiest way to go about this.
http://pexpect.sourceforge.net/pexpect.html
Something along these lines should work pretty well:
import pexpect
import time
def ChangePassword(user, pass):
passwd = pexpect.spawn("/usr/bin/passwd %s" % user)
for x in xrange(2):
# wait for password: to come out of passwd's stdout
passwd.expect("password: ")
# send pass to passwd's stdin
passwd.sendline(pass)
time.sleep(0.1)
ChangePassword('foo', 'bar') # changes user "foo"'s password to "bar"
|
security question: Changing system password via python
|
I'm working on a project aimed at system administration for a linux installation.
I need to perform some tasks like change the user password...
I was planning to use the subprocess module for this.
I'm concerned about security so, what are the 'best practices' when doing this via python?
is subprocess sufficient, or is there something better out there for the job?
[EDIT]
I should add that this is not an interactive script, it will parse the values to the system's passwd program
[/EDIT]
|
[
"I believe the pexpect module would be the easiest way to go about this.\nhttp://pexpect.sourceforge.net/pexpect.html\nSomething along these lines should work pretty well:\nimport pexpect\nimport time\n\ndef ChangePassword(user, pass):\n passwd = pexpect.spawn(\"/usr/bin/passwd %s\" % user)\n\n for x in xrange(2):\n # wait for password: to come out of passwd's stdout\n passwd.expect(\"password: \")\n # send pass to passwd's stdin\n passwd.sendline(pass)\n time.sleep(0.1)\n\nChangePassword('foo', 'bar') # changes user \"foo\"'s password to \"bar\"\n\n"
] |
[
3
] |
[] |
[] |
[
"python",
"security",
"system"
] |
stackoverflow_0001977022_python_security_system.txt
|
Q:
How to make read-only data accessible by diff requests while the server is running (apache, mod_python)
I am using Apache/2.2.8 (Ubuntu) mod_python/3.3.1 Python/2.5.2 and I would like to preload the data I work with.
Currently I read the data from a file on disk every time I get a request, then parse it and store it in an object. The data file is relatively large and I would like to parse/preload it ahead of time.
I was thinking I could either 1) load the data in memory when apache starts (~100MB to 500MB of data would reside in memory while the server is running) or I could 2) load it when the first data request is submitted and keep it in memory until I shut the server down.
below is the mock up of the second idea:
from mod_python import apache
from mod_python import Session
gvar = 0
def handler(req):
req.content_type = 'text/plain'
session = Session.Session(req)
if session.is_new():
global gvar
req.write('gvar was originally : '+str(gvar))
gvar = 314
session['addr'] = req.connection.remote_ip
session.save()
req.write('\ngvar was just set to: '+str(gvar))
else:
global gvar
req.write('gvar set to: '+str(gvar))
return apache.OK
output (session one):
gvar was originally : 0
gvar was just set to: 314
output (session > 1):
gvar set to: 314
Please share your comments and solutions,
thx
A:
You could set a tmpfs (or ramfs) mount with the data and it will stay in RAM (tmpfs may send data to swap).
A:
You don't say what form your data is in, but if a keystore will suffice then you can use shelve along with OS caching in order to hold the data in a preparsed format.
A:
Another option is to use posix_ipc to hold the data in shared memory, available to all processes.
|
How to make read-only data accessible by diff requests while the server is running (apache, mod_python)
|
I am using Apache/2.2.8 (Ubuntu) mod_python/3.3.1 Python/2.5.2 and I would like to preload the data I work with.
Currently I read the data from a file on disk every time I get a request, then parse it and store it in an object. The data file is relatively large and I would like to parse/preload it ahead of time.
I was thinking I could either 1) load the data in memory when apache starts (~100MB to 500MB of data would reside in memory while the server is running) or I could 2) load it when the first data request is submitted and keep it in memory until I shut the server down.
below is the mock up of the second idea:
from mod_python import apache
from mod_python import Session
gvar = 0
def handler(req):
req.content_type = 'text/plain'
session = Session.Session(req)
if session.is_new():
global gvar
req.write('gvar was originally : '+str(gvar))
gvar = 314
session['addr'] = req.connection.remote_ip
session.save()
req.write('\ngvar was just set to: '+str(gvar))
else:
global gvar
req.write('gvar set to: '+str(gvar))
return apache.OK
output (session one):
gvar was originally : 0
gvar was just set to: 314
output (session > 1):
gvar set to: 314
Please share your comments and solutions,
thx
|
[
"You could set a tmpfs (or ramfs) mount with the data and it will stay in RAM (tmpfs may send data to swap).\n",
"You don't say what form your data is in, but if a keystore will suffice then you can use shelve along with OS caching in order to hold the data in a preparsed format.\n",
"Another option is to use posix_ipc to hold the data in shared memory, available to all processes.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"apache",
"mod_python",
"python"
] |
stackoverflow_0001957148_apache_mod_python_python.txt
|
Q:
sqlalchemy lookup tables
Hi I have a table in 3NF form
ftype_table = Table(
'FTYPE',
Column('ftypeid', Integer, primary_key=True),
Column('typename', String(50)),
base.metadata,
schema='TEMP')
file_table = Table(
'FILE',
base.metadata,
Column('fileid', Integer, primary_key=True),
Column('datatypeid', Integer, ForeignKey(ftype_table.c.datatypeid)),
Column('size', Integer),
schema='TEMP')
and mappers
class File(object): pass
class FileType(object): pass
mapper(File, file_table, properties={'filetype': relation(FileType)})
mapper(FileType, file_table)
suppose Ftype table contains 1:TXT 2:AVI 3:PPT
what i would like to do is the following if i create a File object like this:
file=File()
file.size=10
file.filetype= FileType('PPT')
Session.save(file)
Session.flush()
is that the File table contains fileid:xxx,size:10, datatypeid:3
Unfortunately an entry gets added to the FileType table and this id gets propagated to the File table.
Is there a smart way to do achieve the above with sqlalchemy witout the need to do a query on the FileType table to see if the entry exist or not
Thanks
A:
the UniqueObject recipe is the standard answer here: http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject . The idea is to override the creation of File using either __metaclass__.call() or File.__new__() to return the already-existing object, from the DB or from cache (the initial DB lookup, if the object isn't already present, is obviously unavoidable unless something constructed around MySQL's REPLACE is used).
edit: since I've been working on the usage recipes, I've rewritten the unique object recipe to be more portable and updated for 0.5/0.6.
A:
Just create a cache of FileType objects, so that the database lookup occurs only the first time you use a given file type:
class FileTypeCache(dict):
def __missing__(self, key):
obj = self[key] = Session.query(FileType).filter_by(typename=key).one()
return obj
filetype_cache = FileTypeCache()
file=File()
file.size=10
file.filetype= filetype_cache['PPT']
should work, modulo typos.
A:
Since declarative_base and zzzeek code does not work with sqlalchemy 0.4, I
used the following cache so that new objects also stay unique if they are not present in the db
class FileTypeCache(dict):
def __missing__(self, key):
try:
obj = self[key] = Session.query(FileType).filter_by(typename=key).one()
return obj
except InvalidRequestError:
return obj=self[key]= FileType(key)
return obj
override eq of FileType
class FileType(object):
def __init__(self, typename)
self.typename=typename
def __eq__(self):
if isinstance(other, FileType):
return self.typename == other.typename
else:
return False
|
sqlalchemy lookup tables
|
Hi I have a table in 3NF form
ftype_table = Table(
'FTYPE',
Column('ftypeid', Integer, primary_key=True),
Column('typename', String(50)),
base.metadata,
schema='TEMP')
file_table = Table(
'FILE',
base.metadata,
Column('fileid', Integer, primary_key=True),
Column('datatypeid', Integer, ForeignKey(ftype_table.c.datatypeid)),
Column('size', Integer),
schema='TEMP')
and mappers
class File(object): pass
class FileType(object): pass
mapper(File, file_table, properties={'filetype': relation(FileType)})
mapper(FileType, file_table)
suppose Ftype table contains 1:TXT 2:AVI 3:PPT
what i would like to do is the following if i create a File object like this:
file=File()
file.size=10
file.filetype= FileType('PPT')
Session.save(file)
Session.flush()
is that the File table contains fileid:xxx,size:10, datatypeid:3
Unfortunately an entry gets added to the FileType table and this id gets propagated to the File table.
Is there a smart way to do achieve the above with sqlalchemy witout the need to do a query on the FileType table to see if the entry exist or not
Thanks
|
[
"the UniqueObject recipe is the standard answer here: http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject . The idea is to override the creation of File using either __metaclass__.call() or File.__new__() to return the already-existing object, from the DB or from cache (the initial DB lookup, if the object isn't already present, is obviously unavoidable unless something constructed around MySQL's REPLACE is used).\nedit: since I've been working on the usage recipes, I've rewritten the unique object recipe to be more portable and updated for 0.5/0.6.\n",
"Just create a cache of FileType objects, so that the database lookup occurs only the first time you use a given file type:\n\nclass FileTypeCache(dict):\n def __missing__(self, key):\n obj = self[key] = Session.query(FileType).filter_by(typename=key).one()\n return obj\n\nfiletype_cache = FileTypeCache()\n\nfile=File()\nfile.size=10\nfile.filetype= filetype_cache['PPT']\n\nshould work, modulo typos.\n",
"Since declarative_base and zzzeek code does not work with sqlalchemy 0.4, I\nused the following cache so that new objects also stay unique if they are not present in the db\nclass FileTypeCache(dict):\n def __missing__(self, key):\n try:\n obj = self[key] = Session.query(FileType).filter_by(typename=key).one()\n return obj\n except InvalidRequestError:\n return obj=self[key]= FileType(key)\n return obj\n\noverride eq of FileType\nclass FileType(object):\n def __init__(self, typename)\n self.typename=typename\n def __eq__(self):\n if isinstance(other, FileType):\n return self.typename == other.typename\n else:\n return False\n\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"python",
"sqlalchemy"
] |
stackoverflow_0001964784_python_sqlalchemy.txt
|
Q:
In memory database with socket capability
Python --> SQLite --> ASP.NET C#
I am looking for an in memory database application that does not have to write the data it receives to disc. Basically, I'll be having a Python server which receives gaming UDP data and translates the data and stores it in the memory database engine.
I want to stay away from writing to disc as it takes too long. The data is not important, if something goes wrong, it simply flushes and fills up with the next wave of data sent by players.
Next, another ASP.NET server must be able to connect to this in memory database via TCP/IP at regular intervals, say once every second, or 10 seconds. It has to pull this data, and this will in turn update on a website that displays "live" game data.
I'm looking at SQlite, and wondering, is this the right tool for the job, anyone have any suggestions?
Thanks!!!
A:
Totally not my field, but I think Redis is along these lines.
A:
This sounds like a premature optimization (apologizes if you've already done the profiling). What I would suggest is go ahead and write the system in the simplest, cleanest way, but put a bit of abstraction around the database bits so they can easily by swapped out. Then profile it and find your bottleneck.
If it turns out it is the database, optimize the database in the usual way (indexes, query optimizations, etc...). If its still too slow, most databases support an in-memory table format. Or you can mount a RAM disk and mount individual tables or the whole database on it.
A:
The application of SQlite depends on your data complexity.
If you need to perform complex queries on relational data, then it might be a viable option. If your data is flat (i.e. not relational) and processed as a whole, then some python-internal data structures might be applicable.
A:
Perhaps AppFabric would work for you?
http://msdn.microsoft.com/en-us/windowsserver/ee695849.aspx
A:
SQLite doesn't allow remote "connections" as far as I know, it only supports being invoked as an in-process library. However, you could try to use MySQL which, while heavier, supports remote connections and does have in-memory tables.
See http://dev.mysql.com/doc/refman/5.5/en/memory-storage-engine.html
|
In memory database with socket capability
|
Python --> SQLite --> ASP.NET C#
I am looking for an in memory database application that does not have to write the data it receives to disc. Basically, I'll be having a Python server which receives gaming UDP data and translates the data and stores it in the memory database engine.
I want to stay away from writing to disc as it takes too long. The data is not important, if something goes wrong, it simply flushes and fills up with the next wave of data sent by players.
Next, another ASP.NET server must be able to connect to this in memory database via TCP/IP at regular intervals, say once every second, or 10 seconds. It has to pull this data, and this will in turn update on a website that displays "live" game data.
I'm looking at SQlite, and wondering, is this the right tool for the job, anyone have any suggestions?
Thanks!!!
|
[
"Totally not my field, but I think Redis is along these lines.\n",
"This sounds like a premature optimization (apologizes if you've already done the profiling). What I would suggest is go ahead and write the system in the simplest, cleanest way, but put a bit of abstraction around the database bits so they can easily by swapped out. Then profile it and find your bottleneck.\nIf it turns out it is the database, optimize the database in the usual way (indexes, query optimizations, etc...). If its still too slow, most databases support an in-memory table format. Or you can mount a RAM disk and mount individual tables or the whole database on it.\n",
"The application of SQlite depends on your data complexity. \nIf you need to perform complex queries on relational data, then it might be a viable option. If your data is flat (i.e. not relational) and processed as a whole, then some python-internal data structures might be applicable.\n",
"Perhaps AppFabric would work for you?\nhttp://msdn.microsoft.com/en-us/windowsserver/ee695849.aspx\n",
"SQLite doesn't allow remote \"connections\" as far as I know, it only supports being invoked as an in-process library. However, you could try to use MySQL which, while heavier, supports remote connections and does have in-memory tables.\nSee http://dev.mysql.com/doc/refman/5.5/en/memory-storage-engine.html\n"
] |
[
1,
1,
0,
0,
0
] |
[] |
[] |
[
"asp.net",
"networking",
"python",
"sqlite",
"udp"
] |
stackoverflow_0001962130_asp.net_networking_python_sqlite_udp.txt
|
Q:
Is RLock a sensible default over Lock?
the threading module in Python provides two kinds of locks: A common lock and a reentrant lock. It seems to me, that if I need a lock, I should always prefer the RLock over the Lock; mainly to prevent deadlock situations.
Besides that, I see two points, when to prefer a Lock over a RLock:
RLock has a more complicated internal structure and may therefore have worse performance.
Due to some reason, I want to prevent a thread recursing through the lock.
Is my reasoning correct? Can you point out other aspects?
A:
Two points:
In officially released Python versions (2.4, 2.5... up to 3.1), an RLock is much slower than a Lock, because Locks are implemented in C and RLocks in Python (this will change in 3.2)
A Lock can be released from any thread (not necessarily the thread which acquire()d it), while an RLock has to be released by the same thread which acquired it
Bottom line, I'd suggest to only use an RLock if it matches the semantics you are looking for, otherwise stick to Locks by default.
A:
Normally you should structure your code such that you never need to recursively lock in normal operation (basically it forces you to use locks tightly around the protected datastructures they are are protecting). Therefore you want to catch an anomalous recursive locking.
|
Is RLock a sensible default over Lock?
|
the threading module in Python provides two kinds of locks: A common lock and a reentrant lock. It seems to me, that if I need a lock, I should always prefer the RLock over the Lock; mainly to prevent deadlock situations.
Besides that, I see two points, when to prefer a Lock over a RLock:
RLock has a more complicated internal structure and may therefore have worse performance.
Due to some reason, I want to prevent a thread recursing through the lock.
Is my reasoning correct? Can you point out other aspects?
|
[
"Two points:\n\nIn officially released Python versions (2.4, 2.5... up to 3.1), an RLock is much slower than a Lock, because Locks are implemented in C and RLocks in Python (this will change in 3.2)\nA Lock can be released from any thread (not necessarily the thread which acquire()d it), while an RLock has to be released by the same thread which acquired it\n\nBottom line, I'd suggest to only use an RLock if it matches the semantics you are looking for, otherwise stick to Locks by default.\n",
"Normally you should structure your code such that you never need to recursively lock in normal operation (basically it forces you to use locks tightly around the protected datastructures they are are protecting). Therefore you want to catch an anomalous recursive locking. \n"
] |
[
10,
3
] |
[] |
[] |
[
"multithreading",
"python"
] |
stackoverflow_0001822541_multithreading_python.txt
|
Q:
Python performance characteristics
I'm in the process of tuning a pet project of mine to improve its performance. I've already busted out the profiler to identify hotspots but I'm thinking understanding Pythons performance characteristics a little better would be quite useful going forward.
There are a few things I'd like to know:
How smart is its optimizer?
Some modern compilers have been blessed with remarkably clever optimisers, that can often take simple code and make it run faster than any human attempts at tuning the code. Depending on how smart the optimizer is, it may be far better for my code to be 'dumb'.
While Python is an 'interpreted' language, it does appear to compile down to some form of bytecode (.pyc). How smart is it when it does this?
Will it fold constants?
Will it inline small functions or unroll short loops?
Will it perform complex data/flow analysis I'm not qualified to explain properly.
How fast are the following operations (comparatively)
Function calls
Class instantiation
Arithmetic
'Heavier' math operations such as sqrt()
How are numbers handled internally?
How are numbers stored within Python. Are they stored as integers / floats internally or moved around as a string?
NumPy
How much of a performance difference can NumPy make? This application makes heavy use of Vectors and related mathematics. How much of a difference can be made by using this to accelerate these operations.
Anything else interesting
If you can think of anything else worth knowing, feel free to mention it.
Some background...
Since there are a few people bringing in the 'look at your algorithms first' advice (which is quite sensible advice, but doesn't really help with my purpose in asking this question) I'll add a bit here about whats going on, and why I'm asking about this.
The pet project in question is a ray-tracer written in Python. It's not yet very far along and currently just hit tests against two objects (a triangle and a sphere) within the scene. No shading, shadowing or lighting calculations are being performed. The algorithm is basically:
for each x, y position in the image:
create a ray
hit test vs. sphere
hit test vs. triangle
colour the pixel based on the closest object, or black if no hit.
Algorithmic refinements in ray-tracing generally work by eliminating objects in the scene early. They can provide a considerable boost for complex scenes, but if this ray-tracer can't hit test against a mere two objects without struggling, then it's not going to be able to handle very much at all.
While I realise that a Python based ray-tracer won't quite be able to reach the performance of a C based one, given that real-time ray tracers like Arauna can manage 15-20 FPS on my computer rendering reasonably complex scenes at 640x480, I'd expect rendering a very basic 500x500 image in Python to be doable in under a second.
Currently, my code is taking 38 seconds. It seems to me like it really shouldn't take that long.
Profiling shows the bulk of the time being spent in the actual hit testing routines for these shapes. This isn't particularly surprising in a ray tracer, and what I expected. The call-counts for these hit tests are each 250,000 (500x500 exactly), which would indicate they're being called exactly as often as they should be. This is a a pretty text-book case of the 3% where optimization is advisable.
I'm planning on doing the full timing / measuring thing as I work on improving the code. However, without some basic knowledge of what costs what in Python my attempts to tune my code would be little more than stumbling in the dark. I figured it would serve me well to gain a little knowledge to light the way.
A:
Python's compiler is deliberately dirt-simple -- this makes it fast and highly predictable. Apart from some constant folding, it basically generates bytecode that faithfully mimics your sources. Somebody else already suggested dis, and it's indeed a good way to look at the bytecode you're getting -- for example, how for i in [1, 2, 3]: isn't actually doing constant folding but generating the literal list on the fly, while for i in (1, 2, 3): (looping on a literal tuple instead of a literal list) is able to constant-fold (reason: a list is a mutable object, and to keep to the "dirt-simple" mission statement the compiler doesn't bother to check that this specific list is never modified so it could be optimized into a tuple).
So there's space for ample manual micro-optimization -- hoisting, in particular. I.e., rewrite
for x in whatever():
anobj.amethod(x)
as
f = anobj.amethod
for x in whatever():
f(x)
to save the repeated lookups (the compiler doesn't check whether a run of anobj.amethod can actually change anobj's bindings &c so that a fresh lookup is needed next time -- it just does the dirt-simple thing, i.e., no hoisting, which guarantees correctness but definitely doesn't guarantee blazing speed;-).
The timeit module (best used at a shell prompt IMHO) makes it very simple to measure the overall effects of compilation + bytecode interpretation (just ensure the snippet you're measuring has no side effects that would affect the timing, since timeit does run it over and over in a loop;-). For example:
$ python -mtimeit 'for x in (1, 2, 3): pass'
1000000 loops, best of 3: 0.219 usec per loop
$ python -mtimeit 'for x in [1, 2, 3]: pass'
1000000 loops, best of 3: 0.512 usec per loop
you can see the costs of the repeated list construction -- and confirm that is indeed what we're observing by trying a minor tweak:
$ python -mtimeit -s'Xs=[1,2,3]' 'for x in Xs: pass'
1000000 loops, best of 3: 0.236 usec per loop
$ python -mtimeit -s'Xs=(1,2,3)' 'for x in Xs: pass'
1000000 loops, best of 3: 0.213 usec per loop
moving the iterable's construction to the -s setup (which is run only once and not timed) shows that the looping proper is slightly faster on tuples (maybe 10%), but the big issue with the first pair (list slower than tuple by over 100%) is mostly with the construction.
Armed with timeit and the knowledge that the compiler's deliberately very simple minded in its optimizations, we can easily answer other questions of yours:
How fast are the following operations
(comparatively)
* Function calls
* Class instantiation
* Arithmetic
* 'Heavier' math operations such as sqrt()
$ python -mtimeit -s'def f(): pass' 'f()'
10000000 loops, best of 3: 0.192 usec per loop
$ python -mtimeit -s'class o: pass' 'o()'
1000000 loops, best of 3: 0.315 usec per loop
$ python -mtimeit -s'class n(object): pass' 'n()'
10000000 loops, best of 3: 0.18 usec per loop
so we see: instantiating a new-style class and calling a function (both empty) are about the same speed, with instantiations possibly having a tiny speed margin, maybe 5%; instantiating an old-style class is slowest (by about 50%). Tiny differences such as 5% or less of course could be noise, so repeating each try a few times is advisable; but differences like 50% are definitely well beyond noise.
$ python -mtimeit -s'from math import sqrt' 'sqrt(1.2)'
1000000 loops, best of 3: 0.22 usec per loop
$ python -mtimeit '1.2**0.5'
10000000 loops, best of 3: 0.0363 usec per loop
$ python -mtimeit '1.2*0.5'
10000000 loops, best of 3: 0.0407 usec per loop
and here we see: calling sqrt is slower than doing the same computation by operator (using the ** raise-to-power operator) by roughly the cost of calling an empty function; all arithmetic operators are roughly the same speed to within noise (the tiny difference of 3 or 4 nanoseconds is definitely noise;-). Checking whether constant folding might interfere:
$ python -mtimeit '1.2*0.5'
10000000 loops, best of 3: 0.0407 usec per loop
$ python -mtimeit -s'a=1.2; b=0.5' 'a*b'
10000000 loops, best of 3: 0.0965 usec per loop
$ python -mtimeit -s'a=1.2; b=0.5' 'a*0.5'
10000000 loops, best of 3: 0.0957 usec per loop
$ python -mtimeit -s'a=1.2; b=0.5' '1.2*b'
10000000 loops, best of 3: 0.0932 usec per loop
...we see that this is indeed the case: if either or both numbers are being looked up as variables (which blocks constant folding), we're paying the "realistic" cost. Variable lookup has its own cost:
$ python -mtimeit -s'a=1.2; b=0.5' 'a'
10000000 loops, best of 3: 0.039 usec per loop
and that's far from negligible when we're trying to measure such tiny times anyway. Indeed constant lookup isn't free either:
$ python -mtimeit -s'a=1.2; b=0.5' '1.2'
10000000 loops, best of 3: 0.0225 usec per loop
as you see, while smaller than variable lookup it's quite comparable -- about half.
If and when (armed with careful profiling and measurement) you decide some nucleus of your computations desperately need optimization, I recommend trying cython -- it's a C / Python merge which tries to be as neat as Python and as fast as C, and while it can't get there 100% it surely makes a good fist of it (in particular, it makes binary code that's quite a bit faster than you can get with its predecessor language, pyrex, as well as being a bit richer than it). For the last few %'s of performance you probably still want to go down to C (or assembly / machine code in some exceptional cases), but that would be really, really rare.
A:
S.Lott is right: the big effects are data structures and algorithms. Also, if you are doing a lot of I/O, how you manage it will make a big difference.
But if you are curious about the compiler internals: it will fold constants, but it will not inline functions or unroll loops. Inlining functions is a hard problem in a dynamic language.
You can see what the compiler does by disassembling some compiled code. Put some sample code in my_file.py, then use:
python -m dis my_file.py
This source:
def foo():
return "BAR!"
for i in [1,2,3]:
print i, foo()
produces:
1 0 LOAD_CONST 0 (<code object foo at 01A0B380, file "\foo\bar.py", line 1>)
3 MAKE_FUNCTION 0
6 STORE_NAME 0 (foo)
4 9 SETUP_LOOP 35 (to 47)
12 LOAD_CONST 1 (1)
15 LOAD_CONST 2 (2)
18 LOAD_CONST 3 (3)
21 BUILD_LIST 3
24 GET_ITER
>> 25 FOR_ITER 18 (to 46)
28 STORE_NAME 1 (i)
5 31 LOAD_NAME 1 (i)
34 PRINT_ITEM
35 LOAD_NAME 0 (foo)
38 CALL_FUNCTION 0
41 PRINT_ITEM
42 PRINT_NEWLINE
43 JUMP_ABSOLUTE 25
>> 46 POP_BLOCK
>> 47 LOAD_CONST 4 (None)
50 RETURN_VALUE
Notice that only the top-level code in the module is disassembled, you need to write a little more code yourself to recurse through the nested code objects if you want to see the function definitions disassembled as well.
A:
The speed of your code might be automatically improved by using the Psyco module.
As for Numpy, it generally speeds things up by a significant factor. I consider it a must when manipulating numerical arrays.
You might also want to speed up the critical parts of your code with Cython or Pyrex, which allow you to create faster extension modules without having to write a full-fledged extension module in C (which would be more cumbersome).
A:
Here's what's interesting.
Data Structure
Algorithm
Those will yield dramatic improvements.
Your list is good for -- at best -- a few single-digit performance improvements.
You need to fundamentally rethink your data structures if you want to see real speed improvements.
A:
If you already know that your algorithm is as fast as possible, and you know that C would be much faster, then you may want to implement the core of your code in C as a C extension to Python. You can pragmatically decide which part of the code goes in C and which is in Python, using each language to its full potential.
Unlike some other languages, calling between C and Python is very fast, so there's no penalty for crossing the border often.
A:
I'm the author of Arauna. I know nothing about Python, but I do know that Arauna is extremely optimized, both high level (data structures & algorithms) and low-level (cache friendly code, SIMD, multithreading). It's a hard target to go for...
|
Python performance characteristics
|
I'm in the process of tuning a pet project of mine to improve its performance. I've already busted out the profiler to identify hotspots but I'm thinking understanding Pythons performance characteristics a little better would be quite useful going forward.
There are a few things I'd like to know:
How smart is its optimizer?
Some modern compilers have been blessed with remarkably clever optimisers, that can often take simple code and make it run faster than any human attempts at tuning the code. Depending on how smart the optimizer is, it may be far better for my code to be 'dumb'.
While Python is an 'interpreted' language, it does appear to compile down to some form of bytecode (.pyc). How smart is it when it does this?
Will it fold constants?
Will it inline small functions or unroll short loops?
Will it perform complex data/flow analysis I'm not qualified to explain properly.
How fast are the following operations (comparatively)
Function calls
Class instantiation
Arithmetic
'Heavier' math operations such as sqrt()
How are numbers handled internally?
How are numbers stored within Python. Are they stored as integers / floats internally or moved around as a string?
NumPy
How much of a performance difference can NumPy make? This application makes heavy use of Vectors and related mathematics. How much of a difference can be made by using this to accelerate these operations.
Anything else interesting
If you can think of anything else worth knowing, feel free to mention it.
Some background...
Since there are a few people bringing in the 'look at your algorithms first' advice (which is quite sensible advice, but doesn't really help with my purpose in asking this question) I'll add a bit here about whats going on, and why I'm asking about this.
The pet project in question is a ray-tracer written in Python. It's not yet very far along and currently just hit tests against two objects (a triangle and a sphere) within the scene. No shading, shadowing or lighting calculations are being performed. The algorithm is basically:
for each x, y position in the image:
create a ray
hit test vs. sphere
hit test vs. triangle
colour the pixel based on the closest object, or black if no hit.
Algorithmic refinements in ray-tracing generally work by eliminating objects in the scene early. They can provide a considerable boost for complex scenes, but if this ray-tracer can't hit test against a mere two objects without struggling, then it's not going to be able to handle very much at all.
While I realise that a Python based ray-tracer won't quite be able to reach the performance of a C based one, given that real-time ray tracers like Arauna can manage 15-20 FPS on my computer rendering reasonably complex scenes at 640x480, I'd expect rendering a very basic 500x500 image in Python to be doable in under a second.
Currently, my code is taking 38 seconds. It seems to me like it really shouldn't take that long.
Profiling shows the bulk of the time being spent in the actual hit testing routines for these shapes. This isn't particularly surprising in a ray tracer, and what I expected. The call-counts for these hit tests are each 250,000 (500x500 exactly), which would indicate they're being called exactly as often as they should be. This is a a pretty text-book case of the 3% where optimization is advisable.
I'm planning on doing the full timing / measuring thing as I work on improving the code. However, without some basic knowledge of what costs what in Python my attempts to tune my code would be little more than stumbling in the dark. I figured it would serve me well to gain a little knowledge to light the way.
|
[
"Python's compiler is deliberately dirt-simple -- this makes it fast and highly predictable. Apart from some constant folding, it basically generates bytecode that faithfully mimics your sources. Somebody else already suggested dis, and it's indeed a good way to look at the bytecode you're getting -- for example, how for i in [1, 2, 3]: isn't actually doing constant folding but generating the literal list on the fly, while for i in (1, 2, 3): (looping on a literal tuple instead of a literal list) is able to constant-fold (reason: a list is a mutable object, and to keep to the \"dirt-simple\" mission statement the compiler doesn't bother to check that this specific list is never modified so it could be optimized into a tuple).\nSo there's space for ample manual micro-optimization -- hoisting, in particular. I.e., rewrite\nfor x in whatever():\n anobj.amethod(x)\n\nas\nf = anobj.amethod\nfor x in whatever():\n f(x)\n\nto save the repeated lookups (the compiler doesn't check whether a run of anobj.amethod can actually change anobj's bindings &c so that a fresh lookup is needed next time -- it just does the dirt-simple thing, i.e., no hoisting, which guarantees correctness but definitely doesn't guarantee blazing speed;-).\nThe timeit module (best used at a shell prompt IMHO) makes it very simple to measure the overall effects of compilation + bytecode interpretation (just ensure the snippet you're measuring has no side effects that would affect the timing, since timeit does run it over and over in a loop;-). For example:\n$ python -mtimeit 'for x in (1, 2, 3): pass'\n1000000 loops, best of 3: 0.219 usec per loop\n$ python -mtimeit 'for x in [1, 2, 3]: pass'\n1000000 loops, best of 3: 0.512 usec per loop\n\nyou can see the costs of the repeated list construction -- and confirm that is indeed what we're observing by trying a minor tweak:\n$ python -mtimeit -s'Xs=[1,2,3]' 'for x in Xs: pass'\n1000000 loops, best of 3: 0.236 usec per loop\n$ python -mtimeit -s'Xs=(1,2,3)' 'for x in Xs: pass'\n1000000 loops, best of 3: 0.213 usec per loop\n\nmoving the iterable's construction to the -s setup (which is run only once and not timed) shows that the looping proper is slightly faster on tuples (maybe 10%), but the big issue with the first pair (list slower than tuple by over 100%) is mostly with the construction.\nArmed with timeit and the knowledge that the compiler's deliberately very simple minded in its optimizations, we can easily answer other questions of yours:\n\nHow fast are the following operations\n (comparatively)\n* Function calls\n* Class instantiation\n* Arithmetic\n* 'Heavier' math operations such as sqrt()\n\n\n$ python -mtimeit -s'def f(): pass' 'f()'\n10000000 loops, best of 3: 0.192 usec per loop\n$ python -mtimeit -s'class o: pass' 'o()'\n1000000 loops, best of 3: 0.315 usec per loop\n$ python -mtimeit -s'class n(object): pass' 'n()'\n10000000 loops, best of 3: 0.18 usec per loop\n\nso we see: instantiating a new-style class and calling a function (both empty) are about the same speed, with instantiations possibly having a tiny speed margin, maybe 5%; instantiating an old-style class is slowest (by about 50%). Tiny differences such as 5% or less of course could be noise, so repeating each try a few times is advisable; but differences like 50% are definitely well beyond noise.\n$ python -mtimeit -s'from math import sqrt' 'sqrt(1.2)'\n1000000 loops, best of 3: 0.22 usec per loop\n$ python -mtimeit '1.2**0.5'\n10000000 loops, best of 3: 0.0363 usec per loop\n$ python -mtimeit '1.2*0.5'\n10000000 loops, best of 3: 0.0407 usec per loop\n\nand here we see: calling sqrt is slower than doing the same computation by operator (using the ** raise-to-power operator) by roughly the cost of calling an empty function; all arithmetic operators are roughly the same speed to within noise (the tiny difference of 3 or 4 nanoseconds is definitely noise;-). Checking whether constant folding might interfere:\n$ python -mtimeit '1.2*0.5'\n10000000 loops, best of 3: 0.0407 usec per loop\n$ python -mtimeit -s'a=1.2; b=0.5' 'a*b'\n10000000 loops, best of 3: 0.0965 usec per loop\n$ python -mtimeit -s'a=1.2; b=0.5' 'a*0.5'\n10000000 loops, best of 3: 0.0957 usec per loop\n$ python -mtimeit -s'a=1.2; b=0.5' '1.2*b'\n10000000 loops, best of 3: 0.0932 usec per loop\n\n...we see that this is indeed the case: if either or both numbers are being looked up as variables (which blocks constant folding), we're paying the \"realistic\" cost. Variable lookup has its own cost:\n$ python -mtimeit -s'a=1.2; b=0.5' 'a'\n10000000 loops, best of 3: 0.039 usec per loop\n\nand that's far from negligible when we're trying to measure such tiny times anyway. Indeed constant lookup isn't free either:\n$ python -mtimeit -s'a=1.2; b=0.5' '1.2'\n10000000 loops, best of 3: 0.0225 usec per loop\n\nas you see, while smaller than variable lookup it's quite comparable -- about half.\nIf and when (armed with careful profiling and measurement) you decide some nucleus of your computations desperately need optimization, I recommend trying cython -- it's a C / Python merge which tries to be as neat as Python and as fast as C, and while it can't get there 100% it surely makes a good fist of it (in particular, it makes binary code that's quite a bit faster than you can get with its predecessor language, pyrex, as well as being a bit richer than it). For the last few %'s of performance you probably still want to go down to C (or assembly / machine code in some exceptional cases), but that would be really, really rare.\n",
"S.Lott is right: the big effects are data structures and algorithms. Also, if you are doing a lot of I/O, how you manage it will make a big difference.\nBut if you are curious about the compiler internals: it will fold constants, but it will not inline functions or unroll loops. Inlining functions is a hard problem in a dynamic language.\nYou can see what the compiler does by disassembling some compiled code. Put some sample code in my_file.py, then use:\npython -m dis my_file.py\n\nThis source:\ndef foo():\n return \"BAR!\"\n\nfor i in [1,2,3]:\n print i, foo()\n\nproduces:\n 1 0 LOAD_CONST 0 (<code object foo at 01A0B380, file \"\\foo\\bar.py\", line 1>)\n 3 MAKE_FUNCTION 0\n 6 STORE_NAME 0 (foo)\n\n 4 9 SETUP_LOOP 35 (to 47)\n 12 LOAD_CONST 1 (1)\n 15 LOAD_CONST 2 (2)\n 18 LOAD_CONST 3 (3)\n 21 BUILD_LIST 3\n 24 GET_ITER\n >> 25 FOR_ITER 18 (to 46)\n 28 STORE_NAME 1 (i)\n\n 5 31 LOAD_NAME 1 (i)\n 34 PRINT_ITEM\n 35 LOAD_NAME 0 (foo)\n 38 CALL_FUNCTION 0\n 41 PRINT_ITEM\n 42 PRINT_NEWLINE\n 43 JUMP_ABSOLUTE 25\n >> 46 POP_BLOCK\n >> 47 LOAD_CONST 4 (None)\n 50 RETURN_VALUE\n\nNotice that only the top-level code in the module is disassembled, you need to write a little more code yourself to recurse through the nested code objects if you want to see the function definitions disassembled as well.\n",
"The speed of your code might be automatically improved by using the Psyco module.\nAs for Numpy, it generally speeds things up by a significant factor. I consider it a must when manipulating numerical arrays.\nYou might also want to speed up the critical parts of your code with Cython or Pyrex, which allow you to create faster extension modules without having to write a full-fledged extension module in C (which would be more cumbersome).\n",
"Here's what's interesting.\n\nData Structure\nAlgorithm\n\nThose will yield dramatic improvements. \nYour list is good for -- at best -- a few single-digit performance improvements.\nYou need to fundamentally rethink your data structures if you want to see real speed improvements.\n",
"If you already know that your algorithm is as fast as possible, and you know that C would be much faster, then you may want to implement the core of your code in C as a C extension to Python. You can pragmatically decide which part of the code goes in C and which is in Python, using each language to its full potential.\nUnlike some other languages, calling between C and Python is very fast, so there's no penalty for crossing the border often.\n",
"I'm the author of Arauna. I know nothing about Python, but I do know that Arauna is extremely optimized, both high level (data structures & algorithms) and low-level (cache friendly code, SIMD, multithreading). It's a hard target to go for...\n"
] |
[
24,
6,
6,
4,
4,
4
] |
[] |
[] |
[
"performance",
"python"
] |
stackoverflow_0001913906_performance_python.txt
|
Q:
Separate logger name for each application instance
My python application consists of main program and several modules. Each module contains
import logging
log = logging.getLogger('myapp.mymodule')
on global level. Handlers and other stuff initialized in main program, and typically all messages forwarded to syslog.
Now I want to launch multiple instances of application (configuration file with instance name can be specified as command line parameter). The question is: how to pass instance name to each imported module? I want logger name to look like 'myappinstance.mymodule' or 'myapp.instance.module'. And I do not want to mess with configuration file parsing in each module, because this will require hardcoded config path.
A:
Here is a solution I can think of:
In the main program, set the formatter of logger named myapp
import logging
logger = logging.getLogger("myapp")
formatter = logging.Formatter("%(asctime)s - instance_name - %(levelname)s - %(message)s")
ch = logging.SysLogHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)
Then all imported module using logger myapp.* will contain instance_name in the logging message.
A:
Well, describing the problem really helps in solving it :) Just had an idea of using environment variables to pass parameters across all modules:
main.py:
import os
os.environ['instance'] = 'blah'
import a
a.py:
import os
import b
print 'a:', os.environ['instance']
b.py:
import os
print 'b:', os.environ['instance']
$ python main.py
b: blah
a: blah
Any other ideas or critics for this one?
A:
Simply write your own logging wrapper which will give you the correct name (tweak as needed to get the instance name that you want):
def get_logger(obj=None):
if isinstance(obj, str):
return logging.getLogger(obj)
elif obj is not None:
logger_name ="%s.%s" % (obj.__class__.__module__, obj.__class__.__name__)
return logging.getLogger(logger_name)
else:
return logging.getLogger()
class Foo(object):
def __init__(self):
self._log = get_logger(self)
Or, if the process id is good enough for you, simply use that in your formatter:
http://www.python.org/doc/2.5.4/lib/node421.html
formatter = logging.Formatter("%(process)d - %(asctime)s - %(levelname)s - %(message)s")
Obviously, that will uniquely identify each process, but won't give you anything related to the instance.
|
Separate logger name for each application instance
|
My python application consists of main program and several modules. Each module contains
import logging
log = logging.getLogger('myapp.mymodule')
on global level. Handlers and other stuff initialized in main program, and typically all messages forwarded to syslog.
Now I want to launch multiple instances of application (configuration file with instance name can be specified as command line parameter). The question is: how to pass instance name to each imported module? I want logger name to look like 'myappinstance.mymodule' or 'myapp.instance.module'. And I do not want to mess with configuration file parsing in each module, because this will require hardcoded config path.
|
[
"Here is a solution I can think of:\nIn the main program, set the formatter of logger named myapp\nimport logging\nlogger = logging.getLogger(\"myapp\")\nformatter = logging.Formatter(\"%(asctime)s - instance_name - %(levelname)s - %(message)s\")\nch = logging.SysLogHandler()\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\nThen all imported module using logger myapp.* will contain instance_name in the logging message.\n",
"Well, describing the problem really helps in solving it :) Just had an idea of using environment variables to pass parameters across all modules:\nmain.py:\nimport os\nos.environ['instance'] = 'blah'\nimport a\n\na.py:\nimport os\nimport b\nprint 'a:', os.environ['instance']\n\nb.py:\nimport os\nprint 'b:', os.environ['instance']\n\n$ python main.py\nb: blah\na: blah\n\nAny other ideas or critics for this one?\n",
"Simply write your own logging wrapper which will give you the correct name (tweak as needed to get the instance name that you want):\ndef get_logger(obj=None):\n if isinstance(obj, str):\n return logging.getLogger(obj) \n elif obj is not None:\n logger_name =\"%s.%s\" % (obj.__class__.__module__, obj.__class__.__name__)\n return logging.getLogger(logger_name)\n else:\n return logging.getLogger()\n\nclass Foo(object):\n\n def __init__(self):\n self._log = get_logger(self)\n\nOr, if the process id is good enough for you, simply use that in your formatter:\nhttp://www.python.org/doc/2.5.4/lib/node421.html\nformatter = logging.Formatter(\"%(process)d - %(asctime)s - %(levelname)s - %(message)s\")\n\nObviously, that will uniquely identify each process, but won't give you anything related to the instance.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"logging",
"python"
] |
stackoverflow_0001975823_logging_python.txt
|
Q:
2 dimensional interpolation problem
I have DATA on x and y axes and the output is on z
for example
y = 10
x = [1,2,3,4,5,6]
z = [2.3,3.4,5.6,7.8,9.6,11.2]
y = 20
x = [1,2,3,4,5,6]
z = [4.3,5.4,7.6,9.8,11.6,13.2]
y = 30
x = [1,2,3,4,5,6]
z = [6.3,7.4,8.6,10.8,13.6,15.2]
how can i find the value of z when y = 15 x = 3.5
I was trying to use scipy but i am very new at it
Thanks a lot for the help
vibhor
A:
scipy.interpolate.bisplrep
Reference:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html
import scipy
import math
import numpy
from scipy import interpolate
x= [1,2,3,4,5,6]
y= [10,20,30]
Y = numpy.array([[i]*len(x) for i in y])
X = numpy.array([x for i in y])
Z = numpy.array([[2.3,3.4,5.6,7.8,9.6,11.2],
[4.3,5.4,7.6,9.8,11.6,13.2],
[6.3,7.4,8.6,10.8,13.6,15.2]])
tck = interpolate.bisplrep(X,Y,Z)
print interpolate.bisplev(3.5,15,tck)
7.84921875
EDIT:
Upper solution does not give you perfect fit.
check
print interpolate.bisplev(x,y,tck)
[[ 2.2531746 4.2531746 6.39603175]
[ 3.54126984 5.54126984 7.11269841]
[ 5.5031746 7.5031746 8.78888889]
[ 7.71111111 9.71111111 10.9968254 ]
[ 9.73730159 11.73730159 13.30873016]
[ 11.15396825 13.15396825 15.2968254 ]]
to overcome this interpolate whit polyinomials of 5rd degree in x and 2nd degree in y direction
tck = interpolate.bisplrep(X,Y,Z,kx=5,ky=2)
print interpolate.bisplev(x,y,tck)
[[ 2.3 4.3 6.3]
[ 3.4 5.4 7.4]
[ 5.6 7.6 8.6]
[ 7.8 9.8 10.8]
[ 9.6 11.6 13.6]
[ 11.2 13.2 15.2]]
This yield
print interpolate.bisplev(3.5,15,tck)
7.88671875
Plotting:
reference http://matplotlib.sourceforge.net/examples/mplot3d/surface3d_demo.html
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(X, Y, Z,rstride=1, cstride=1, cmap=cm.jet)
plt.show()
A:
Given (not as Python code, since the second assignment would obliterate the first in each case, of course;-):
y = 10
x = [1,2,3,4,5,6]
z = [2.3,3.4,5.6,7.8,9.6,11.2]
y = 20
x = [1,2,3,4,5,6]
z = [4.3,5.4,7.6,9.8,11.6,13.2]
you ask: "how can i find the value of z when y = 15 x = 3.5"?
Since you're looking at a point exactly equidistant in both x and y from the given "grid", you just take the midpoint between the grid values (if you had values not equidistant, you'd take a proportional midpoint, see later). So for y=10, the z values for x 3 and 4 are 5.6 and 7.8, so for x 3.5 you estimate their midpoint, 6.7; and similarly for y=20 you estimate the midpoint between 7.6 and 9.8, i.e., 8.7. Finally, since you have y=15, the midpoint between 6.7 and 8.7 is your final interpolated value for z: 7.7.
Say you had y=13 and x=3.8 instead. Then for x you'd take the values 80% of the way, i.e.:
for y=10, 0.2*5.6+0.8*7.8 -> 7.36
for y=20, 0.2*7.6+0.8*9.8 -> 9.46
Now you want the z 30% of the way between these, 0.3*7.36 + 0.7*9.46 -> 8.83, that's z.
This is linear interpolation, and it's really very simple. Do you want to compute it by hand, or find routines that do it for you (given e.g. numpy arrays as "the grids")? Even in the latter case, I hope this "manual" explanation (showing what you're doing in the most elementary of arithmetical terms) can help you understand what you're doing...;-).
There are more advanced forms of interpolation, of course -- do you need those, or does linear interpolation suffice for your use case?
A:
I would say just take the average of the values around it. So if you need X=3.5 and Y=15 (3.5,15), you average (3,10), (3,20), (4,10) and (4,20). Since I have no idea what the data is you are dealing with, I am not sure if the exact proximity would matter - in which case you can just stick w/the average - or if you need to do some sort of inverse distance weighting.
|
2 dimensional interpolation problem
|
I have DATA on x and y axes and the output is on z
for example
y = 10
x = [1,2,3,4,5,6]
z = [2.3,3.4,5.6,7.8,9.6,11.2]
y = 20
x = [1,2,3,4,5,6]
z = [4.3,5.4,7.6,9.8,11.6,13.2]
y = 30
x = [1,2,3,4,5,6]
z = [6.3,7.4,8.6,10.8,13.6,15.2]
how can i find the value of z when y = 15 x = 3.5
I was trying to use scipy but i am very new at it
Thanks a lot for the help
vibhor
|
[
"scipy.interpolate.bisplrep\nReference:\nhttp://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.bisplrep.html\nimport scipy\nimport math\nimport numpy\nfrom scipy import interpolate\n\n\nx= [1,2,3,4,5,6]\ny= [10,20,30]\n\nY = numpy.array([[i]*len(x) for i in y])\nX = numpy.array([x for i in y])\nZ = numpy.array([[2.3,3.4,5.6,7.8,9.6,11.2],\n [4.3,5.4,7.6,9.8,11.6,13.2],\n [6.3,7.4,8.6,10.8,13.6,15.2]]) \n\ntck = interpolate.bisplrep(X,Y,Z)\nprint interpolate.bisplev(3.5,15,tck) \n\n\n7.84921875\n\nEDIT:\nUpper solution does not give you perfect fit. \ncheck \nprint interpolate.bisplev(x,y,tck)\n\n[[ 2.2531746 4.2531746 6.39603175]\n [ 3.54126984 5.54126984 7.11269841]\n [ 5.5031746 7.5031746 8.78888889]\n [ 7.71111111 9.71111111 10.9968254 ]\n [ 9.73730159 11.73730159 13.30873016]\n [ 11.15396825 13.15396825 15.2968254 ]]\n\nto overcome this interpolate whit polyinomials of 5rd degree in x and 2nd degree in y direction \ntck = interpolate.bisplrep(X,Y,Z,kx=5,ky=2)\nprint interpolate.bisplev(x,y,tck) \n\n[[ 2.3 4.3 6.3]\n [ 3.4 5.4 7.4]\n [ 5.6 7.6 8.6]\n [ 7.8 9.8 10.8]\n [ 9.6 11.6 13.6]\n [ 11.2 13.2 15.2]]\n\nThis yield \nprint interpolate.bisplev(3.5,15,tck)\n\n7.88671875\n\nPlotting:\nreference http://matplotlib.sourceforge.net/examples/mplot3d/surface3d_demo.html\nfig = plt.figure()\nax = Axes3D(fig)\nax.plot_surface(X, Y, Z,rstride=1, cstride=1, cmap=cm.jet)\nplt.show()\n\n",
"Given (not as Python code, since the second assignment would obliterate the first in each case, of course;-):\ny = 10\nx = [1,2,3,4,5,6]\nz = [2.3,3.4,5.6,7.8,9.6,11.2]\n\ny = 20 \nx = [1,2,3,4,5,6]\nz = [4.3,5.4,7.6,9.8,11.6,13.2]\n\nyou ask: \"how can i find the value of z when y = 15 x = 3.5\"?\nSince you're looking at a point exactly equidistant in both x and y from the given \"grid\", you just take the midpoint between the grid values (if you had values not equidistant, you'd take a proportional midpoint, see later). So for y=10, the z values for x 3 and 4 are 5.6 and 7.8, so for x 3.5 you estimate their midpoint, 6.7; and similarly for y=20 you estimate the midpoint between 7.6 and 9.8, i.e., 8.7. Finally, since you have y=15, the midpoint between 6.7 and 8.7 is your final interpolated value for z: 7.7.\nSay you had y=13 and x=3.8 instead. Then for x you'd take the values 80% of the way, i.e.:\n\nfor y=10, 0.2*5.6+0.8*7.8 -> 7.36\nfor y=20, 0.2*7.6+0.8*9.8 -> 9.46\n\nNow you want the z 30% of the way between these, 0.3*7.36 + 0.7*9.46 -> 8.83, that's z.\nThis is linear interpolation, and it's really very simple. Do you want to compute it by hand, or find routines that do it for you (given e.g. numpy arrays as \"the grids\")? Even in the latter case, I hope this \"manual\" explanation (showing what you're doing in the most elementary of arithmetical terms) can help you understand what you're doing...;-).\nThere are more advanced forms of interpolation, of course -- do you need those, or does linear interpolation suffice for your use case?\n",
"I would say just take the average of the values around it. So if you need X=3.5 and Y=15 (3.5,15), you average (3,10), (3,20), (4,10) and (4,20). Since I have no idea what the data is you are dealing with, I am not sure if the exact proximity would matter - in which case you can just stick w/the average - or if you need to do some sort of inverse distance weighting.\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"python",
"scipy"
] |
stackoverflow_0001977467_python_scipy.txt
|
Q:
Does Paramiko support non-secure telnet and ftp instead of just SSH and SFTP?
I'm looking at existing python code that heavily uses Paramiko to do SSH and FTP. I need to allow the same code to work with some hosts that do not support a secure connection and over which I have no control.
Is there a quick and easy way to do it via Paramiko, or do I need to step back, create some abstraction that supports both paramiko and Python's FTP libraries, and refactor the code to use this abstraction?
A:
No, paramiko has no support for telnet or ftp -- you're indeed better off using a higher-level abstraction and implementing it twice, with paramiko and without it (with the ftplib and telnetlib modules of the Python standard library).
|
Does Paramiko support non-secure telnet and ftp instead of just SSH and SFTP?
|
I'm looking at existing python code that heavily uses Paramiko to do SSH and FTP. I need to allow the same code to work with some hosts that do not support a secure connection and over which I have no control.
Is there a quick and easy way to do it via Paramiko, or do I need to step back, create some abstraction that supports both paramiko and Python's FTP libraries, and refactor the code to use this abstraction?
|
[
"No, paramiko has no support for telnet or ftp -- you're indeed better off using a higher-level abstraction and implementing it twice, with paramiko and without it (with the ftplib and telnetlib modules of the Python standard library).\n"
] |
[
7
] |
[] |
[] |
[
"paramiko",
"python"
] |
stackoverflow_0001977571_paramiko_python.txt
|
Q:
Why doesn't my Django site return a 404 when checked with this URL parser?
Here's a simple python function that checks if a given url is valid:
from httplib import HTTP
from urlparse import urlparse
def checkURL(url):
p = urlparse(url)
h = HTTP(p[1])
h.putrequest('HEAD', p[2])
h.endheaders()
if h.getreply()[0] == 200:
return 1
else: return 0
This works for most sites, but with my Django-based site I get 200 status code even when I enter a url that is clearly wrong. If I view the same page in a browser, I get a 404. For example, the following page gives a 404 in a browser: http://wefoundland.com/GooseBumper
But gives a 200 when checked with this script. Why?
Edit: While mopoke's answer solved the issue from the Django side of things, there was also a bug in the script above:
instead of parsing the url and then using
h.putrequest('HEAD', p[2])
I actually needed to use the url in the request, like so:
h.putrequest('HEAD', url)
that solved the issue.
A:
Although the content says 404, the site is returning 200 OK in the headers:
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 30 Dec 2009 01:38:24 GMT
Content-Type: text/html; charset=utf-8
Connection: close
Make sure your response is using HttpResponseNotFound. e.g.:
return HttpResponseNotFound('<h1>Page not found</h1>')
A:
Your page isn't actually returning a 404 status code:
alex@alex-laptop:~$ curl -I http://wefoundland.com/GooseBumper
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 30 Dec 2009 01:37:41 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
A:
To get a 404 to be returned by your Django view, use HttpResponseNotFound instead of HttpResponse, or pass in 'status=404' to the HttpResponse constructor.
|
Why doesn't my Django site return a 404 when checked with this URL parser?
|
Here's a simple python function that checks if a given url is valid:
from httplib import HTTP
from urlparse import urlparse
def checkURL(url):
p = urlparse(url)
h = HTTP(p[1])
h.putrequest('HEAD', p[2])
h.endheaders()
if h.getreply()[0] == 200:
return 1
else: return 0
This works for most sites, but with my Django-based site I get 200 status code even when I enter a url that is clearly wrong. If I view the same page in a browser, I get a 404. For example, the following page gives a 404 in a browser: http://wefoundland.com/GooseBumper
But gives a 200 when checked with this script. Why?
Edit: While mopoke's answer solved the issue from the Django side of things, there was also a bug in the script above:
instead of parsing the url and then using
h.putrequest('HEAD', p[2])
I actually needed to use the url in the request, like so:
h.putrequest('HEAD', url)
that solved the issue.
|
[
"Although the content says 404, the site is returning 200 OK in the headers:\nHTTP/1.1 200 OK\nServer: nginx\nDate: Wed, 30 Dec 2009 01:38:24 GMT\nContent-Type: text/html; charset=utf-8\nConnection: close\n\nMake sure your response is using HttpResponseNotFound. e.g.:\n return HttpResponseNotFound('<h1>Page not found</h1>')\n\n",
"Your page isn't actually returning a 404 status code:\nalex@alex-laptop:~$ curl -I http://wefoundland.com/GooseBumper\nHTTP/1.1 200 OK\nServer: nginx\nDate: Wed, 30 Dec 2009 01:37:41 GMT\nContent-Type: text/html; charset=utf-8\nTransfer-Encoding: chunked\nConnection: keep-alive\n\n",
"To get a 404 to be returned by your Django view, use HttpResponseNotFound instead of HttpResponse, or pass in 'status=404' to the HttpResponse constructor.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"python",
"web_applications"
] |
stackoverflow_0001977938_django_python_web_applications.txt
|
Q:
what does '__getnewargs__' do in this code
class NavigableString(unicode, PageElement):
def __new__(cls, value):
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):#this line
return (NavigableString.__str__(self),)
A:
Try this:
x = NavigableString('foop')
y = pickle.dumps(x)
z = pickle.loads(y)
print x, z
I.e.: __getnewargs__ tells pickle.dumps to pickle x in such a way that a pickle.loads back from that string will use NavigableString.__new__ with the proper argument.
|
what does '__getnewargs__' do in this code
|
class NavigableString(unicode, PageElement):
def __new__(cls, value):
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):#this line
return (NavigableString.__str__(self),)
|
[
"Try this:\nx = NavigableString('foop')\ny = pickle.dumps(x)\nz = pickle.loads(y)\nprint x, z\n\nI.e.: __getnewargs__ tells pickle.dumps to pickle x in such a way that a pickle.loads back from that string will use NavigableString.__new__ with the proper argument.\n"
] |
[
15
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001978264_python.txt
|
Q:
pip equivalent to "easy_install ."
Simple Question ;)
Is there a way to simply install the package using pip once you build it. Using easy_install I would simply build my package it (python setup.py build), then if I was happy do a easy_install . and this would dump the resulting egg into the right place. How do I do this using pip?
A:
pip install -e . will install from a local source like easy_install . would.
Most of pip's commands and functionality are designed around installing from source repositories or PyPI package listings, or maintaining consistently versioned dependencies though.
If you are going through the steps of building the package yourself, are you sure you don't want to python setup.py install manually after you are satisfied with the build?
|
pip equivalent to "easy_install ."
|
Simple Question ;)
Is there a way to simply install the package using pip once you build it. Using easy_install I would simply build my package it (python setup.py build), then if I was happy do a easy_install . and this would dump the resulting egg into the right place. How do I do this using pip?
|
[
"pip install -e . will install from a local source like easy_install . would.\nMost of pip's commands and functionality are designed around installing from source repositories or PyPI package listings, or maintaining consistently versioned dependencies though.\nIf you are going through the steps of building the package yourself, are you sure you don't want to python setup.py install manually after you are satisfied with the build?\n"
] |
[
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001978220_python.txt
|
Q:
Transforming DTD's with Python
I'm looking for a library to help me parse and transform DTDs using Python. The only thing I have found so far is xmlproc, but that seems ancient and doesn't seem to support serialization of DTDs. There's this for Java but I'd prefer a Python solution.
Edit: by "serialization" of DTDs I mean that ideally I'd like to be able to parse the DTD to some kind of Python structure, operate on that structure and then write out the result back to a DTD.
A:
I don't know of an end-to-end processor for DTDs, but then again I so rarely use DTDs at all so that's not surprising.
Amara can parse DTDs, but I don't know what level of access you can have to them or if the results can be serialized. I assume they can, but that's not based in reality. libxml2, which is available in Python as lxml is something else to investigate, but I have even less experience with that. It seems from the libxml documentation that you would have access to the full DTD.
Another possibility is to convert the DTD to XSD with one of many programs then use a regular XML processor to manipulate the tree, and return it back to DTD. I worry about how lossy that might be.
At an increasing level of difficulty, if you're going to write a parser yourself for the DTD grammar, consider PyParsing or PLY.
A:
You might want to consider converting your DTD to one of the XML-based formats. At that point, you can process it with ElementTree, or whatever XML toolkit you prefer.
I've had good experience with RelaxNG, which is fairly concise and straightforward. There's a list of conversion tools on its site: http://relaxng.org/#conversion
If you prefer XML Schema, here's what is available: http://www.w3.org/XML/Schema
If you're dealing with third-party documents or DTDs, this may not work for you. If it's in-house, give it a shot. XML-based schemas are much more pleasant to work with.
|
Transforming DTD's with Python
|
I'm looking for a library to help me parse and transform DTDs using Python. The only thing I have found so far is xmlproc, but that seems ancient and doesn't seem to support serialization of DTDs. There's this for Java but I'd prefer a Python solution.
Edit: by "serialization" of DTDs I mean that ideally I'd like to be able to parse the DTD to some kind of Python structure, operate on that structure and then write out the result back to a DTD.
|
[
"I don't know of an end-to-end processor for DTDs, but then again I so rarely use DTDs at all so that's not surprising.\nAmara can parse DTDs, but I don't know what level of access you can have to them or if the results can be serialized. I assume they can, but that's not based in reality. libxml2, which is available in Python as lxml is something else to investigate, but I have even less experience with that. It seems from the libxml documentation that you would have access to the full DTD.\nAnother possibility is to convert the DTD to XSD with one of many programs then use a regular XML processor to manipulate the tree, and return it back to DTD. I worry about how lossy that might be.\nAt an increasing level of difficulty, if you're going to write a parser yourself for the DTD grammar, consider PyParsing or PLY.\n",
"You might want to consider converting your DTD to one of the XML-based formats. At that point, you can process it with ElementTree, or whatever XML toolkit you prefer.\nI've had good experience with RelaxNG, which is fairly concise and straightforward. There's a list of conversion tools on its site: http://relaxng.org/#conversion\nIf you prefer XML Schema, here's what is available: http://www.w3.org/XML/Schema\nIf you're dealing with third-party documents or DTDs, this may not work for you. If it's in-house, give it a shot. XML-based schemas are much more pleasant to work with.\n"
] |
[
0,
0
] |
[] |
[] |
[
"dtd",
"dtd_parsing",
"python"
] |
stackoverflow_0001975316_dtd_dtd_parsing_python.txt
|
Q:
Is this essential functional programming feature missing from python?
I have a class in python that allows me to save a function (in a database) for later use. Now I need to have a method in the class that allows me to call this function on some arguments. Since I don't know how many arguments the function has ahead of time, I have to pass them in as list. This is where things fall apart because I can't find any way to get the argument to take its arguments from the tuple. In LISP this is very easy, since there's a keyword (well just one character) '@' for exactly this purpose:
(defmacro (call function arguments)
`(,function ,@args))
Does python do this and I've just missed it somehow?
And if it doesn't, does anyone have a creative solution?
A:
Python uses * for argument expansion. If you want keyword arguments, expand a dict using **. So the macro you showed would be:
def call(function, args):
return function(*args)
But usually the Pythonic way is to just do the call inline. There actually is a function called apply() that does exactly this, but it is deprecated because the inline way is usually cleaner.
A:
No, this is not missing from python. SaltyCrane explains the use of *args and **kwargs much better than I could.
|
Is this essential functional programming feature missing from python?
|
I have a class in python that allows me to save a function (in a database) for later use. Now I need to have a method in the class that allows me to call this function on some arguments. Since I don't know how many arguments the function has ahead of time, I have to pass them in as list. This is where things fall apart because I can't find any way to get the argument to take its arguments from the tuple. In LISP this is very easy, since there's a keyword (well just one character) '@' for exactly this purpose:
(defmacro (call function arguments)
`(,function ,@args))
Does python do this and I've just missed it somehow?
And if it doesn't, does anyone have a creative solution?
|
[
"Python uses * for argument expansion. If you want keyword arguments, expand a dict using **. So the macro you showed would be:\ndef call(function, args):\n return function(*args)\n\nBut usually the Pythonic way is to just do the call inline. There actually is a function called apply() that does exactly this, but it is deprecated because the inline way is usually cleaner.\n",
"No, this is not missing from python. SaltyCrane explains the use of *args and **kwargs much better than I could.\n"
] |
[
12,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001979003_python.txt
|
Q:
Hooking into a wave-out on different platforms
I am going to apologize in advance for being extremely vague, but my knowledge in this area is somewhat limited so I don't know the neccessary "keywords" to make my point/question clear. Sorry.
What I want to do is to find a way to obtain access to raw audio data as it is being output, say, when some external application is playing back music, when data is passed from the microphone to the output device and so on. I want to have access to that data in real time (well, almost real time, anyway), so that I can analyze/visualize it, etc.
I know, that it is certainly possible, as I've done it a long time ago in Java (I think I was using Processing and Minim libraries). This was done in windows by enabling a sort of "loopback" input device on the sound card (I think my vendor called it "Wave Out Mix" or something). How would one approach the same problem under a Linux-based OS?
I intend to use python for the analyzing/visualization part, however I can work in C if it is neccessary to get to the raw data.
Thanks in advance for any information.
A:
Whether you can access the "wave out" or "loopback" depends on your sound card and drivers.
The native sound API on Linux is called ALSA. Search for the ALSA docs and sample code and you should be able to get some code to record from your sound card, then hopefully set up your mixer so that you're recording from "wave out" instead of from the microphone.
The older Linux sound API (/dev/dsp) is called OSS. It's slightly simpler and ALSA emulates most of this API - but ALSA is the preferred solution if you want full access to your sound card.
You may want to check out Jack - it's a system for routing the audio output from one application to the input of another, in a big chain or all sorts of other configurations. There are lots and lots of compatible programs, and if everything you need already supports Jack, then you'll find it's by far the most straightforward API for this type of thing.
Finally, this may sound stupid, but you can get an analog loopback cable - a male-to-male stereo mini jack - and loop it from your headphone jack to your line in jack, and record "wave out" that way, no matter what soundcard you have. It's a stupid hack with an analog hole, but it does work, and depending on what you're trying to record, it may be good enough.
|
Hooking into a wave-out on different platforms
|
I am going to apologize in advance for being extremely vague, but my knowledge in this area is somewhat limited so I don't know the neccessary "keywords" to make my point/question clear. Sorry.
What I want to do is to find a way to obtain access to raw audio data as it is being output, say, when some external application is playing back music, when data is passed from the microphone to the output device and so on. I want to have access to that data in real time (well, almost real time, anyway), so that I can analyze/visualize it, etc.
I know, that it is certainly possible, as I've done it a long time ago in Java (I think I was using Processing and Minim libraries). This was done in windows by enabling a sort of "loopback" input device on the sound card (I think my vendor called it "Wave Out Mix" or something). How would one approach the same problem under a Linux-based OS?
I intend to use python for the analyzing/visualization part, however I can work in C if it is neccessary to get to the raw data.
Thanks in advance for any information.
|
[
"Whether you can access the \"wave out\" or \"loopback\" depends on your sound card and drivers.\nThe native sound API on Linux is called ALSA. Search for the ALSA docs and sample code and you should be able to get some code to record from your sound card, then hopefully set up your mixer so that you're recording from \"wave out\" instead of from the microphone.\nThe older Linux sound API (/dev/dsp) is called OSS. It's slightly simpler and ALSA emulates most of this API - but ALSA is the preferred solution if you want full access to your sound card.\nYou may want to check out Jack - it's a system for routing the audio output from one application to the input of another, in a big chain or all sorts of other configurations. There are lots and lots of compatible programs, and if everything you need already supports Jack, then you'll find it's by far the most straightforward API for this type of thing.\nFinally, this may sound stupid, but you can get an analog loopback cable - a male-to-male stereo mini jack - and loop it from your headphone jack to your line in jack, and record \"wave out\" that way, no matter what soundcard you have. It's a stupid hack with an analog hole, but it does work, and depending on what you're trying to record, it may be good enough.\n"
] |
[
4
] |
[] |
[] |
[
"audio",
"language_agnostic",
"linux",
"python",
"windows"
] |
stackoverflow_0001978990_audio_language_agnostic_linux_python_windows.txt
|
Q:
What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)?
a='aaaa'
print isinstance(a, basestring)#true
print isinstance(a, str)#true
A:
In Python versions prior to 3.0 there are two kinds of strings "plain strings" and "unicode strings". Plain strings (str) cannot represent characters outside of the Latin alphabet (ignoring details of code pages for simplicity). Unicode strings (unicode) can represent characters from any alphabet including some fictional ones like Klingon.
So why have two kinds of strings, would it not be better to just have Unicode since that would cover all the cases? Well it is better to have only Unicode but Python was created before Unicode was the preferred method for representing strings. It takes time to transition the string type in a language with many users, in Python 3.0 it is finally the case that all strings are Unicode.
The inheritance hierarchy of Python strings pre-3.0 is:
object
|
|
basestring
/ \
/ \
str unicode
'basestring' introduced in Python 2.3 can be thought of as a step in the direction of string unification as it can be used to check whether an object is an instance of str or unicode
>>> string1 = "I am a plain string"
>>> string2 = u"I am a unicode string"
>>> isinstance(string1, str)
True
>>> isinstance(string2, str)
False
>>> isinstance(string1, unicode)
False
>>> isinstance(string2, unicode)
True
>>> isinstance(string1, basestring)
True
>>> isinstance(string2, basestring)
True
A:
All strings are basestrings, but unicode strings are not of type str. Try this instead:
>>> a=u'aaaa'
>>> print isinstance(a, basestring)
True
>>> print isinstance(a, str)
False
A:
Really what you're asking is the difference between the basestring and str class.
Str is a class that inherits from basestr. But unicode strings also exist, as could other ones, if you wanted to make one.
>>> a = u'aaaa'
>>> isinstance(a, str)
False
>>> isinstance(a, basestring)
True
A:
Basestring is the superclass of string. In your example, a is of type "str" thus, it is both a basestring, and a str
|
What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)?
|
a='aaaa'
print isinstance(a, basestring)#true
print isinstance(a, str)#true
|
[
"In Python versions prior to 3.0 there are two kinds of strings \"plain strings\" and \"unicode strings\". Plain strings (str) cannot represent characters outside of the Latin alphabet (ignoring details of code pages for simplicity). Unicode strings (unicode) can represent characters from any alphabet including some fictional ones like Klingon.\nSo why have two kinds of strings, would it not be better to just have Unicode since that would cover all the cases? Well it is better to have only Unicode but Python was created before Unicode was the preferred method for representing strings. It takes time to transition the string type in a language with many users, in Python 3.0 it is finally the case that all strings are Unicode.\nThe inheritance hierarchy of Python strings pre-3.0 is:\n object\n |\n |\n basestring\n / \\\n / \\\n str unicode\n\n'basestring' introduced in Python 2.3 can be thought of as a step in the direction of string unification as it can be used to check whether an object is an instance of str or unicode \n>>> string1 = \"I am a plain string\"\n>>> string2 = u\"I am a unicode string\"\n>>> isinstance(string1, str)\nTrue\n>>> isinstance(string2, str)\nFalse\n>>> isinstance(string1, unicode)\nFalse\n>>> isinstance(string2, unicode)\nTrue\n>>> isinstance(string1, basestring)\nTrue\n>>> isinstance(string2, basestring)\nTrue\n\n",
"All strings are basestrings, but unicode strings are not of type str. Try this instead:\n>>> a=u'aaaa'\n>>> print isinstance(a, basestring)\nTrue\n>>> print isinstance(a, str)\nFalse\n\n",
"Really what you're asking is the difference between the basestring and str class.\nStr is a class that inherits from basestr. But unicode strings also exist, as could other ones, if you wanted to make one.\n>>> a = u'aaaa'\n>>> isinstance(a, str)\nFalse\n>>> isinstance(a, basestring)\nTrue\n\n",
"Basestring is the superclass of string. In your example, a is of type \"str\" thus, it is both a basestring, and a str\n"
] |
[
398,
8,
4,
1
] |
[] |
[] |
[
"built_in_types",
"python",
"python_2.x"
] |
stackoverflow_0001979004_built_in_types_python_python_2.x.txt
|
Q:
What causes subprocess.call to output blank file when attempting db export with mysqldump?
I am having some problems using subprocess.call to export a database using mysqldump. I'm using Python 3.1 installed on Windows 7.
from time import gmtime, strftime
import subprocess
DumpDir = "c:/apps/sqlbackup/";
DumpFile = "mysqldump-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) + ".sql";
params = [r"mysqldump --user root --password=mypassword --force --flush-privileges --compress --comments mydatabase --result-file=" + DumpDir + DumpFile];
subprocess.call(params, shell=True);
The above code causes a blank file to be created in the DumpDir.
I've tried getting python to print the command so I can test it via the CMD prompt using:
print(subprocess.list2cmdline(params));
If I paste the output to the CMD prompt and execute it, everything works fine.
Any ideas?
I'm new to Python, so I am sure the answer is simple but I've tried so many variations to get this working that I just can't figure this out.
A:
I'm uncertain of what exactly caused the problem but the above code now works after:
I reset the PATH environment setting
in Windows to be sure the path to
mysqldump is added everytime the PC
boots.
I restarted the PC (to ensure
Python/MySQL were restarted and PATH
environment settings were definitely
correct).
The problem appears to be resolved now, which is a little strange. The fact that the .sql file was being created but was empty indicated that mysqldump was executed by Python. I'm not sure why the output file was empty when executed by Python versus executing the same mysqldump command from the CMD prompt provided a successful export.
|
What causes subprocess.call to output blank file when attempting db export with mysqldump?
|
I am having some problems using subprocess.call to export a database using mysqldump. I'm using Python 3.1 installed on Windows 7.
from time import gmtime, strftime
import subprocess
DumpDir = "c:/apps/sqlbackup/";
DumpFile = "mysqldump-" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) + ".sql";
params = [r"mysqldump --user root --password=mypassword --force --flush-privileges --compress --comments mydatabase --result-file=" + DumpDir + DumpFile];
subprocess.call(params, shell=True);
The above code causes a blank file to be created in the DumpDir.
I've tried getting python to print the command so I can test it via the CMD prompt using:
print(subprocess.list2cmdline(params));
If I paste the output to the CMD prompt and execute it, everything works fine.
Any ideas?
I'm new to Python, so I am sure the answer is simple but I've tried so many variations to get this working that I just can't figure this out.
|
[
"I'm uncertain of what exactly caused the problem but the above code now works after:\n\nI reset the PATH environment setting\nin Windows to be sure the path to\nmysqldump is added everytime the PC\nboots.\nI restarted the PC (to ensure\nPython/MySQL were restarted and PATH\nenvironment settings were definitely\ncorrect).\n\nThe problem appears to be resolved now, which is a little strange. The fact that the .sql file was being created but was empty indicated that mysqldump was executed by Python. I'm not sure why the output file was empty when executed by Python versus executing the same mysqldump command from the CMD prompt provided a successful export. \n"
] |
[
1
] |
[] |
[] |
[
"mysqldump",
"python",
"subprocess"
] |
stackoverflow_0001978944_mysqldump_python_subprocess.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.