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:
How to impress developers with IronPython/Python
I need an IronPython\Python example that would show C#/VB.NET developers how awesome this language really is.
I'm looking for an easy to understand code snippet or application I can use to demo Python's capabilities.
Any thoughts?
A:
Peter Norvig's spelling corrector in 21 lines of Python 2.5.
A:
Rewrite any small C# app in IronPython, and show them how many lines of code it took you. If that's not impressing, I don't know what is.
I'm referring to one of your internal apps.
A:
I'd do a quick demo of something trivial (in Python, at least) but cool in IDLE. For instance:
>>> text = # some nice long text, e.g. the Gettysburg Address
>>> letters = [c.lower() for c in text if c.isalpha()]
>>> letters
['f', 'o', 'u', 'r', 's', 'c', 'o', 'r', 'e', 'a', 'n', 'd', 's', 'e', 'v', 'e',
...
>>> freq = {}
>>> for c in letters:
freq[c] = freq.get(c, 0) + 1
>>> freq
{'a': 102, 'c': 31, 'b': 14, 'e': 165, 'd': 58, 'g': 28, 'f': 27, 'i': 68, 'h': 80,
...
>>> for c in sorted(freq.keys(), key=lambda x: freq[x], reverse=True):
print c, freq[c]
e 165
t 126
a 102
...
This shows off what the basic list and dictionary classes look like, how list comprehensions work, named arguments, lambda expressions, the usefulness of an interactive interpreter, and it accomplishes a fairly complicated task in seven lines of code.
Edit:
Oh, and I'd then show off how the code works if you set letters using a generator expression:
letters = (c.lower() for c in text if c.isalpha())
...which is to say, exactly the same.
A:
At the very basic level you could show a string reversal program in C# and Python.
In C#:
public static string ReverseString(string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
In Python:
s[::-1]
I feel that you should demo multiple examples rather than just one. Build up from something simple, like the one above, and go to more complex ones.
A:
import clr
clr.AddReference('System.Speech')
clr.AddReference('System.Xml')
from System.Speech.Synthesis import SpeechSynthesizer
from System.Net import WebClient
from System.Xml import XmlDocument, XmlTextReader
content = WebClient().DownloadString("http://twitter.com/statuses/public_timeline.xml")
xmlDoc = XmlDocument()
spk = SpeechSynthesizer()
xmlDoc.LoadXml(content)
statusesNode = xmlDoc.SelectSingleNode("statuses")
for status in statusesNode:
s = "<?xml version=\"1.0\"?><speak version=\"1.0\" xml:lang=\"en-US\"><break/>"
s = s + status.SelectSingleNode("text").InnerText + "</speak>"
spk.SpeakSsml(s)
A talking Twitter client.
For more examples
http://www.ironpython.info/index.php/Main_Page
A:
Something simple but cool with generators, maybe?
def isprime(n):
return all(n%x!=0 for x in range(2, int(n**0.5)+1))
def containsPrime(start, limit):
return any(isPrime(x) for x in xrange(start, limit))
A:
How about a demonstration of duck typing? Redirecting StdOut to a gui, for example.
Or some of the exceptionally useful pure python libraries out there (SqlAlchemy springs to mind in my line of work, your mileage may vary).
Some of the short cut bits of syntax would be good as well, for example:
Get a quick overview of a large dataset:
print data[::1000]
Find all the strings that begin with 'a':
[s for s in list_of_strings if s.startswith('a')]
Then show them the generator version:
the_as = (s for s in really_big_list_of_strings if s.startswith('a'))
the_as.next()
A:
I have to agree Geo. Show a C# or VB app next to the same app written in IronPython. When I've done my IronPython talks, I've had a lot of success morphing C# code into Python. It makes for a very dramatic presentation.
I'm also a big fan of showing off how duck typing makes your code more testable.
A:
Generators, defining an iterator, simple
http://ttsiodras.googlepages.com/yield.html
A:
You could use CherryPy's helloworld example:
import cherrypy
class HelloWorld(object):
def index(self):
return "Hello World!"
index.exposed = True
cherrypy.quickstart(HelloWorld())
A:
How about a prime number generator.
>>> def sieve(x):
... if x: return [ x[0] ] + sieve([ y for y in x if y % x[0] > 0 ])
... return []
...
>>> sieve(range(2,100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
A:
Show them an example from the IronPython cookbook like this one on DataGridView Custom Formatting. It's not terribly flashy, but it is something that everyone will be familiar with because just about everyone has built an app with a gridview (or wants to do so).
The most important part of your demo will be the code walkthrough where you point out how things are less verbose than C# and more similar to VB.
Make sure to change the example from the cookbook to show some of the batteries included from Python. Perhaps use the os module to get a directory listing and populate the grid with filename, size, date created, etc.
A:
The possibility of doing this thanks to IronPython ability to add new members to a type at runtime impressed me
http://ironpython-resource.com/post/2008/08/23/IronPython-Dynamically-creating-objects-and-binding-them-to-a-form.aspx
|
How to impress developers with IronPython/Python
|
I need an IronPython\Python example that would show C#/VB.NET developers how awesome this language really is.
I'm looking for an easy to understand code snippet or application I can use to demo Python's capabilities.
Any thoughts?
|
[
"Peter Norvig's spelling corrector in 21 lines of Python 2.5.\n",
"Rewrite any small C# app in IronPython, and show them how many lines of code it took you. If that's not impressing, I don't know what is.\nI'm referring to one of your internal apps.\n",
"I'd do a quick demo of something trivial (in Python, at least) but cool in IDLE. For instance:\n>>> text = # some nice long text, e.g. the Gettysburg Address\n>>> letters = [c.lower() for c in text if c.isalpha()]\n>>> letters\n ['f', 'o', 'u', 'r', 's', 'c', 'o', 'r', 'e', 'a', 'n', 'd', 's', 'e', 'v', 'e',\n ...\n>>> freq = {}\n>>> for c in letters:\n freq[c] = freq.get(c, 0) + 1\n\n>>> freq\n {'a': 102, 'c': 31, 'b': 14, 'e': 165, 'd': 58, 'g': 28, 'f': 27, 'i': 68, 'h': 80, \n ...\n>>> for c in sorted(freq.keys(), key=lambda x: freq[x], reverse=True):\n print c, freq[c]\n\ne 165\nt 126\na 102\n...\n\nThis shows off what the basic list and dictionary classes look like, how list comprehensions work, named arguments, lambda expressions, the usefulness of an interactive interpreter, and it accomplishes a fairly complicated task in seven lines of code.\nEdit:\nOh, and I'd then show off how the code works if you set letters using a generator expression:\nletters = (c.lower() for c in text if c.isalpha())\n\n...which is to say, exactly the same.\n",
"At the very basic level you could show a string reversal program in C# and Python.\nIn C#:\npublic static string ReverseString(string s)\n{\n char[] arr = s.ToCharArray();\n Array.Reverse(arr);\n return new string(arr);\n}\n\nIn Python:\ns[::-1]\n\nI feel that you should demo multiple examples rather than just one. Build up from something simple, like the one above, and go to more complex ones.\n",
"import clr\nclr.AddReference('System.Speech')\nclr.AddReference('System.Xml')\n\nfrom System.Speech.Synthesis import SpeechSynthesizer\nfrom System.Net import WebClient\nfrom System.Xml import XmlDocument, XmlTextReader\n\n\ncontent = WebClient().DownloadString(\"http://twitter.com/statuses/public_timeline.xml\")\nxmlDoc = XmlDocument()\nspk = SpeechSynthesizer()\n\nxmlDoc.LoadXml(content)\nstatusesNode = xmlDoc.SelectSingleNode(\"statuses\")\nfor status in statusesNode:\n s = \"<?xml version=\\\"1.0\\\"?><speak version=\\\"1.0\\\" xml:lang=\\\"en-US\\\"><break/>\"\n s = s + status.SelectSingleNode(\"text\").InnerText + \"</speak>\"\n spk.SpeakSsml(s)\n\nA talking Twitter client.\nFor more examples\nhttp://www.ironpython.info/index.php/Main_Page\n",
"Something simple but cool with generators, maybe?\ndef isprime(n):\n return all(n%x!=0 for x in range(2, int(n**0.5)+1))\n\ndef containsPrime(start, limit):\n return any(isPrime(x) for x in xrange(start, limit))\n\n",
"How about a demonstration of duck typing? Redirecting StdOut to a gui, for example.\nOr some of the exceptionally useful pure python libraries out there (SqlAlchemy springs to mind in my line of work, your mileage may vary).\nSome of the short cut bits of syntax would be good as well, for example:\nGet a quick overview of a large dataset:\nprint data[::1000]\n\nFind all the strings that begin with 'a':\n[s for s in list_of_strings if s.startswith('a')]\n\nThen show them the generator version:\nthe_as = (s for s in really_big_list_of_strings if s.startswith('a'))\nthe_as.next()\n\n",
"I have to agree Geo. Show a C# or VB app next to the same app written in IronPython. When I've done my IronPython talks, I've had a lot of success morphing C# code into Python. It makes for a very dramatic presentation.\nI'm also a big fan of showing off how duck typing makes your code more testable.\n",
"Generators, defining an iterator, simple \nhttp://ttsiodras.googlepages.com/yield.html\n",
"You could use CherryPy's helloworld example:\nimport cherrypy\n\nclass HelloWorld(object):\n def index(self):\n return \"Hello World!\"\n index.exposed = True\n\ncherrypy.quickstart(HelloWorld())\n\n",
"How about a prime number generator.\n>>> def sieve(x):\n... if x: return [ x[0] ] + sieve([ y for y in x if y % x[0] > 0 ])\n... return []\n... \n>>> sieve(range(2,100))\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n\n",
"Show them an example from the IronPython cookbook like this one on DataGridView Custom Formatting. It's not terribly flashy, but it is something that everyone will be familiar with because just about everyone has built an app with a gridview (or wants to do so).\nThe most important part of your demo will be the code walkthrough where you point out how things are less verbose than C# and more similar to VB.\nMake sure to change the example from the cookbook to show some of the batteries included from Python. Perhaps use the os module to get a directory listing and populate the grid with filename, size, date created, etc.\n",
"The possibility of doing this thanks to IronPython ability to add new members to a type at runtime impressed me\nhttp://ironpython-resource.com/post/2008/08/23/IronPython-Dynamically-creating-objects-and-binding-them-to-a-form.aspx\n"
] |
[
19,
10,
6,
4,
4,
3,
3,
3,
2,
2,
1,
1,
0
] |
[] |
[] |
[
"ironpython",
"python"
] |
stackoverflow_0001708103_ironpython_python.txt
|
Q:
Masquerading real module of a class
Suppose you have the following layout for a python package
./a
./a/__init__.py
./a/_b.py
inside __init__.py you have
from _b import *
and inside _b.py you have
class B(object): pass
If you import from interactive prompt
>>> import a
>>> a.B
<class 'a._b.B'>
>>>
How can I completely hide the existence of _b ?
The problem I am trying to solve is the following: I want a facade package importing "hidden" modules and classes. The classes available from the facade (in my case a) are kept stable and guaranteed for the future. I want, however, freedom to relocate classes "under the hood", hence the hidden modules. This is all nice, but if some client code pickles an object provided by the facade, this pickled data will refer to the hidden module nesting, not to the facade nesting. In other words, if I reposition the B class in a module _c.py, client codes will not be able to unpickle because the pickled classes are referring to a._b.B, which has been moved. If they referred to a.B, I could relocate the B class as much as I want under the hood, without ruining pickled data.
A:
try:
B.__module__= 'a'
Incidentally you probably want an absolute import:
from a._b import *
as relative imports without the new explicit dot syntax are going away (see PEP 328).
ETA re comment:
I would have to set the module explicitly for every class
Yes, I don't think there's a way around that but you could at least automate it, at the end of __init__:
for value in globals().values():
if inspect.isclass(value) and value.__module__.startswith('a.'):
value.__module__= 'a'
(For new-style classes only you could get away with isinstance(value, type) instead of inspect. If the module doesn't have to run as __main__ you could use __name__ instead of hard-coding 'a'.)
A:
You could set the __module__ variable for Class B
class B(object): pass
B.__module__ = 'a'
For classes, functions, and methods, this attribute contains the name of the module in which the object was defined.
Or define it once in your __init__.py:
from a._b import B # change this line, when required, e.g. from a._c import B
B.__module__ = 'a'
|
Masquerading real module of a class
|
Suppose you have the following layout for a python package
./a
./a/__init__.py
./a/_b.py
inside __init__.py you have
from _b import *
and inside _b.py you have
class B(object): pass
If you import from interactive prompt
>>> import a
>>> a.B
<class 'a._b.B'>
>>>
How can I completely hide the existence of _b ?
The problem I am trying to solve is the following: I want a facade package importing "hidden" modules and classes. The classes available from the facade (in my case a) are kept stable and guaranteed for the future. I want, however, freedom to relocate classes "under the hood", hence the hidden modules. This is all nice, but if some client code pickles an object provided by the facade, this pickled data will refer to the hidden module nesting, not to the facade nesting. In other words, if I reposition the B class in a module _c.py, client codes will not be able to unpickle because the pickled classes are referring to a._b.B, which has been moved. If they referred to a.B, I could relocate the B class as much as I want under the hood, without ruining pickled data.
|
[
"try:\nB.__module__= 'a'\n\nIncidentally you probably want an absolute import:\nfrom a._b import *\n\nas relative imports without the new explicit dot syntax are going away (see PEP 328).\nETA re comment:\n\nI would have to set the module explicitly for every class\n\nYes, I don't think there's a way around that but you could at least automate it, at the end of __init__:\nfor value in globals().values():\n if inspect.isclass(value) and value.__module__.startswith('a.'):\n value.__module__= 'a'\n\n(For new-style classes only you could get away with isinstance(value, type) instead of inspect. If the module doesn't have to run as __main__ you could use __name__ instead of hard-coding 'a'.)\n",
"You could set the __module__ variable for Class B\nclass B(object): pass\nB.__module__ = 'a'\n\n\nFor classes, functions, and methods, this attribute contains the name of the module in which the object was defined.\n\nOr define it once in your __init__.py:\nfrom a._b import B # change this line, when required, e.g. from a._c import B\nB.__module__ = 'a'\n\n"
] |
[
6,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001808522_python.txt
|
Q:
I just want to download this URL...but it is giving me an error! ...unicode.. (Python)
theurl = 'http://bit.ly/6IcCtf/'
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
if unicode == 1:
#print urlResponse.headers['content-type']
#encoding=urlResponse.headers['content-type'].split('charset=')[-1]
#htmlSource = unicode(htmlSource, encoding)
htmlSource = htmlSource.encode('utf8')
return htmlSource
Please take a look at the unicode portion. I've tried those two options...but doesn't work.
htmlSource = htmlSource.encode('utf8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 370747: ordinal not in range(128)
and also this when I try the longer method of encoding...
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1
A:
Your html data is a string that comes from the internet already encoded with some encoding. Before encoding it to utf-8, you must decode it first.
Python is implicity trying to decode it (That's why you get a UnicodeDecodeError not UnicodeEncodeError).
You can solve the problem by explicity decoding your bytestring (using the appropriate encoding) before trying to reencode it to utf-8.
Example:
utf8encoded = htmlSource.decode('some_encoding').encode('utf-8')
Use the correct encoding the page was encoded in first place, instead of 'some_encoding'.
You have to know which encoding a string is using before you can decode it.
A:
Not decode? htmlSource = htmlSource.decode('utf8')
decode mean "decode htmlSource from utf8 encoding"
encode mean "encode htmlSource to utf8 encoding"
since you are extracting the existing data (crawling from website), you need to decode it, and when you insert to mysql, you may need to encode as utf8 according to your mysql db/table/fields collations.
A:
Probably you want to decode Utf8, not encode it:
htmlSource = htmlSource.decode('utf8')
|
I just want to download this URL...but it is giving me an error! ...unicode.. (Python)
|
theurl = 'http://bit.ly/6IcCtf/'
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
if unicode == 1:
#print urlResponse.headers['content-type']
#encoding=urlResponse.headers['content-type'].split('charset=')[-1]
#htmlSource = unicode(htmlSource, encoding)
htmlSource = htmlSource.encode('utf8')
return htmlSource
Please take a look at the unicode portion. I've tried those two options...but doesn't work.
htmlSource = htmlSource.encode('utf8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 370747: ordinal not in range(128)
and also this when I try the longer method of encoding...
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1
|
[
"Your html data is a string that comes from the internet already encoded with some encoding. Before encoding it to utf-8, you must decode it first.\nPython is implicity trying to decode it (That's why you get a UnicodeDecodeError not UnicodeEncodeError).\nYou can solve the problem by explicity decoding your bytestring (using the appropriate encoding) before trying to reencode it to utf-8.\nExample:\nutf8encoded = htmlSource.decode('some_encoding').encode('utf-8')\n\nUse the correct encoding the page was encoded in first place, instead of 'some_encoding'.\nYou have to know which encoding a string is using before you can decode it.\n",
"Not decode? htmlSource = htmlSource.decode('utf8')\ndecode mean \"decode htmlSource from utf8 encoding\"\nencode mean \"encode htmlSource to utf8 encoding\"\nsince you are extracting the existing data (crawling from website), you need to decode it, and when you insert to mysql, you may need to encode as utf8 according to your mysql db/table/fields collations.\n",
"Probably you want to decode Utf8, not encode it:\nhtmlSource = htmlSource.decode('utf8')\n\n"
] |
[
5,
3,
1
] |
[] |
[] |
[
"encode",
"http",
"python",
"unicode",
"urllib2"
] |
stackoverflow_0001808612_encode_http_python_unicode_urllib2.txt
|
Q:
Getting error when INSERT into MySQL
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1
def getSource(theurl, moved = 0):
if moved == 1:
theurl = urllib2.urlopen(theurl).geturl()
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
return htmlSource
new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource)
new_u.save()
Why is this happening?
I am basically downloading URL of a page...and then saving it to a database using Django.
It only happens sometimes....and sometimes it works fine.
Edit: it seems like I have to set the database to UTF-8? What is the command to do that?
A:
You basically need to ensure proper a string encoding. E.g. the string you provide to django is not UTF-8 encoded and therefore some characters can't be resolved.
Some helpful advice on how to find the encoding of the requested page can be found here: urllib2 read to Unicode
A:
There are 2 ways to go if you want to alter the character set in MySQL.
First is the default of the database, see MySQL Alter database,
and the second is per-table: MySQL Alter Table.
The database gives the default charset for, I believe, new tables. This
can be overridden on a per-table basis, which you need to do since you
already have tables. "utf8" is a supported character set.
Also have a look at Blog about UTF8 with django and MySQL.
|
Getting error when INSERT into MySQL
|
_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1
def getSource(theurl, moved = 0):
if moved == 1:
theurl = urllib2.urlopen(theurl).geturl()
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
return htmlSource
new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource)
new_u.save()
Why is this happening?
I am basically downloading URL of a page...and then saving it to a database using Django.
It only happens sometimes....and sometimes it works fine.
Edit: it seems like I have to set the database to UTF-8? What is the command to do that?
|
[
"You basically need to ensure proper a string encoding. E.g. the string you provide to django is not UTF-8 encoded and therefore some characters can't be resolved.\nSome helpful advice on how to find the encoding of the requested page can be found here: urllib2 read to Unicode\n",
"There are 2 ways to go if you want to alter the character set in MySQL.\nFirst is the default of the database, see MySQL Alter database,\nand the second is per-table: MySQL Alter Table.\nThe database gives the default charset for, I believe, new tables. This\ncan be overridden on a per-table basis, which you need to do since you\nalready have tables. \"utf8\" is a supported character set.\nAlso have a look at Blog about UTF8 with django and MySQL.\n"
] |
[
3,
0
] |
[] |
[] |
[
"database",
"django",
"html",
"mysql",
"python"
] |
stackoverflow_0001808455_database_django_html_mysql_python.txt
|
Q:
What is the default content-type/charset?
According to this answer: urllib2 read to Unicode
I have to get the content-type in order to change to Unicode. However, some websites don't have a "charset".
For example, the ['content-type'] for this page is "text/html". I can't convert it to Unicode.
encoding=urlResponse.headers['content-type'].split('charset=')[-1]
htmlSource = unicode(htmlSource, encoding)
TypeError: 'int' object is not callable
Is there a default "encoding" (English, of course)...so that if nothing is found, I can just use that?
A:
Is there a default "encoding" (English, of course)...so that if nothing is found, I can just use that?
No, there isn't. You must guess.
Trivial approach: try and decode as UTF-8. If it works, great, it's probably UTF-8. If it doesn't, choose a most-likely encoding for the kinds of pages you're browsing. For English pages that's cp1252, the Windows Western European encoding. (Which is like ISO-8859-1; in fact most browsers will use cp1252 instead of iso-8859-1 even if you specify that charset, so it's worth duplicating that behaviour.)
If you need to guess other languages, it gets very hairy. There are existing modules to help you guess in these situations. See eg. chardet.
A:
Well, I just browsed the given URL, which redirects to
http://www.engadget.com/2009/11/23/apple-hits-back-at-verizon-in-new-iphone-ads-video
then hit Ctrl + U (view source) in Firefox and it shows
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
@Konrad: what do you mean "seems as though ... uses ISO-8859-1"??
@alex: what makes you think it doesn't have a "charset"??
Look at the code you have (which we guess is the line that cause the error (please always show full traceback and error message!)):
htmlSource = unicode(htmlSource, encoding)
and the error message:
TypeError: 'int' object is not callable
That means that unicode doesn't refer to the built-in function, it refers to an int. I recall that in your other question you had something like
if unicode == 1:
I suggest that you use some other name for that variable -- say use_unicode.
More suggestions: (1) always show enough code to reproduce the error (2) always read the error message.
A:
htmlSource=htmlSource.decode("utf8") should work for most cases, except you are crawling non-English encoding sites.
Or you could write the force decode function like this:
def forcedecode(text):
for x in ["utf8","sjis","cp1252","utf16"]:
try:return text.decode(x)
except:pass
return "Unknown Encoding"
A:
If there's no explicit content type, it should be ISO-8859-1 as stated earlier in the answers. Unfortunately that's not always the case, which is why browser developers spent some time on getting algorithms going that try to guess the content type based on the content of your page.
Luckily for you, Mark Pilgrim did all the hard work on porting the Firefox implementation to Python, in the form of the chardet module. His introduction on how it works for one of the chapters of Dive Into Python 3 is also well worth reading.
|
What is the default content-type/charset?
|
According to this answer: urllib2 read to Unicode
I have to get the content-type in order to change to Unicode. However, some websites don't have a "charset".
For example, the ['content-type'] for this page is "text/html". I can't convert it to Unicode.
encoding=urlResponse.headers['content-type'].split('charset=')[-1]
htmlSource = unicode(htmlSource, encoding)
TypeError: 'int' object is not callable
Is there a default "encoding" (English, of course)...so that if nothing is found, I can just use that?
|
[
"\nIs there a default \"encoding\" (English, of course)...so that if nothing is found, I can just use that? \n\nNo, there isn't. You must guess.\nTrivial approach: try and decode as UTF-8. If it works, great, it's probably UTF-8. If it doesn't, choose a most-likely encoding for the kinds of pages you're browsing. For English pages that's cp1252, the Windows Western European encoding. (Which is like ISO-8859-1; in fact most browsers will use cp1252 instead of iso-8859-1 even if you specify that charset, so it's worth duplicating that behaviour.)\nIf you need to guess other languages, it gets very hairy. There are existing modules to help you guess in these situations. See eg. chardet.\n",
"Well, I just browsed the given URL, which redirects to\nhttp://www.engadget.com/2009/11/23/apple-hits-back-at-verizon-in-new-iphone-ads-video\n\nthen hit Ctrl + U (view source) in Firefox and it shows\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n\n@Konrad: what do you mean \"seems as though ... uses ISO-8859-1\"??\n@alex: what makes you think it doesn't have a \"charset\"??\nLook at the code you have (which we guess is the line that cause the error (please always show full traceback and error message!)):\nhtmlSource = unicode(htmlSource, encoding)\n\nand the error message:\nTypeError: 'int' object is not callable\n\nThat means that unicode doesn't refer to the built-in function, it refers to an int. I recall that in your other question you had something like\nif unicode == 1:\n\nI suggest that you use some other name for that variable -- say use_unicode.\nMore suggestions: (1) always show enough code to reproduce the error (2) always read the error message.\n",
"htmlSource=htmlSource.decode(\"utf8\") should work for most cases, except you are crawling non-English encoding sites.\nOr you could write the force decode function like this:\ndef forcedecode(text):\n for x in [\"utf8\",\"sjis\",\"cp1252\",\"utf16\"]:\n try:return text.decode(x)\n except:pass\n return \"Unknown Encoding\"\n\n",
"If there's no explicit content type, it should be ISO-8859-1 as stated earlier in the answers. Unfortunately that's not always the case, which is why browser developers spent some time on getting algorithms going that try to guess the content type based on the content of your page.\nLuckily for you, Mark Pilgrim did all the hard work on porting the Firefox implementation to Python, in the form of the chardet module. His introduction on how it works for one of the chapters of Dive Into Python 3 is also well worth reading.\n"
] |
[
3,
3,
0,
0
] |
[] |
[] |
[
"encoding",
"html",
"python",
"unicode"
] |
stackoverflow_0001808567_encoding_html_python_unicode.txt
|
Q:
python: how can i avoid " list index out of range" in this simple while loop
my L1 array contains numbers like 0.029999999999999999 which i want to print off as 0.03
my code works, but gives an error at the end because the last count is out of range. i understand why it breaks, but dont know how to fix it. thanks
count = 1
while L1:
print "%.2f" %L1[count]
count = count + 1
A:
If you want to print all numbers in L1, use:
for x in L1: print '%.2f' % x
If you want to skip the first one, for x in L1[1:]: will work.
Edit: the OP mentions in a comment (!) that their desire is actually to "create a new array" (I imagine they actually mean "a new list", not an array.array, but that wouldn't be very different). There are no "rounded numbers" in the float world -- you can use round(x, 2), but that will still give you a float, so it won't necessarily have "exactly 2 digits". Anyway, for a list of strings:
newlistofstrings = ['%.2f' % x for x in L1]
or for one with decimal numbers (which can have exactly 2 digits, if you want):
import decimal
newlistofnnumbers = [decimal.Decimal('%.2f') % x for x in L1]
A:
Why don't you just loop through the L1 list instead of doing a while loop?
for i in L1:
print "%.2f" % i
Keep it simple :)
A:
L2=["%.2f" %i for i in L1]
A:
2 problems:
Your loop never ends (while L1)
You start indexing with 1 (count = 1 in initialisation)
Better is, like the others said:
for i in L1:
print "%.2f" % i
and if you also need the index (count):
for (index, item) in enumerate(L1):
print "Element number (0-based) %d is %f" % (index, item)
See also Pythonic expressions for some more nice ways to use python.
|
python: how can i avoid " list index out of range" in this simple while loop
|
my L1 array contains numbers like 0.029999999999999999 which i want to print off as 0.03
my code works, but gives an error at the end because the last count is out of range. i understand why it breaks, but dont know how to fix it. thanks
count = 1
while L1:
print "%.2f" %L1[count]
count = count + 1
|
[
"If you want to print all numbers in L1, use:\nfor x in L1: print '%.2f' % x\n\nIf you want to skip the first one, for x in L1[1:]: will work.\nEdit: the OP mentions in a comment (!) that their desire is actually to \"create a new array\" (I imagine they actually mean \"a new list\", not an array.array, but that wouldn't be very different). There are no \"rounded numbers\" in the float world -- you can use round(x, 2), but that will still give you a float, so it won't necessarily have \"exactly 2 digits\". Anyway, for a list of strings:\nnewlistofstrings = ['%.2f' % x for x in L1]\n\nor for one with decimal numbers (which can have exactly 2 digits, if you want):\nimport decimal\nnewlistofnnumbers = [decimal.Decimal('%.2f') % x for x in L1]\n\n",
"Why don't you just loop through the L1 list instead of doing a while loop?\nfor i in L1:\n print \"%.2f\" % i\n\nKeep it simple :)\n",
"L2=[\"%.2f\" %i for i in L1]\n\n",
"2 problems:\n\nYour loop never ends (while L1)\nYou start indexing with 1 (count = 1 in initialisation)\n\nBetter is, like the others said:\nfor i in L1:\n print \"%.2f\" % i\n\nand if you also need the index (count):\nfor (index, item) in enumerate(L1):\n print \"Element number (0-based) %d is %f\" % (index, item)\n\nSee also Pythonic expressions for some more nice ways to use python.\n"
] |
[
9,
2,
0,
0
] |
[] |
[] |
[
"loops",
"python",
"while_loop"
] |
stackoverflow_0001806608_loops_python_while_loop.txt
|
Q:
Algorithm should I create a new thread?
Is there an algorithm that checks whether creating a new thread pays off performance wise?
I'll set a maximum of threads that can be created anyway but if I add just one task it wouldn't be an advantage to start a new thread for that.
The programming language I use is python.
Edit 1#
Can this question even be answered or is it to general because it depends on what the threads work on?
A:
python (at least standard CPython) is a special case, because it won't run more than one thread at a time, therefore if you are doing number-crunching on a multiple cores, then pure python isn't really the best choice.
In CPython, while running python code, only one thread is executing. It protected by the Global Interpreter Lock. If you're going IO or sleeping or waiting on the other hand, then python threads make sense.
If you are number-crunching then you probably want to do that in a C-extension anyway. Failing that the multiprocessing library provides a way for pure python code to take advantage of multiple cores.
In the general, non-python, case: the question can't be answered, because it depend on:
Will running tasks on a new thread be faster at all>
What is the cost of starting a new thread?
What sort of work do the tasks contain? (IO-bound, CPU-bound, network-bound, user-bound)
How efficient is the OS at scheduling threads?
How much shared data/locking do the tasks need?
What dependencies exist between tasks?
If your tasks are independent and CPU-bound, then running one per-CPU core is probably best - but in python you'll need multiple processes to take advantage.
A:
Rule of thumb: if a thread is going to do input/output, it may be worth separating it.
If it's doing number-crunching then optimum number of threads is number of CPUs.
A:
Testing will tell you.
Basicly try, and benchmark.
A:
There is no general answer for this ... yet. But there is a trend. Since computers get more and more CPU cores (try to buy a new single CPU PC ...), using threads becomes the de-facto standard.
So if you have some work which can be parallelized, then by all means use the threading module and create a pool of workers. That won't make your code much slower in the worst case (just one thread) but it can make it much faster if a user has a more powerful PC.
In the worst case, your program will complete less than 100ms later -> people won't notice the slowdown but they will notice the speedup with 8 cores.
|
Algorithm should I create a new thread?
|
Is there an algorithm that checks whether creating a new thread pays off performance wise?
I'll set a maximum of threads that can be created anyway but if I add just one task it wouldn't be an advantage to start a new thread for that.
The programming language I use is python.
Edit 1#
Can this question even be answered or is it to general because it depends on what the threads work on?
|
[
"python (at least standard CPython) is a special case, because it won't run more than one thread at a time, therefore if you are doing number-crunching on a multiple cores, then pure python isn't really the best choice.\nIn CPython, while running python code, only one thread is executing. It protected by the Global Interpreter Lock. If you're going IO or sleeping or waiting on the other hand, then python threads make sense.\nIf you are number-crunching then you probably want to do that in a C-extension anyway. Failing that the multiprocessing library provides a way for pure python code to take advantage of multiple cores.\nIn the general, non-python, case: the question can't be answered, because it depend on:\n\nWill running tasks on a new thread be faster at all>\nWhat is the cost of starting a new thread?\nWhat sort of work do the tasks contain? (IO-bound, CPU-bound, network-bound, user-bound)\nHow efficient is the OS at scheduling threads?\nHow much shared data/locking do the tasks need?\nWhat dependencies exist between tasks?\n\nIf your tasks are independent and CPU-bound, then running one per-CPU core is probably best - but in python you'll need multiple processes to take advantage. \n",
"Rule of thumb: if a thread is going to do input/output, it may be worth separating it. \nIf it's doing number-crunching then optimum number of threads is number of CPUs.\n",
"Testing will tell you.\nBasicly try, and benchmark. \n",
"There is no general answer for this ... yet. But there is a trend. Since computers get more and more CPU cores (try to buy a new single CPU PC ...), using threads becomes the de-facto standard.\nSo if you have some work which can be parallelized, then by all means use the threading module and create a pool of workers. That won't make your code much slower in the worst case (just one thread) but it can make it much faster if a user has a more powerful PC.\nIn the worst case, your program will complete less than 100ms later -> people won't notice the slowdown but they will notice the speedup with 8 cores.\n"
] |
[
4,
3,
0,
0
] |
[] |
[] |
[
"math",
"multithreading",
"python"
] |
stackoverflow_0001808806_math_multithreading_python.txt
|
Q:
NHibernate and python
We have an existing C# project based on NHibernate and WPF. I am asked to convert it to Linux and to consider other implementation like Python. But for some reason, they like NHibernate a lot and want to keep it.
Do you know if it's possible to keep the NHibernate stuff and make it work with Python ? I am under the impression that NHibernate is glue code between C# and the DB, so can not be exported to other languages.
Alternative question: can somebody recommend a good python compatible replacement of NHibernate ? The backend DB is Oracle something.
A:
NHibernate is not specific to C#, but it is specific to .NET.
IronPython is a .NET language from which you could use NHibernate.
.NET and NHibernate can run on Linux through Mono. I'm not sure how good Mono's support is for WPF.
I'm not sure if IronPython runs on Linux, but that would seem to be the closest thing to what you are looking for.
There is a Java version of NHibernate (said tongue in cheek) called Hibernate and there are integration points between Java and Python where Linux is very much supported.
I know the Python community has its own ORMs, but as far as I'm aware, those options are not as mature and feature rich as Hibernate/NHibernate.
I would imagine that almost all of the options available to you would support Oracle.
A:
What about running your project under Mono on Linux? Mono seems to support NHibernate, which means you may be able to get away with out rewriting large chunks of your application.
Also, if you really wanted to get Python in on the action, you could use IronPython along with Mono.
A:
SQLAlchemy is the most powerful ORM in Python so far.
A:
Check out Django. They have a nice ORM and I believe it has tools to attempt a reverse-engineer from the DB schema.
|
NHibernate and python
|
We have an existing C# project based on NHibernate and WPF. I am asked to convert it to Linux and to consider other implementation like Python. But for some reason, they like NHibernate a lot and want to keep it.
Do you know if it's possible to keep the NHibernate stuff and make it work with Python ? I am under the impression that NHibernate is glue code between C# and the DB, so can not be exported to other languages.
Alternative question: can somebody recommend a good python compatible replacement of NHibernate ? The backend DB is Oracle something.
|
[
"NHibernate is not specific to C#, but it is specific to .NET.\nIronPython is a .NET language from which you could use NHibernate.\n.NET and NHibernate can run on Linux through Mono. I'm not sure how good Mono's support is for WPF.\nI'm not sure if IronPython runs on Linux, but that would seem to be the closest thing to what you are looking for.\nThere is a Java version of NHibernate (said tongue in cheek) called Hibernate and there are integration points between Java and Python where Linux is very much supported.\nI know the Python community has its own ORMs, but as far as I'm aware, those options are not as mature and feature rich as Hibernate/NHibernate.\nI would imagine that almost all of the options available to you would support Oracle.\n",
"What about running your project under Mono on Linux? Mono seems to support NHibernate, which means you may be able to get away with out rewriting large chunks of your application.\nAlso, if you really wanted to get Python in on the action, you could use IronPython along with Mono.\n",
"SQLAlchemy is the most powerful ORM in Python so far.\n",
"Check out Django. They have a nice ORM and I believe it has tools to attempt a reverse-engineer from the DB schema.\n"
] |
[
5,
2,
1,
0
] |
[] |
[] |
[
"nhibernate",
"orm",
"python"
] |
stackoverflow_0001809201_nhibernate_orm_python.txt
|
Q:
How to get the current open file line in python?
Suppose you open a file, and do an seek() somewhere in the file, how do you know the current file line ?
(I personally solved with an ad-hoc file class that maps the seek position to the line after scanning the file, but I wanted to see other hints and to add this question to stackoverflow, as I was not able to find the problem anywhere on google)
A:
When you use seek(), python gets to use pointer offsets to jump to the desired position in the file. But in order to know the current line number, you have to examine each character up to that position. So you might as well abandon seek() in favor of read():
Replace
f = open(filename, "r")
f.seek(55)
with
f = open(filename, "r")
line=f.read(55).count('\n')+1
print(line)
Perhaps you do not wish to use f.read(num) since this may require a lot of memory if num is very large. In that case, you could use a generator like this:
import itertools
import operator
line_number=reduce(operator.add,( f.read(1)=='\n' for _ in itertools.repeat(None,num)))
pos=f.tell()
This is equivalent to f.seek(num) with the added benefit of giving you line_number.
A:
Here's how I would approach the problem, using as much laziness as possible:
from random import randint
from itertools import takewhile, islice
file = "/etc/passwd"
f = open(file, "r")
f.seek(randint(10,250))
pos = f.tell()
print "pos=%d" % pos
def countbytes(iterable):
bytes = 0
for item in iterable:
bytes += len(item)
yield bytes
print 1+len(list(takewhile(lambda x: x <= pos, countbytes(open(file, "r")))))
For a slightly less readable but much more lazy approach, use enumerate and dropwhile:
from random import randint
from itertools import islice, dropwhile
file = "/etc/passwd"
f = open(file, "r")
f.seek(randint(10,250))
pos = f.tell()
print "pos=%d" % pos
def countbytes(iterable):
bytes = 0
for item in iterable:
bytes += len(item)
yield bytes
print list(
islice(
dropwhile(lambda x: x[1] <= pos, enumerate(countbytes(open(file, "r"))))
, 1))[0][0]+1
|
How to get the current open file line in python?
|
Suppose you open a file, and do an seek() somewhere in the file, how do you know the current file line ?
(I personally solved with an ad-hoc file class that maps the seek position to the line after scanning the file, but I wanted to see other hints and to add this question to stackoverflow, as I was not able to find the problem anywhere on google)
|
[
"When you use seek(), python gets to use pointer offsets to jump to the desired position in the file. But in order to know the current line number, you have to examine each character up to that position. So you might as well abandon seek() in favor of read():\nReplace\nf = open(filename, \"r\")\nf.seek(55)\n\nwith\nf = open(filename, \"r\")\nline=f.read(55).count('\\n')+1\nprint(line)\n\nPerhaps you do not wish to use f.read(num) since this may require a lot of memory if num is very large. In that case, you could use a generator like this:\nimport itertools\nimport operator\nline_number=reduce(operator.add,( f.read(1)=='\\n' for _ in itertools.repeat(None,num)))\npos=f.tell()\n\nThis is equivalent to f.seek(num) with the added benefit of giving you line_number.\n",
"Here's how I would approach the problem, using as much laziness as possible:\nfrom random import randint\nfrom itertools import takewhile, islice\n\nfile = \"/etc/passwd\"\nf = open(file, \"r\")\n\nf.seek(randint(10,250))\npos = f.tell()\n\nprint \"pos=%d\" % pos\n\ndef countbytes(iterable):\n bytes = 0\n for item in iterable:\n bytes += len(item)\n yield bytes\n\nprint 1+len(list(takewhile(lambda x: x <= pos, countbytes(open(file, \"r\")))))\n\nFor a slightly less readable but much more lazy approach, use enumerate and dropwhile:\nfrom random import randint\nfrom itertools import islice, dropwhile\n\nfile = \"/etc/passwd\"\nf = open(file, \"r\")\n\nf.seek(randint(10,250))\npos = f.tell()\n\nprint \"pos=%d\" % pos\n\ndef countbytes(iterable):\n bytes = 0\n for item in iterable:\n bytes += len(item)\n yield bytes\n\nprint list(\n islice(\n dropwhile(lambda x: x[1] <= pos, enumerate(countbytes(open(file, \"r\"))))\n , 1))[0][0]+1\n\n"
] |
[
6,
4
] |
[] |
[] |
[
"file",
"line_count",
"python",
"seek"
] |
stackoverflow_0001809232_file_line_count_python_seek.txt
|
Q:
Is it possible to script for data entry with Drupal?
I'm planning on putting a store's inventory on a Drupal site and I'm wondering if it's possible to create a script (maybe in python/php?) to enter the data automatically to Drupal with CCK? Thanks in advance!
A:
The fastest and easiest thing would be to do the stuff with a little Drupal module you make for the case, instead of having to send lots of posts to the server and spend resources on node loads and what not.
Anyways, what you need for this is quite similar to what mac answers here:
In this case you don't need all the special file_field stuff, but you still need to insert the values for the different cck fields you might have and the node body and title. After setting the value which you could get directly from your database, you can save your node.
If you connect to the db directly, you need to have the same type as the one you use for drupal, or do it outside the Drupal api. If you do use the drupal API for it, take a look at db_set_active()
A:
There are a couple of Drupal modules dedicated to different scenarios of external (mass) imports - check this overview for a options/comparisons.
If you have very specific needs, you could write your own module, using the existing ones and the links/hints provided by googletorps (+1) for guidance on how to do the actual insertion while ignoring the generalizations.
A:
Lots of good suggestions have been done by Henrik and Googletorp already.
A few additional elements to consider to design your strategy:
Are you going to do a full-fledged e-store (presumably realised with ubercart) or are you simply setting up a view of nodes, just to present the inventory to site visitors?
How many products are you going to import?
How often are you going to reimport them?
Solutions that I would feel to exclude for sure:
POST: as commented by googletorp, it would be overly complicated.
External script: you can't really avoid (unless you like to live dangerously and/or have time to waste) using drupal API, whether they are the core ones or those of ubercart. Data is scattered across several tables, and there are plenty of hooks that are triggered when a node is inserted. The only exception is if you would do a PHP script that perform the bootstrap first (see the structure of index.php or xmlrpc.php to see how it works), but in that case I would rather go for a module altogether: much more elegant, portable, maintainable.
Solutions that I would support:
Do your own module! As pointed out by googletorp, I gave some sample code on how to add CCK fields in this answer.
Yes, that is... is the only one I believe in! ;)
However what I learned is equally important, is to pick a suitable source of data for the import. Here's my opinion:
Read directly from DB: Good only if you have to import stuff once and for all and if the DB schema of the exporting application is simple enough to build sensible queries. Software changes and evolves, and DB schemas follow. If you find yourself in the need of re-importing in two months time and the schema of your other application has changed, you will have to change your code, change tests, etc, etc...
Use XML files: If your original application can export in this format, with PHP' SimpleXML and Xpath + PHP typecasting it's really a breeze to get the data you want in the format you want in a matter of minutes. The only downside of this method is that relies on... files. So, if you need to have periodic unmanned and automatic imports, it's a bit of a pain to foresee all the problems that can happen (wrong permissions on filesystems, corrupted files, wrong encoding...) and to put in place counter-measures. Vice-versa, I like this method a lot for when I know somebody will be supervising the import process all the time and can intervene in case of troubles.
Webservice: That is the one I like the most if I have to import in an automatic and periodic fashion. The biggest advantage is that the two applications "talk" to each other, and expose some of their business logic, so that you can actually have a session that looks like: "hey, I need all the products that have changed prices since last week" - "here you are, they should be 127, in three categories, do you copy that?" - "Oh yeah... Got all of them loud and clear: 127 items and 3 categories!". This simplify a lot trapping errors and exceptions. While Drupal works out the box as a webservice consumer and provider, you will have to implement webservice also on the other application, and this might or might not be difficult: it totally depends from the exporting application.
HTH!
A:
CCK or otherwise, it's just a wellformed POST query (presumably), so sure, go for it.
A:
If your source data is in MySQL I would be looking at the Migrate module to create content. Here is an excerpt from its project page:
... provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).
|
Is it possible to script for data entry with Drupal?
|
I'm planning on putting a store's inventory on a Drupal site and I'm wondering if it's possible to create a script (maybe in python/php?) to enter the data automatically to Drupal with CCK? Thanks in advance!
|
[
"The fastest and easiest thing would be to do the stuff with a little Drupal module you make for the case, instead of having to send lots of posts to the server and spend resources on node loads and what not.\nAnyways, what you need for this is quite similar to what mac answers here:\nIn this case you don't need all the special file_field stuff, but you still need to insert the values for the different cck fields you might have and the node body and title. After setting the value which you could get directly from your database, you can save your node.\nIf you connect to the db directly, you need to have the same type as the one you use for drupal, or do it outside the Drupal api. If you do use the drupal API for it, take a look at db_set_active()\n",
"There are a couple of Drupal modules dedicated to different scenarios of external (mass) imports - check this overview for a options/comparisons.\nIf you have very specific needs, you could write your own module, using the existing ones and the links/hints provided by googletorps (+1) for guidance on how to do the actual insertion while ignoring the generalizations.\n",
"Lots of good suggestions have been done by Henrik and Googletorp already.\nA few additional elements to consider to design your strategy:\n\nAre you going to do a full-fledged e-store (presumably realised with ubercart) or are you simply setting up a view of nodes, just to present the inventory to site visitors?\nHow many products are you going to import?\nHow often are you going to reimport them?\n\nSolutions that I would feel to exclude for sure:\n\nPOST: as commented by googletorp, it would be overly complicated.\nExternal script: you can't really avoid (unless you like to live dangerously and/or have time to waste) using drupal API, whether they are the core ones or those of ubercart. Data is scattered across several tables, and there are plenty of hooks that are triggered when a node is inserted. The only exception is if you would do a PHP script that perform the bootstrap first (see the structure of index.php or xmlrpc.php to see how it works), but in that case I would rather go for a module altogether: much more elegant, portable, maintainable.\n\nSolutions that I would support:\n\nDo your own module! As pointed out by googletorp, I gave some sample code on how to add CCK fields in this answer.\nYes, that is... is the only one I believe in! ;)\n\nHowever what I learned is equally important, is to pick a suitable source of data for the import. Here's my opinion:\n\nRead directly from DB: Good only if you have to import stuff once and for all and if the DB schema of the exporting application is simple enough to build sensible queries. Software changes and evolves, and DB schemas follow. If you find yourself in the need of re-importing in two months time and the schema of your other application has changed, you will have to change your code, change tests, etc, etc...\nUse XML files: If your original application can export in this format, with PHP' SimpleXML and Xpath + PHP typecasting it's really a breeze to get the data you want in the format you want in a matter of minutes. The only downside of this method is that relies on... files. So, if you need to have periodic unmanned and automatic imports, it's a bit of a pain to foresee all the problems that can happen (wrong permissions on filesystems, corrupted files, wrong encoding...) and to put in place counter-measures. Vice-versa, I like this method a lot for when I know somebody will be supervising the import process all the time and can intervene in case of troubles.\nWebservice: That is the one I like the most if I have to import in an automatic and periodic fashion. The biggest advantage is that the two applications \"talk\" to each other, and expose some of their business logic, so that you can actually have a session that looks like: \"hey, I need all the products that have changed prices since last week\" - \"here you are, they should be 127, in three categories, do you copy that?\" - \"Oh yeah... Got all of them loud and clear: 127 items and 3 categories!\". This simplify a lot trapping errors and exceptions. While Drupal works out the box as a webservice consumer and provider, you will have to implement webservice also on the other application, and this might or might not be difficult: it totally depends from the exporting application.\n\nHTH!\n",
"CCK or otherwise, it's just a wellformed POST query (presumably), so sure, go for it.\n",
"If your source data is in MySQL I would be looking at the Migrate module to create content. Here is an excerpt from its project page:\n\n... provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).\n\n"
] |
[
2,
2,
2,
0,
0
] |
[] |
[] |
[
"data_entry",
"drupal",
"php",
"python"
] |
stackoverflow_0001808721_data_entry_drupal_php_python.txt
|
Q:
Cross-platform help viewer with search functionality
I am looking for a help viewer like Windows CHM that basically provides support for
adding content in HTML format
define Table of Contents
decent search
It should work on Windows, Mac and Linux. Bonus points for also having support for generating a "plain HTML/javascript" version that can be viewed in any browser (albeit without search support).
Language preference: Python
A:
wxHtmlHelpController, which is part of wxWidgets, is a cross-platform viewer for HtmlHelp.
I'm not sure how easy it is to use it from a non-wxWidgets program, but I think it can be done.
A:
wxHtmlHelpController doesn't support any scripting within pages, nor does it support css.
|
Cross-platform help viewer with search functionality
|
I am looking for a help viewer like Windows CHM that basically provides support for
adding content in HTML format
define Table of Contents
decent search
It should work on Windows, Mac and Linux. Bonus points for also having support for generating a "plain HTML/javascript" version that can be viewed in any browser (albeit without search support).
Language preference: Python
|
[
"wxHtmlHelpController, which is part of wxWidgets, is a cross-platform viewer for HtmlHelp.\nI'm not sure how easy it is to use it from a non-wxWidgets program, but I think it can be done.\n",
"wxHtmlHelpController doesn't support any scripting within pages, nor does it support css.\n"
] |
[
2,
1
] |
[] |
[] |
[
"chm",
"cross_platform",
"documentation",
"python"
] |
stackoverflow_0001468314_chm_cross_platform_documentation_python.txt
|
Q:
python script optimization for app engine
i have the following script i am using to scrap data from my uni website and insert into a GAE Db
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import datetime
__author__ = "Nash Rafeeq"
url = "http://webspace.apiit.edu.my/schedule/timetable.jsp"
viewurl = "http://localhost:8000/timekeeper/intake/checkintake/"
inserturl = "http://localhost:8000/timekeeper/intake/addintake/"
print url
mech = Browser()
try:
page = mech.open(url)
html = page.read()
except Exception, err:
print str(err)
#print html
soup = BeautifulSoup(html)
soup.prettify()
tables = soup.find('select')
for options in tables:
intake = options.string
#print intake
try:
#print viewurl+intake
page = mech.open(viewurl+intake)
html = page.read()
print html
if html=="Exist in database":
print intake, " Exist in the database skiping"
else:
page = mech.open(inserturl+intake)
html = page.read()
print html
if html=="Ok":
print intake, "added to the database"
else:
print "Error adding ", intake, " to database"
except Exception, err:
print str(err)
i am wondering what would be the best way to optimize this script so i can run it on the app engine servers. as it is, it is now scraping over 300 entries and take well over 10 mins to insert all the data on my local machine
the model that is being used to store the data is
class Intake(db.Model):
intake=db.StringProperty(multiline=False, required=True)
#@permerlink
def get_absolute_url(self):
return "/timekeeper/%s/" % self.intake
class Meta:
db_table = "Intake"
verbose_name_plural = "Intakes"
ordering = ['intake']
A:
Divide and conquer.
Make a list of tasks (e.g. urls to scrape/parse)
Add your tasks into a queue (appengine taskqueue api, amazon sqs, …)
Process your queue
A:
The first thing you should do is rewrite your script to use the App Engine datastore directly. A large part of the time you're spending is undoubtedly because you're using HTTP requests (two per entry!) to insert data into your datastore. Using the datastore directly with batch puts ought to cut a couple of orders of magnitude off your runtime.
If your parsing code is still too slow, you can cut the work up into chunks and use the task queue API to do the work in multiple requests.
A:
hi according to tosh and nick i have modified the script as bellow
from google.appengine.api import urlfetch
from BeautifulSoup import BeautifulSoup
from timkeeper.models import Intake
from google.appengine.ext import db
__author__ = "Nash Rafeeq"
url = "http://webspace.apiit.edu.my/schedule/timetable.jsp"
try:
page = urlfetch.fetch(url)
#print html
soup = BeautifulSoup(page.content)
soup.prettify()
tables = soup.find('select')
models=[]
for options in tables:
intake_code = options.string
if Intake.all().filter('intake',intake_code).count()<1:
data = Intake(intake=intake_code)
models.append(data)
try:
if len(models)>0:
db.put(models)
else:
pass
except Exception,err:
pass
except Exception, err:
print str(err)
am i on the right track ? also i am not really sure how to get this to invoke on a schedule (once a week) what would be the best way to do it?
and thanks for the prompt answers
|
python script optimization for app engine
|
i have the following script i am using to scrap data from my uni website and insert into a GAE Db
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import re
import datetime
__author__ = "Nash Rafeeq"
url = "http://webspace.apiit.edu.my/schedule/timetable.jsp"
viewurl = "http://localhost:8000/timekeeper/intake/checkintake/"
inserturl = "http://localhost:8000/timekeeper/intake/addintake/"
print url
mech = Browser()
try:
page = mech.open(url)
html = page.read()
except Exception, err:
print str(err)
#print html
soup = BeautifulSoup(html)
soup.prettify()
tables = soup.find('select')
for options in tables:
intake = options.string
#print intake
try:
#print viewurl+intake
page = mech.open(viewurl+intake)
html = page.read()
print html
if html=="Exist in database":
print intake, " Exist in the database skiping"
else:
page = mech.open(inserturl+intake)
html = page.read()
print html
if html=="Ok":
print intake, "added to the database"
else:
print "Error adding ", intake, " to database"
except Exception, err:
print str(err)
i am wondering what would be the best way to optimize this script so i can run it on the app engine servers. as it is, it is now scraping over 300 entries and take well over 10 mins to insert all the data on my local machine
the model that is being used to store the data is
class Intake(db.Model):
intake=db.StringProperty(multiline=False, required=True)
#@permerlink
def get_absolute_url(self):
return "/timekeeper/%s/" % self.intake
class Meta:
db_table = "Intake"
verbose_name_plural = "Intakes"
ordering = ['intake']
|
[
"Divide and conquer.\n\nMake a list of tasks (e.g. urls to scrape/parse)\nAdd your tasks into a queue (appengine taskqueue api, amazon sqs, …)\nProcess your queue\n\n",
"The first thing you should do is rewrite your script to use the App Engine datastore directly. A large part of the time you're spending is undoubtedly because you're using HTTP requests (two per entry!) to insert data into your datastore. Using the datastore directly with batch puts ought to cut a couple of orders of magnitude off your runtime.\nIf your parsing code is still too slow, you can cut the work up into chunks and use the task queue API to do the work in multiple requests.\n",
"hi according to tosh and nick i have modified the script as bellow \nfrom google.appengine.api import urlfetch\nfrom BeautifulSoup import BeautifulSoup\nfrom timkeeper.models import Intake\nfrom google.appengine.ext import db\n\n__author__ = \"Nash Rafeeq\" \n\nurl = \"http://webspace.apiit.edu.my/schedule/timetable.jsp\"\ntry:\n page = urlfetch.fetch(url)\n #print html \n soup = BeautifulSoup(page.content)\n soup.prettify() \n tables = soup.find('select')\n models=[]\n for options in tables:\n intake_code = options.string\n if Intake.all().filter('intake',intake_code).count()<1:\n data = Intake(intake=intake_code)\n models.append(data)\n try:\n if len(models)>0:\n db.put(models)\n else:\n pass \n except Exception,err:\n pass\nexcept Exception, err:\n print str(err)\n\nam i on the right track ? also i am not really sure how to get this to invoke on a schedule (once a week) what would be the best way to do it?\nand thanks for the prompt answers \n"
] |
[
4,
2,
1
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0001809335_google_app_engine_python.txt
|
Q:
Why say x = x in Python?
In this file, in the function cross_from_below(x, threshold), there is a line that says threshold = threshold. What's the point of this line? Does this do something differently than if this command weren't there?
A:
There is no point to that assignment. It's probably just left over and should be removed. The next function is nearly identical, and doesn't have it.
A:
No, in the specific example you quote, that line is (harmless but) redundant -- indeed the very next function (cross threshold from above rather than from below) is almost identical (save of course for the direction of the comparisons), lacks that extra assignment, yet works just the same way.
The one and only case where something like threshold=threshold would make a difference is in a def statement, where it's the idiom to force early binding of a name (it makes use of the fact that default values are evaluated at def time, i.e., "early";-). But that's not what that code is doing -- just adding it for completeness.
A:
It could mean something. For example, if threshold was a property of a class, then assigning it could call a setter method.
But in this case, I think it's a typo. I've looked at the changelog and there is no hint that this was intentional for any reason.
A:
Or it could be one of those cases where it made sense at some point to write something like :
self.threshold = threshold
because the function was a method of some class that needed to kept the threshold. (In which case, it would mean something else, wouldn't it ?)
|
Why say x = x in Python?
|
In this file, in the function cross_from_below(x, threshold), there is a line that says threshold = threshold. What's the point of this line? Does this do something differently than if this command weren't there?
|
[
"There is no point to that assignment. It's probably just left over and should be removed. The next function is nearly identical, and doesn't have it.\n",
"No, in the specific example you quote, that line is (harmless but) redundant -- indeed the very next function (cross threshold from above rather than from below) is almost identical (save of course for the direction of the comparisons), lacks that extra assignment, yet works just the same way.\nThe one and only case where something like threshold=threshold would make a difference is in a def statement, where it's the idiom to force early binding of a name (it makes use of the fact that default values are evaluated at def time, i.e., \"early\";-). But that's not what that code is doing -- just adding it for completeness.\n",
"It could mean something. For example, if threshold was a property of a class, then assigning it could call a setter method.\nBut in this case, I think it's a typo. I've looked at the changelog and there is no hint that this was intentional for any reason.\n",
"Or it could be one of those cases where it made sense at some point to write something like : \n self.threshold = threshold\n\nbecause the function was a method of some class that needed to kept the threshold. (In which case, it would mean something else, wouldn't it ?)\n"
] |
[
14,
8,
3,
1
] |
[] |
[] |
[
"equals",
"identity",
"python"
] |
stackoverflow_0001809805_equals_identity_python.txt
|
Q:
Running twistd as root, modules aren't found
I have a simple web server written in Twisted, and I'm trying to start it up daemonized with twistd. Everything works fine with reactor.run() but when I use twistd -y (as root), none of my packages which are in direct child directories get found. I'm running twistd as root, since the server runs on port 80. The manpage for twistd says:
Note that if twistd is run as root, the working directory is not searched for Python modules.
Well that's great but why? And how can I work around? twistd seems to be ignoring --rundir . even if I set that option explicitly.
A:
General UNIX wisdom is that searching the working directory for things to execute when root is a bad idea. The argument goes that it opens the door to trojans. In not going out of its way to add the working directory to the Python module import search path when running as root, twistd is basically trying to follow this wisdom.
As another commenter said, you can explicitly set PYTHONPATH yourself to include the directories which contain the code your app needs.
You can also skip running as root entirely and use authbind to bind low-numbered ports without having superuser privileges. This is how all of my servers are deployed.
|
Running twistd as root, modules aren't found
|
I have a simple web server written in Twisted, and I'm trying to start it up daemonized with twistd. Everything works fine with reactor.run() but when I use twistd -y (as root), none of my packages which are in direct child directories get found. I'm running twistd as root, since the server runs on port 80. The manpage for twistd says:
Note that if twistd is run as root, the working directory is not searched for Python modules.
Well that's great but why? And how can I work around? twistd seems to be ignoring --rundir . even if I set that option explicitly.
|
[
"General UNIX wisdom is that searching the working directory for things to execute when root is a bad idea. The argument goes that it opens the door to trojans. In not going out of its way to add the working directory to the Python module import search path when running as root, twistd is basically trying to follow this wisdom.\nAs another commenter said, you can explicitly set PYTHONPATH yourself to include the directories which contain the code your app needs.\nYou can also skip running as root entirely and use authbind to bind low-numbered ports without having superuser privileges. This is how all of my servers are deployed.\n"
] |
[
7
] |
[] |
[] |
[
"python",
"twisted"
] |
stackoverflow_0001807484_python_twisted.txt
|
Q:
Hide stderr output in unit tests
I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, à la 2> /dev/null?
A:
I suggest writing a context manager:
import contextlib
import sys
@contextlib.contextmanager
def nostderr():
savestderr = sys.stderr
class Devnull(object):
def write(self, _): pass
def flush(self): pass
sys.stderr = Devnull()
try:
yield
finally:
sys.stderr = savestderr
Now, wrap any code snippet whose stderr you want suppressed in a with nostderr(): and you have the localized, temporary, guaranteed-reversible stderr suppression that you want.
A:
You could create a dummy file object that did nothing with its output, and set stderr to that:
class NullWriter:
def write(self, s):
pass
sys.stderr = NullWriter()
If you only want to quiet stderr for a specific duration, you can use a with statement like so:
class Quieter:
def __enter__(self):
self.old_stderr = sys.stderr
sys.stderr = NullWriter()
def __exit__(self, type, value, traceback):
sys.stderr = self.old_stderr
with Quieter():
# Do stuff; stderr will be suppressed, and it will be restored
# when this block exits
Requires Python 2.6 or higher, or you can use it in Python 2.5 with a from __future__ import with_statement.
A:
Another possibility (besides assigning to sys.stderr) is to structure your code to write errors to a file provided, but to default that file to sys.stderr. Then you can provide a DevNull writer during testing.
If you do want to reassign sys.stderr, you can use the unittest framework to manage it for you:
class DevNull(object):
def write(self, data):
pass
class MyTestCase(unittest.TestCase):
def setUp(self):
self.old_stderr = sys.stderr
sys.stderr = DevNull()
def tearDown(self):
sys.stderr = self.old_stderr
This way, every test dev-null's stderr, but then restores it at the end of the test.
A:
class DevNull(object):
def write(self, data): pass
sys.stderr = DevNull()
To have a less permanent solution, one could figure out something like as follows:
_stderr = None
def quiet():
global _stderr
if _stderr is None:
_stderr = sys.stderr
sys.stderr = DevNull()
def verbose():
global _stderr
if _stderr is not None:
sys.stderr = _stderr
_stderr = None
Function names can probably be better
|
Hide stderr output in unit tests
|
I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, à la 2> /dev/null?
|
[
"I suggest writing a context manager:\nimport contextlib\nimport sys\n\n@contextlib.contextmanager\ndef nostderr():\n savestderr = sys.stderr\n class Devnull(object):\n def write(self, _): pass\n def flush(self): pass\n sys.stderr = Devnull()\n try:\n yield\n finally:\n sys.stderr = savestderr\n\nNow, wrap any code snippet whose stderr you want suppressed in a with nostderr(): and you have the localized, temporary, guaranteed-reversible stderr suppression that you want.\n",
"You could create a dummy file object that did nothing with its output, and set stderr to that:\nclass NullWriter:\n def write(self, s):\n pass\n\nsys.stderr = NullWriter()\n\nIf you only want to quiet stderr for a specific duration, you can use a with statement like so:\nclass Quieter:\n def __enter__(self):\n self.old_stderr = sys.stderr\n sys.stderr = NullWriter()\n\n def __exit__(self, type, value, traceback):\n sys.stderr = self.old_stderr\n\nwith Quieter():\n # Do stuff; stderr will be suppressed, and it will be restored\n # when this block exits\n\nRequires Python 2.6 or higher, or you can use it in Python 2.5 with a from __future__ import with_statement.\n",
"Another possibility (besides assigning to sys.stderr) is to structure your code to write errors to a file provided, but to default that file to sys.stderr. Then you can provide a DevNull writer during testing.\nIf you do want to reassign sys.stderr, you can use the unittest framework to manage it for you:\nclass DevNull(object):\n def write(self, data): \n pass\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self):\n self.old_stderr = sys.stderr\n sys.stderr = DevNull()\n\n def tearDown(self):\n sys.stderr = self.old_stderr\n\nThis way, every test dev-null's stderr, but then restores it at the end of the test.\n",
"class DevNull(object):\n def write(self, data): pass\n\nsys.stderr = DevNull()\n\nTo have a less permanent solution, one could figure out something like as follows:\n_stderr = None\ndef quiet():\n global _stderr\n if _stderr is None:\n _stderr = sys.stderr\n sys.stderr = DevNull()\n\ndef verbose():\n global _stderr\n if _stderr is not None:\n sys.stderr = _stderr\n _stderr = None\n\nFunction names can probably be better\n"
] |
[
26,
12,
5,
4
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0001809958_python_unit_testing.txt
|
Q:
How can I create a script that manufactures MLA citations?
I have a folder full of Windows .URL files. I'd like to translate them into a list of MLA citations for my paper.
Is this a good application of Python? How can I get the page titles? I'm on Windows XP with Python 3.1.1.
A:
This is a fantastic use for Python! The .URL file format has a syntax like this:
[InternetShortcut]
URL=http://www.example.com/
OtherStuff=irrelevant
To parse your .URL files, start with ConfigParser, which will read this and make an InternetShortcut section that you can read the URL from. Once you have a list of URLs, you can then use urllib or urllib2 to load the URL, and use a dumb regex to get the page title (or BeautifulSoup as Alex suggests).
Once you have that, you have a list of URLs and page titles...not enough for a full MLA citation, but should be enough to get you started, no?
Something like this (very rough, coding in the SO window):
from glob import glob
from urllib2 import urlopen
from ConfigParser import ConfigParser
from re import search
# I use RE here, you might consider BeautifulSoup because RE can be stupid
TITLE = r"<title>([^<]+)</title>"
result = []
for file in glob("*.url"):
config = ConfigParser.ConfigParser()
config.read(file)
url = config.get("InternetShortcut", "URL")
# Get the title
page = urlopen(url).read()
try: title = search(TITLE, page).groups()[0]
except: title = "Couldn't find title"
result.append((url, title))
for url, title in result:
print "'%s' <%s>" % (title, url)
A:
Given a file that contains an HTML page, you can parse it to extract its title, and BeautifulSoup is the recommended third-party library for the job. Get the BeautifulSoup version compatible with Python 3.1 here, install it, then:
parse each file's contents into a soup object e.g. with:
from BeautifulSoup import BeautifulSoup
html = open('thefile.html', 'r').read()
soup = BeautifulSoup(html)
get the title tag, if any, and print its string contents (if any):
title = soup.find('title')
if title is None: print('No title!')
else: print('Title: ' + title.string)
|
How can I create a script that manufactures MLA citations?
|
I have a folder full of Windows .URL files. I'd like to translate them into a list of MLA citations for my paper.
Is this a good application of Python? How can I get the page titles? I'm on Windows XP with Python 3.1.1.
|
[
"This is a fantastic use for Python! The .URL file format has a syntax like this:\n[InternetShortcut]\nURL=http://www.example.com/\nOtherStuff=irrelevant\n\nTo parse your .URL files, start with ConfigParser, which will read this and make an InternetShortcut section that you can read the URL from. Once you have a list of URLs, you can then use urllib or urllib2 to load the URL, and use a dumb regex to get the page title (or BeautifulSoup as Alex suggests).\nOnce you have that, you have a list of URLs and page titles...not enough for a full MLA citation, but should be enough to get you started, no?\nSomething like this (very rough, coding in the SO window):\nfrom glob import glob\nfrom urllib2 import urlopen\nfrom ConfigParser import ConfigParser\nfrom re import search\n\n# I use RE here, you might consider BeautifulSoup because RE can be stupid\nTITLE = r\"<title>([^<]+)</title>\"\n\nresult = []\nfor file in glob(\"*.url\"):\n config = ConfigParser.ConfigParser()\n config.read(file)\n url = config.get(\"InternetShortcut\", \"URL\")\n\n # Get the title\n page = urlopen(url).read()\n try: title = search(TITLE, page).groups()[0]\n except: title = \"Couldn't find title\"\n\n result.append((url, title))\n\nfor url, title in result:\n print \"'%s' <%s>\" % (title, url)\n\n",
"Given a file that contains an HTML page, you can parse it to extract its title, and BeautifulSoup is the recommended third-party library for the job. Get the BeautifulSoup version compatible with Python 3.1 here, install it, then:\n\nparse each file's contents into a soup object e.g. with:\nfrom BeautifulSoup import BeautifulSoup\nhtml = open('thefile.html', 'r').read()\nsoup = BeautifulSoup(html)\nget the title tag, if any, and print its string contents (if any):\ntitle = soup.find('title')\nif title is None: print('No title!')\nelse: print('Title: ' + title.string)\n\n"
] |
[
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001810405_python.txt
|
Q:
Dynamically binding Python methods to an instance correctly binds the method names, but not the method
I'm writing a client for a group of RESTful services. The body of the REST calls have the same XML structure, given parameters. There are several dozen calls, and I will not be implementing all of them. As such, I want to make them easy to specify and easy to use. The REST methods are grouped by functionality in separate modules and will need to share the same urllib2 opener for authentication and cookies. Here's an example of how a method is declared:
@rest_method('POST', '/document')
def createDocument(id, title, body):
# possibly some validation on the arguments
pass
All the developer has to care about is validation. The format of the XML (for POST and PUT) or the URL (for GET and DELETE) and the deserialization of the response is done in helper methods. The decorated methods are collected in a client object from which they will be executed and processed. For example:
c = RESTClient('http://foo.com', username, password)
c.createDocument(1, 'title', 'body')
The code is done. The only issue is in attaching the decorated methods to the client class. Although all the decorated methods can be seen in the client instance, they all share the same definition, namely the last one to be bound. Here's a brief example which duplicates the behaviour I'm seeing:
import types
class C(object): pass
def one(a): return a
def two(a, b): return a+b
def bracketit(t): return '(%s)' % t
c = C()
for m in (one, two):
new_method = lambda self, *args, **kwargs:\
bracketit(m(*args, **kwargs))
method = types.MethodType(new_method, c, C)
setattr(C, m.__name__, method)
print c.one
print c.two
print c.two(1, 2)
print c.one(1)
When I run this, I get the following output:
<bound method C.<lambda> of <__main__.C object at 0x1003b0d90>>
<bound method C.<lambda> of <__main__.C object at 0x1003b0d90>>
(3)
Traceback (most recent call last):
File "/tmp/test.py", line 19, in <module>
print c.one(1)
File "/tmp/test.py", line 12, in <lambda>
bracketit(m(*args, **kwargs))
TypeError: two() takes exactly 2 arguments (1 given)
I'm not sure why the two methods are bound in the same way. I haven't been able to find much documentation on how instancemethod binds methods to instances. What is going on underneath the hood, and how would I fix the above code so that the second call prints '(1)'?
A:
The lambda is calling m, pulling it from the local scope. After the end of the for loop, m is set to two. Calling c.one or c.two will result in two being called.
You can tell that two is being called by looking at the last line of your traceback:
TypeError: two() takes exactly 2 arguments (1 given)
A good demonstration of what is going on can be found here.
This should do what you expect, but is a kinda messy:
class C(object): pass
def one(a): return a
def two(a, b): return a+b
def bracketit(t): return '(%s)' % t
c = C()
for m in (one, two):
def build_method(m):
return (lambda self, *args, **kwargs:
bracketit(m(*args, **kwargs)))
method = build_method(m)
setattr(C, m.__name__, method)
print c.one
print c.two
print c.two(1, 2)
print c.one(1)
I also removed the explicit creation of an unbound method, as it is unnessesary.
A:
The problem is the variable m is left as two at the end of the loop, and that affects the definitions made during the loop. You can fix it by creating closures with nested functions:
for m in (one, two):
def make_method(m):
def new_method(self, *args, **kwargs):
return bracketit(m(*args, **kwargs))
return new_method
method = types.MethodType(make_method(m), c, C)
setattr(C, m.__name__, method)
when run in your test code produces:
<bound method C.new_method of <__main__.C object at 0x0135EF30>>
<bound method C.new_method of <__main__.C object at 0x0135EF30>>
(3)
(1)
|
Dynamically binding Python methods to an instance correctly binds the method names, but not the method
|
I'm writing a client for a group of RESTful services. The body of the REST calls have the same XML structure, given parameters. There are several dozen calls, and I will not be implementing all of them. As such, I want to make them easy to specify and easy to use. The REST methods are grouped by functionality in separate modules and will need to share the same urllib2 opener for authentication and cookies. Here's an example of how a method is declared:
@rest_method('POST', '/document')
def createDocument(id, title, body):
# possibly some validation on the arguments
pass
All the developer has to care about is validation. The format of the XML (for POST and PUT) or the URL (for GET and DELETE) and the deserialization of the response is done in helper methods. The decorated methods are collected in a client object from which they will be executed and processed. For example:
c = RESTClient('http://foo.com', username, password)
c.createDocument(1, 'title', 'body')
The code is done. The only issue is in attaching the decorated methods to the client class. Although all the decorated methods can be seen in the client instance, they all share the same definition, namely the last one to be bound. Here's a brief example which duplicates the behaviour I'm seeing:
import types
class C(object): pass
def one(a): return a
def two(a, b): return a+b
def bracketit(t): return '(%s)' % t
c = C()
for m in (one, two):
new_method = lambda self, *args, **kwargs:\
bracketit(m(*args, **kwargs))
method = types.MethodType(new_method, c, C)
setattr(C, m.__name__, method)
print c.one
print c.two
print c.two(1, 2)
print c.one(1)
When I run this, I get the following output:
<bound method C.<lambda> of <__main__.C object at 0x1003b0d90>>
<bound method C.<lambda> of <__main__.C object at 0x1003b0d90>>
(3)
Traceback (most recent call last):
File "/tmp/test.py", line 19, in <module>
print c.one(1)
File "/tmp/test.py", line 12, in <lambda>
bracketit(m(*args, **kwargs))
TypeError: two() takes exactly 2 arguments (1 given)
I'm not sure why the two methods are bound in the same way. I haven't been able to find much documentation on how instancemethod binds methods to instances. What is going on underneath the hood, and how would I fix the above code so that the second call prints '(1)'?
|
[
"The lambda is calling m, pulling it from the local scope. After the end of the for loop, m is set to two. Calling c.one or c.two will result in two being called.\nYou can tell that two is being called by looking at the last line of your traceback:\nTypeError: two() takes exactly 2 arguments (1 given)\n\nA good demonstration of what is going on can be found here.\nThis should do what you expect, but is a kinda messy:\nclass C(object): pass\ndef one(a): return a\ndef two(a, b): return a+b\ndef bracketit(t): return '(%s)' % t\n\nc = C()\n\nfor m in (one, two):\n def build_method(m):\n return (lambda self, *args, **kwargs:\n bracketit(m(*args, **kwargs)))\n method = build_method(m)\n setattr(C, m.__name__, method)\n\nprint c.one \nprint c.two\nprint c.two(1, 2)\nprint c.one(1)\n\nI also removed the explicit creation of an unbound method, as it is unnessesary.\n",
"The problem is the variable m is left as two at the end of the loop, and that affects the definitions made during the loop. You can fix it by creating closures with nested functions:\nfor m in (one, two):\n def make_method(m):\n def new_method(self, *args, **kwargs):\n return bracketit(m(*args, **kwargs))\n return new_method\n method = types.MethodType(make_method(m), c, C)\n setattr(C, m.__name__, method)\n\nwhen run in your test code produces:\n<bound method C.new_method of <__main__.C object at 0x0135EF30>>\n<bound method C.new_method of <__main__.C object at 0x0135EF30>>\n(3)\n(1)\n\n"
] |
[
3,
3
] |
[] |
[] |
[
"python",
"types"
] |
stackoverflow_0001810514_python_types.txt
|
Q:
Python/OpenCV: Converting images taken from capture
I'm trying to convert images taken from a capture (webcam) and do some processing on them with OpenCV, but I'm having a difficult time..
When trying to convert the image to grayscale, the program crashes. (Python.exe has stopped working)
Here is the main snippet of my code:
newFrameImageGS = cv.CreateImage ((320, 240), cv.IPL_DEPTH_8U, 1)
for i in range(0,5):
newFrameImage = cv.QueryFrame(ps3eye)
cv.CvtColor(newFrameImage,newFrameImageGS,cv.CV_BGR2GRAY)
golfSwing.append(newFrameImageGS)
When I try using cvConvertScale I get the assertion error:
src.size() == dst.size() && src.channels() == dst.channels()
which makes sense, but I'm pretty confused on how to go about converting the input images of my web cam into images that can be used by functions like cvUpdateMotionHistory() and cvCalcOpticalFlowLK()
Any ideas? Thanks.
UPDATE:
I converted the image to grayscale manually with this:
for row in range(0,newFrameImage.height):
for col in range(0,newFrameImage.width):
newFrameImageGS[row,col] = (newFrameImage8U[row,col][0] * 0.114 + # B
newFrameImage8U[row,col][1] * 0.587 + # G
newFrameImage8U[row,col][2] * 0.299) # R
But this takes quite a while.. and i still can't figure out why cvCvtColor is causing the program to crash.
A:
For some reason, CvtColor caused the program to crash when the image depths where 8 bit. When I converted them to 32 bit, the program no longer crashed and everything seemed to work OK. I have no idea why this is, but at least it works now.
newFrameImage = cv.QueryFrame(ps3eye)
newFrameImage32F = cv.CreateImage((320, 240), cv.IPL_DEPTH_32F, 3)
cv.ConvertScale(newFrameImage,newFrameImage32F)
newFrameImageGS_32F = cv.CreateImage ((320,240), cv.IPL_DEPTH_32F, 1)
cv.CvtColor(newFrameImage32F,newFrameImageGS_32F,cv.CV_RGB2GRAY)
newFrameImageGS = cv.CreateImage ((320,240), cv.IPL_DEPTH_8U, 1)
cv.ConvertScale(newFrameImageGS_32F,newFrameImageGS)
A:
There is a common mistake here:
You're creating a single image in the newFrameImageGS variable before the loop, then overwrite its contents in the loop, which is then appended to a list. The result will not be what you would expect. The list will contain five references to the same image instance at the end, since only the object reference is appended to the list, no copy of the object made this way. This image will contain the very last frame, so you get five of that frame as a result, which is not what you want, I guess. Please review the Python tutorial if it is not clear for you. You can solve this by moving the first line of the above code into the body of the for loop.
Another possibilities if fixing the above would not help you:
The CvtColor function seems to be the correct one for conversion to grayscale, since it can convert to a different number of channels.
According to this manual the CvtColor function requires a destination image of the same data type as the source. Please double check that newFrameImage is a IPL_DEPTH_8U image.
|
Python/OpenCV: Converting images taken from capture
|
I'm trying to convert images taken from a capture (webcam) and do some processing on them with OpenCV, but I'm having a difficult time..
When trying to convert the image to grayscale, the program crashes. (Python.exe has stopped working)
Here is the main snippet of my code:
newFrameImageGS = cv.CreateImage ((320, 240), cv.IPL_DEPTH_8U, 1)
for i in range(0,5):
newFrameImage = cv.QueryFrame(ps3eye)
cv.CvtColor(newFrameImage,newFrameImageGS,cv.CV_BGR2GRAY)
golfSwing.append(newFrameImageGS)
When I try using cvConvertScale I get the assertion error:
src.size() == dst.size() && src.channels() == dst.channels()
which makes sense, but I'm pretty confused on how to go about converting the input images of my web cam into images that can be used by functions like cvUpdateMotionHistory() and cvCalcOpticalFlowLK()
Any ideas? Thanks.
UPDATE:
I converted the image to grayscale manually with this:
for row in range(0,newFrameImage.height):
for col in range(0,newFrameImage.width):
newFrameImageGS[row,col] = (newFrameImage8U[row,col][0] * 0.114 + # B
newFrameImage8U[row,col][1] * 0.587 + # G
newFrameImage8U[row,col][2] * 0.299) # R
But this takes quite a while.. and i still can't figure out why cvCvtColor is causing the program to crash.
|
[
"For some reason, CvtColor caused the program to crash when the image depths where 8 bit. When I converted them to 32 bit, the program no longer crashed and everything seemed to work OK. I have no idea why this is, but at least it works now.\nnewFrameImage = cv.QueryFrame(ps3eye)\n\nnewFrameImage32F = cv.CreateImage((320, 240), cv.IPL_DEPTH_32F, 3)\ncv.ConvertScale(newFrameImage,newFrameImage32F)\n\nnewFrameImageGS_32F = cv.CreateImage ((320,240), cv.IPL_DEPTH_32F, 1)\ncv.CvtColor(newFrameImage32F,newFrameImageGS_32F,cv.CV_RGB2GRAY)\n\nnewFrameImageGS = cv.CreateImage ((320,240), cv.IPL_DEPTH_8U, 1)\ncv.ConvertScale(newFrameImageGS_32F,newFrameImageGS)\n\n",
"There is a common mistake here:\nYou're creating a single image in the newFrameImageGS variable before the loop, then overwrite its contents in the loop, which is then appended to a list. The result will not be what you would expect. The list will contain five references to the same image instance at the end, since only the object reference is appended to the list, no copy of the object made this way. This image will contain the very last frame, so you get five of that frame as a result, which is not what you want, I guess. Please review the Python tutorial if it is not clear for you. You can solve this by moving the first line of the above code into the body of the for loop.\nAnother possibilities if fixing the above would not help you:\nThe CvtColor function seems to be the correct one for conversion to grayscale, since it can convert to a different number of channels.\nAccording to this manual the CvtColor function requires a destination image of the same data type as the source. Please double check that newFrameImage is a IPL_DEPTH_8U image.\n"
] |
[
4,
1
] |
[] |
[] |
[
"iplimage",
"opencv",
"python"
] |
stackoverflow_0001807528_iplimage_opencv_python.txt
|
Q:
A simple spider question
I am a newbie trying to achive this simple task by using Scrapy with no luck so far. I am asking your advice about how to do this with Scrapy or with any other tool (with Python). Thank you.
I want to
start from a page that lists bios of attorneys whose last name start with A: initial_url = www.example.com/Attorneys/List.aspx?LastName=A
From LastName=A to extract links to actual bios: /BioLinks/
visit each of the /BioLinks/ to extract the school info for each attorney.
I am able to extract the /BioLinks/ and School information but I am unable to go from the initial url to the bio pages.
If you think this is the wrong way to go about this, then, how would you achieve this goal?
Many thanks.
A:
Not sure I fully understand what you're asking, but maybe you need to get the absolute URL to each bio and retrieve the source code for that page:
import urllib2
bio_page = urllib.urlopen(bio_url).read()
Then use a regular expressions or other parsing to get the attorney's law school.
|
A simple spider question
|
I am a newbie trying to achive this simple task by using Scrapy with no luck so far. I am asking your advice about how to do this with Scrapy or with any other tool (with Python). Thank you.
I want to
start from a page that lists bios of attorneys whose last name start with A: initial_url = www.example.com/Attorneys/List.aspx?LastName=A
From LastName=A to extract links to actual bios: /BioLinks/
visit each of the /BioLinks/ to extract the school info for each attorney.
I am able to extract the /BioLinks/ and School information but I am unable to go from the initial url to the bio pages.
If you think this is the wrong way to go about this, then, how would you achieve this goal?
Many thanks.
|
[
"Not sure I fully understand what you're asking, but maybe you need to get the absolute URL to each bio and retrieve the source code for that page:\nimport urllib2\nbio_page = urllib.urlopen(bio_url).read()\n\nThen use a regular expressions or other parsing to get the attorney's law school.\n"
] |
[
0
] |
[] |
[] |
[
"python",
"web_crawler"
] |
stackoverflow_0001810652_python_web_crawler.txt
|
Q:
Parsing a string which represents a list of tuples
I have strings which look like this one:
"(8, 12.25), (13, 15), (16.75, 18.5)"
and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values.
I could do that with eval("(8, 12.25), (13, 15), (16.75, 18.5)") which gives me a tuple of tuples, but I don't think naively evaluating external information would be a wise decision.
So I wondered what an elegant pythonic solution might look like.
A:
>>> import ast
>>> print ast.literal_eval("(8, 12.25), (13, 15), (16.75, 18.5)")
((8, 12.25), (13, 15), (16.75, 18.5))
A:
def parse(s):
tuples = s.split('), ')
out = []
for x in tuples:
a,b = x.strip('()').split(', ')
out.append((float(a),float(b)))
return out
this should do the job.
A:
I've used safe_eval for jobs like this in the past.
A:
If you're working with a CSV file, and you want more than the "naive" solution which doesn't handle any errors, you're probably best off using the Python's CSV module.
A:
Download PyParsing.
I've worked with it before. You can get some pretty robust parsing behavior out of it, and I think it provides builtins that will handle your entire parsing needs with this sort of thing. Look up commaSeparatedList and nestedExpr.
A:
what's wrong with doing it systematically ? split on ")", then go through the list, remove all "(".
>>> s="(8, 12.25), (13, 15), (16.75, 18.5)"
>>> [ i.replace("(","") for i in s.split(")") ]
['8, 12.25', ', 13, 15', ', 16.75, 18.5', '']
>>> b = [ i.replace("(","") for i in s.split(")") ]
>>> for i in b:
... print i.strip(", ").replace(" ","").split(",")
...
['8', '12.25']
['13', '15']
['16.75', '18.5']
['']
Now you can bring each element into your data structure.
|
Parsing a string which represents a list of tuples
|
I have strings which look like this one:
"(8, 12.25), (13, 15), (16.75, 18.5)"
and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values.
I could do that with eval("(8, 12.25), (13, 15), (16.75, 18.5)") which gives me a tuple of tuples, but I don't think naively evaluating external information would be a wise decision.
So I wondered what an elegant pythonic solution might look like.
|
[
">>> import ast\n>>> print ast.literal_eval(\"(8, 12.25), (13, 15), (16.75, 18.5)\")\n((8, 12.25), (13, 15), (16.75, 18.5))\n\n",
"def parse(s):\n tuples = s.split('), ')\n out = []\n for x in tuples:\n a,b = x.strip('()').split(', ')\n out.append((float(a),float(b)))\n return out\n\nthis should do the job.\n",
"I've used safe_eval for jobs like this in the past. \n",
"If you're working with a CSV file, and you want more than the \"naive\" solution which doesn't handle any errors, you're probably best off using the Python's CSV module.\n",
"Download PyParsing.\nI've worked with it before. You can get some pretty robust parsing behavior out of it, and I think it provides builtins that will handle your entire parsing needs with this sort of thing. Look up commaSeparatedList and nestedExpr.\n",
"what's wrong with doing it systematically ? split on \")\", then go through the list, remove all \"(\".\n>>> s=\"(8, 12.25), (13, 15), (16.75, 18.5)\"\n>>> [ i.replace(\"(\",\"\") for i in s.split(\")\") ]\n['8, 12.25', ', 13, 15', ', 16.75, 18.5', '']\n>>> b = [ i.replace(\"(\",\"\") for i in s.split(\")\") ]\n>>> for i in b:\n... print i.strip(\", \").replace(\" \",\"\").split(\",\")\n...\n['8', '12.25']\n['13', '15']\n['16.75', '18.5']\n['']\n\nNow you can bring each element into your data structure.\n"
] |
[
27,
4,
2,
1,
1,
1
] |
[] |
[] |
[
"data_structures",
"eval",
"python",
"string",
"tuples"
] |
stackoverflow_0001810109_data_structures_eval_python_string_tuples.txt
|
Q:
Line-breaking Expression in Python
I am beginner in python and facing this problem. So how i can break the below expression in 2-3 lines
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))
Like this.
totalIncome = (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold))
Basic reason is i wanted to fit the line in 80 columns. And if i am not right about question Title please also suggest suitable title. Thanks in advance.
A:
You always never have to use line continuation characters in python thanks to parentheses:
totalIncome = ( (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)) )
Which gives you the advantage of not having to remove the character in case you join the lines later. Same goes for strings:
longString = ( 'This is the one line '
'being continued here and '
'ending with a line break \n' )
You almost always can use parentheses instead of line continuation symbols and it just looks nicer.
A:
Put your expression in parentheses:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold)))
A:
I despise breaking a line over into several lines using 'backslashes'. By wrapping the entire expression on the right hand side of the equals character, you can break the lines without worrying about ensuring there is trailing whitespace or not, such as:
totalIncome = ((classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost + float(classCSeatsSold)))
A:
Just in case you revisit the scene:
You have excessive parentheses already. You also have unnecessary occurrences of float() ... if a cost is a float and a seatsSold is an int, then you don't need float() at all.
Instead of
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))
you could have
totalIncome = classACost * classASeatsSold + classBCost * classBSeatsSold + classCCost * classCSeatsSold
which can be wrapped as
totalIncome = (
classACost * classASeatsSold
+ classBCost * classBSeatsSold
+ classCCost * classCSeatsSold
)
or
totalIncome = (classACost * classASeatsSold
+ classBCost * classBSeatsSold
+ classCCost * classCSeatsSold)
or whatever reasonable style takes your fancy. Splitting at some fixed limit is IMHO not reasonable:
totalIncome = (classACost * classASeatsSold + classBCost * classBSeatsSold +
classCCost * classCSeatsSold)
I prefer the first because it screams "Generalise me!" ...
total_income = sum(seat_price[c] * seats_sold[c] for c in class_codes)
|
Line-breaking Expression in Python
|
I am beginner in python and facing this problem. So how i can break the below expression in 2-3 lines
totalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))
Like this.
totalIncome = (classACost * float(classASeatsSold)) +
(classBCost * float(classBSeatsSold)) +
(classCCost * float(classCSeatsSold))
Basic reason is i wanted to fit the line in 80 columns. And if i am not right about question Title please also suggest suitable title. Thanks in advance.
|
[
"You always never have to use line continuation characters in python thanks to parentheses:\ntotalIncome = ( (classACost * float(classASeatsSold)) +\n (classBCost * float(classBSeatsSold)) +\n (classCCost * float(classCSeatsSold)) )\n\nWhich gives you the advantage of not having to remove the character in case you join the lines later. Same goes for strings:\nlongString = ( 'This is the one line '\n 'being continued here and '\n 'ending with a line break \\n' )\n\nYou almost always can use parentheses instead of line continuation symbols and it just looks nicer.\n",
"Put your expression in parentheses:\ntotalIncome = ((classACost * float(classASeatsSold)) +\n (classBCost * float(classBSeatsSold)) +\n (classCCost * float(classCSeatsSold)))\n\n",
"I despise breaking a line over into several lines using 'backslashes'. By wrapping the entire expression on the right hand side of the equals character, you can break the lines without worrying about ensuring there is trailing whitespace or not, such as:\ntotalIncome = ((classACost * float(classASeatsSold)) + \n (classBCost * float(classBSeatsSold)) + \n (classCCost + float(classCSeatsSold)))\n\n",
"Just in case you revisit the scene:\nYou have excessive parentheses already. You also have unnecessary occurrences of float() ... if a cost is a float and a seatsSold is an int, then you don't need float() at all.\nInstead of \ntotalIncome = (classACost * float(classASeatsSold)) + (classBCost * float(classBSeatsSold)) + (classCCost * float(classCSeatsSold))\n\nyou could have\ntotalIncome = classACost * classASeatsSold + classBCost * classBSeatsSold + classCCost * classCSeatsSold\n\nwhich can be wrapped as\ntotalIncome = (\n classACost * classASeatsSold\n + classBCost * classBSeatsSold\n + classCCost * classCSeatsSold\n )\n\nor\ntotalIncome = (classACost * classASeatsSold\n + classBCost * classBSeatsSold\n + classCCost * classCSeatsSold)\n\nor whatever reasonable style takes your fancy. Splitting at some fixed limit is IMHO not reasonable:\ntotalIncome = (classACost * classASeatsSold + classBCost * classBSeatsSold + \n classCCost * classCSeatsSold)\n\nI prefer the first because it screams \"Generalise me!\" ...\ntotal_income = sum(seat_price[c] * seats_sold[c] for c in class_codes)\n\n"
] |
[
14,
4,
4,
1
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0001809890_python_syntax.txt
|
Q:
Standard library - higher-precision floating point?
So, I'm having some precision issues in Python.
I would like to calculate functions like this:
P(x,y) = exp(-x)/(exp(-x) + exp(-y))
Where x and y might be >1000. Python's math.exp(-1000) (in 2.6 at least!) doesn't have enough floating point precision to handle this.
this form looks like logistic / logit / log-odds, but it's not, right? Is there some algebraic simplification I'm missing here?
I know about Decimal, but am not sure if it applies here
looks like homework, but it's not, I promise!
(Also, I'm open to titles! I couldn't think of a good one for this question!)
A:
you could divide the top and bottom by exp(-x)
P(x,y) = 1/(1 + exp(x-y))
A:
>>> import decimal
>>> decimal.Decimal(-1000).exp()
Decimal('5.075958897549456765291809480E-435')
>>> decimal.getcontext().prec = 60
>>> decimal.Decimal(-1000).exp()
Decimal('5.07595889754945676529180947957433691930559928289283736183239E-435')
A:
P(x,y) = exp(-x)/(exp(-x) + exp(-y))
is equivalent to:
P(x,y) = 1 / (1 + exp(x-y))
Perhaps the second one works without the use of more precision.
A:
I think you are looking for the bigfloat package for arbitrary precision floating-point reliable arithmetic.
|
Standard library - higher-precision floating point?
|
So, I'm having some precision issues in Python.
I would like to calculate functions like this:
P(x,y) = exp(-x)/(exp(-x) + exp(-y))
Where x and y might be >1000. Python's math.exp(-1000) (in 2.6 at least!) doesn't have enough floating point precision to handle this.
this form looks like logistic / logit / log-odds, but it's not, right? Is there some algebraic simplification I'm missing here?
I know about Decimal, but am not sure if it applies here
looks like homework, but it's not, I promise!
(Also, I'm open to titles! I couldn't think of a good one for this question!)
|
[
"you could divide the top and bottom by exp(-x)\nP(x,y) = 1/(1 + exp(x-y))\n\n",
">>> import decimal\n>>> decimal.Decimal(-1000).exp()\nDecimal('5.075958897549456765291809480E-435')\n>>> decimal.getcontext().prec = 60\n>>> decimal.Decimal(-1000).exp()\nDecimal('5.07595889754945676529180947957433691930559928289283736183239E-435')\n\n",
"P(x,y) = exp(-x)/(exp(-x) + exp(-y))\n\nis equivalent to:\nP(x,y) = 1 / (1 + exp(x-y))\n\nPerhaps the second one works without the use of more precision.\n",
"I think you are looking for the bigfloat package for arbitrary precision floating-point reliable arithmetic.\n"
] |
[
8,
8,
4,
3
] |
[] |
[] |
[
"floating_point",
"python"
] |
stackoverflow_0001811010_floating_point_python.txt
|
Q:
How can I track python imports
I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main python libraries.
I'm basically looking for an app that will show me something like:
App1 >>imports>> App2,App3.method
App2 >>imports>> App3,etc
I could just look through all of my files, but I'd rather not, it's a big app.
A:
Here's a simple (and slightly rudimentary;-) way to trace "who's trying to import what" in terms of module names:
import inspect
import __builtin__
savimp = __builtin__.__import__
def newimp(name, *x):
caller = inspect.currentframe().f_back
print name, caller.f_globals.get('__name__')
return savimp(name, *x)
__builtin__.__import__ = newimp
which gives, for example (having saved this as tracimp.py):
$ python -c 'import tracimp; import email; import sys; import email.mime'
email __main__
sys email
email.mime email
sys __main__
email.mime __main__
As you see, one specific characteristic of "wrapping" the __import__ built-in is that it won't be silenced by the fact that a module being imported is already in sys.modules: since taking care of that is one of __import__'s jobs, our wrapper gets called for both modules "being loaded for the first time" and ones that are just going to get fetched from sys.modules because they were already imported previously. This should come in really handy when you're trying to diagnose circular imports (it boils down to finding loops in the directed graph whose edges are identified by the two module names -- imported and importer -- which this simple approach is printing on each output line).
A:
You could use one of these scripts to make python module dependency graphs:
http://furius.ca/snakefood/
http://www.tarind.com/depgraph.html
http://code.activestate.com/recipes/535136/
A:
Try using python -v to run your program. It will trace the sequence of imports.
Another option is pylint, which will alert you to all sorts of issues, including cyclic imports.
|
How can I track python imports
|
I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main python libraries.
I'm basically looking for an app that will show me something like:
App1 >>imports>> App2,App3.method
App2 >>imports>> App3,etc
I could just look through all of my files, but I'd rather not, it's a big app.
|
[
"Here's a simple (and slightly rudimentary;-) way to trace \"who's trying to import what\" in terms of module names:\nimport inspect\nimport __builtin__\nsavimp = __builtin__.__import__\n\ndef newimp(name, *x):\n caller = inspect.currentframe().f_back\n print name, caller.f_globals.get('__name__')\n return savimp(name, *x)\n\n__builtin__.__import__ = newimp\n\nwhich gives, for example (having saved this as tracimp.py):\n$ python -c 'import tracimp; import email; import sys; import email.mime'\nemail __main__\nsys email\nemail.mime email\nsys __main__\nemail.mime __main__\n\nAs you see, one specific characteristic of \"wrapping\" the __import__ built-in is that it won't be silenced by the fact that a module being imported is already in sys.modules: since taking care of that is one of __import__'s jobs, our wrapper gets called for both modules \"being loaded for the first time\" and ones that are just going to get fetched from sys.modules because they were already imported previously. This should come in really handy when you're trying to diagnose circular imports (it boils down to finding loops in the directed graph whose edges are identified by the two module names -- imported and importer -- which this simple approach is printing on each output line).\n",
"You could use one of these scripts to make python module dependency graphs:\n\n\nhttp://furius.ca/snakefood/\n\n\nhttp://www.tarind.com/depgraph.html\n\n\nhttp://code.activestate.com/recipes/535136/\n\n\n",
"Try using python -v to run your program. It will trace the sequence of imports.\nAnother option is pylint, which will alert you to all sorts of issues, including cyclic imports.\n"
] |
[
16,
11,
10
] |
[
"It shouldn't be possible to get a cyclic import in python because it checks if the module has already been imported before importing it again. You can only import a module once, no matter how many times you call import.\nFrom http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d80a1c6db2b867c?pli=1 :\n\nImports are pretty straightforward\n really. Just remember the following:\n'import' and 'from xxx import yyy' are\n executable statements. They execute\n when the running program reaches that\n line.\nIf a module is not in sys.modules,\n then an import creates the new module\n entry in sys.modules and then executes\n the code in the module. It does not\n return control to the calling module\n until the execution has completed.\nIf a module does exist in sys.modules\n then an import simply returns that\n module whether or not it has completed\n executing. That is the reason why\n cyclic imports may return modules\n which appear to be partly empty.\nFinally, the executing script runs in\n a module named __main__, importing the\n script under its own name will create\n a new module unrelated to\n __main__.\nTake that lot together and you\n shouldn't get any surprises when\n importing modules.\n\n"
] |
[
-5
] |
[
"import",
"python"
] |
stackoverflow_0001811095_import_python.txt
|
Q:
Where can I find good tutorials and guides on wxPython and wxGlade?
Just out of curiosity, aside from their respective sites, have any of you guys found a better resource for figuring out wxPython/wxGlade?
I figured I'd ask while I'm chewing on something else, I plan on using those tools to create a GUI for the project I've started.
A:
wxGlade: http://wiki.wxpython.org/WxGladeTutorial
A video tutorial for wxGlade: http://showmedo.com/videotutorials/video?name=7850030&fromSeriesID=785
wxPython in general: http://www.wxpython.org/tutorial.php
Another wxPython tutorial: http://www.zetcode.com/wxpython/
It is also a good idea to study the code samples in wxPython's Demo application (installed with its documentation package) for the widgets you want to use.
Warning: There're bugs in wxPython have left unfixed for a long time. For example the wxAuiNotebook and such complex widgets have such bugs and deficiencies.
A:
For wxpython, apart from the wxpython.org site of course, you might want to look at this (slightly dated) tutorial and these five videos. For wxglade, again apart from the specific sites, there's a video tutorial here (though I haven't seen it, and I know little about wxglade so I'm not sure how helpful my opinion would be here;-).
|
Where can I find good tutorials and guides on wxPython and wxGlade?
|
Just out of curiosity, aside from their respective sites, have any of you guys found a better resource for figuring out wxPython/wxGlade?
I figured I'd ask while I'm chewing on something else, I plan on using those tools to create a GUI for the project I've started.
|
[
"wxGlade: http://wiki.wxpython.org/WxGladeTutorial\nA video tutorial for wxGlade: http://showmedo.com/videotutorials/video?name=7850030&fromSeriesID=785\nwxPython in general: http://www.wxpython.org/tutorial.php\nAnother wxPython tutorial: http://www.zetcode.com/wxpython/\nIt is also a good idea to study the code samples in wxPython's Demo application (installed with its documentation package) for the widgets you want to use.\nWarning: There're bugs in wxPython have left unfixed for a long time. For example the wxAuiNotebook and such complex widgets have such bugs and deficiencies.\n",
"For wxpython, apart from the wxpython.org site of course, you might want to look at this (slightly dated) tutorial and these five videos. For wxglade, again apart from the specific sites, there's a video tutorial here (though I haven't seen it, and I know little about wxglade so I'm not sure how helpful my opinion would be here;-).\n"
] |
[
2,
0
] |
[] |
[] |
[
"python",
"wxglade",
"wxpython"
] |
stackoverflow_0001811164_python_wxglade_wxpython.txt
|
Q:
How to make article spinner regex?
Let's say I have teh following:
{{Hello|Hi|Hey} {world|earth} |
{Goodbye|farewell} {noobs|n3wbz|n00blets}}
And I want that to turn into any of the following:
Hello world
Goodbye noobs
Hi earth
farewell n3wbz
// etc.
Paying attention to the way the "spinning" syntax is nested. It could be nested a billion layers deep for all we know.
I can do this easy, except once they're nested like the above example my regex messes up and the results are not correct.
Could someone show an example in either a .NET language or Python please?
A:
A simple way with re.subn, which can also accept a function instead of a replacement string:
import re
from random import randint
def select(m):
choices = m.group(1).split('|')
return choices[randint(0, len(choices)-1)]
def spinner(s):
r = re.compile('{([^{}]*)}')
while True:
s, n = r.subn(select, s)
if n == 0: break
return s.strip()
It simply replaces all the deepest choices it meets, then iterates until no choice remains. subn returns a tuple with the result and how many replacements were made, which is convenient to detect the end of the processing.
My version of select() can be replaced by Bobince's that uses random.choice() and is more elegant if you just want to stick to a random selector. If you want to build a choice tree, you could extend the above function, but you will need global variables to keep track of where you are, so moving the functions into a class would make sense. This is just a hint, I won't develop that idea since it was not really the orginial question.
Note finally that you should use r.subn(select, s, re.U) if you need unicode strings (s = u"{...}")
Example:
>>> s = "{{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}}"
>>> print spinner(s)
'farewell n3wbz'
Edit: Replaced sub by subn to avoid infinite loop (thanks to Bobince to point it out) and make it more efficient, and replaced {([^{}]+)} by {([^{}]*)} to extract empty curly brackets as well. That should make it more robust to ill-formatted patterns.
For people who like to put as much as possible on one line (which I personally wouldn't encourage):
def spin(s):
while True:
s, n = re.subn('{([^{}]*)}',
lambda m: random.choice(m.group(1).split("|")),
s)
if n == 0: break
return s.strip()
A:
Should be fairly simple, just disallow a brace set from including another, then repeatedly call doing replacements from the inner matches outwards:
def replacebrace(match):
return random.choice(match.group(1).split('|'))
def randomizebraces(s):
while True:
s1= re.sub(r'\{([^{}]*)\}', replacebrace, s)
if s1==s:
return s
s= s1
>>> randomizebraces('{{Hello|Hi|Hey} {world|earth}|{Goodbye|farewell} {noobs|n3wbz|n00blets}}')
'Hey world'
>>> randomizebraces('{{Hello|Hi|Hey} {world|earth}|{Goodbye|farewell} {noobs|n3wbz|n00blets}}')
'Goodbye noobs'
A:
This regex inverter uses pyparsing to generate matching strings (with some restrictions - unlimited repetition symbols like + and * are not allowed). If you replace {}'s with ()'s to make your original string into a regex, the inverter generates this list:
Helloworld
Helloearth
Hiworld
Hiearth
Heyworld
Heyearth
Goodbyenoobs
Goodbyen3wbz
Goodbyen00blets
farewellnoobs
farewelln3wbz
farewelln00blets
(I know the spaces are collapsed out, but maybe this code will give you some ideas on how to attack this problem.)
A:
I would use re.finditer and build a basic parse tree to determine the nesting level. To do it, I would use the span attribute of the regex match object:
text = '{{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}}'
import re
re_bracks = re.compile(r'{.+?}')
# subclass list for a basic tree datatype
class bracks(list):
def __init__(self, m):
self.m = m
# icky procedure to create the parse tree
# I hate these but don't know how else to do it
parse_tree = []
for m in re_bracks.finditer(text):
if not this_element:
# this first match
parse_tree.extend(element(m))
else:
# ... and all the rest
this_element = bracks(m)
this_start, this_end = m.span()
# if this match is nested in the old one ...
if this_start < previous_start and this_end > previous_end:
# nest it inside the previous one
previous_element.extend(this_element)
else:
# otherwise make it a child of the parse_tree
parse_tree.extend(element(m))
previous_element = this_element
previous_start, previous_end = this_start, this_end
This would give you the nesting depth of the bracketed expressions. Add some similar logic for the pipes and you'd be well on your way to solving the problem.
A:
I'd recommend taking a look at the dada engine for inspiration.
I've done an implementation of something inspired by this in scheme and leveraged scheme's AST to express my needs.
Specifically, I'd recommend strongly against trying to use a regex as a parser in general.
|
How to make article spinner regex?
|
Let's say I have teh following:
{{Hello|Hi|Hey} {world|earth} |
{Goodbye|farewell} {noobs|n3wbz|n00blets}}
And I want that to turn into any of the following:
Hello world
Goodbye noobs
Hi earth
farewell n3wbz
// etc.
Paying attention to the way the "spinning" syntax is nested. It could be nested a billion layers deep for all we know.
I can do this easy, except once they're nested like the above example my regex messes up and the results are not correct.
Could someone show an example in either a .NET language or Python please?
|
[
"A simple way with re.subn, which can also accept a function instead of a replacement string:\nimport re\nfrom random import randint\n\ndef select(m):\n choices = m.group(1).split('|')\n return choices[randint(0, len(choices)-1)]\n\ndef spinner(s):\n r = re.compile('{([^{}]*)}')\n while True:\n s, n = r.subn(select, s)\n if n == 0: break\n return s.strip()\n\nIt simply replaces all the deepest choices it meets, then iterates until no choice remains. subn returns a tuple with the result and how many replacements were made, which is convenient to detect the end of the processing.\nMy version of select() can be replaced by Bobince's that uses random.choice() and is more elegant if you just want to stick to a random selector. If you want to build a choice tree, you could extend the above function, but you will need global variables to keep track of where you are, so moving the functions into a class would make sense. This is just a hint, I won't develop that idea since it was not really the orginial question.\nNote finally that you should use r.subn(select, s, re.U) if you need unicode strings (s = u\"{...}\")\nExample:\n>>> s = \"{{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}}\"\n>>> print spinner(s)\n'farewell n3wbz'\n\n\nEdit: Replaced sub by subn to avoid infinite loop (thanks to Bobince to point it out) and make it more efficient, and replaced {([^{}]+)} by {([^{}]*)} to extract empty curly brackets as well. That should make it more robust to ill-formatted patterns.\nFor people who like to put as much as possible on one line (which I personally wouldn't encourage):\ndef spin(s):\n while True:\n s, n = re.subn('{([^{}]*)}',\n lambda m: random.choice(m.group(1).split(\"|\")),\n s)\n if n == 0: break\n return s.strip()\n\n",
"Should be fairly simple, just disallow a brace set from including another, then repeatedly call doing replacements from the inner matches outwards:\ndef replacebrace(match):\n return random.choice(match.group(1).split('|'))\n\ndef randomizebraces(s):\n while True:\n s1= re.sub(r'\\{([^{}]*)\\}', replacebrace, s)\n if s1==s:\n return s\n s= s1\n\n>>> randomizebraces('{{Hello|Hi|Hey} {world|earth}|{Goodbye|farewell} {noobs|n3wbz|n00blets}}')\n'Hey world'\n>>> randomizebraces('{{Hello|Hi|Hey} {world|earth}|{Goodbye|farewell} {noobs|n3wbz|n00blets}}')\n'Goodbye noobs'\n\n",
"This regex inverter uses pyparsing to generate matching strings (with some restrictions - unlimited repetition symbols like + and * are not allowed). If you replace {}'s with ()'s to make your original string into a regex, the inverter generates this list:\nHelloworld\nHelloearth\nHiworld\nHiearth\nHeyworld\nHeyearth\nGoodbyenoobs\nGoodbyen3wbz\nGoodbyen00blets\nfarewellnoobs\nfarewelln3wbz\nfarewelln00blets\n\n(I know the spaces are collapsed out, but maybe this code will give you some ideas on how to attack this problem.)\n",
"I would use re.finditer and build a basic parse tree to determine the nesting level. To do it, I would use the span attribute of the regex match object:\ntext = '{{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}}'\n\nimport re\nre_bracks = re.compile(r'{.+?}')\n\n# subclass list for a basic tree datatype\nclass bracks(list):\n def __init__(self, m):\n self.m = m\n\n# icky procedure to create the parse tree\n# I hate these but don't know how else to do it\nparse_tree = []\nfor m in re_bracks.finditer(text):\n if not this_element:\n # this first match\n parse_tree.extend(element(m))\n else:\n # ... and all the rest\n this_element = bracks(m)\n this_start, this_end = m.span()\n\n # if this match is nested in the old one ...\n if this_start < previous_start and this_end > previous_end:\n # nest it inside the previous one\n previous_element.extend(this_element) \n else:\n # otherwise make it a child of the parse_tree\n parse_tree.extend(element(m))\n\n previous_element = this_element\n previous_start, previous_end = this_start, this_end\n\nThis would give you the nesting depth of the bracketed expressions. Add some similar logic for the pipes and you'd be well on your way to solving the problem.\n",
"I'd recommend taking a look at the dada engine for inspiration.\nI've done an implementation of something inspired by this in scheme and leveraged scheme's AST to express my needs.\nSpecifically, I'd recommend strongly against trying to use a regex as a parser in general.\n"
] |
[
5,
4,
2,
1,
1
] |
[] |
[] |
[
".net",
"article",
"c#",
"python",
"spinner"
] |
stackoverflow_0001810861_.net_article_c#_python_spinner.txt
|
Q:
Does my code leak memory (python)?
links_list = char.getLinks(words)
for source_url in links_list:
try:
print 'Downloading URL: ' + source_url
urldict = hash_url(source_url)
source_url_short = urldict['url_short']
source_url_hash = urldict['url_short_hash']
if Url.objects.filter(source_url_short = source_url_short).count() == 0:
try:
htmlSource = getSource(source_url)
except:
htmlSource = '-'
print '\thtmlSource got an error...'
new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource)
new_u.save()
time.sleep(3)
else:
print '\tAlready in database'
except:
print '\tError with downloading URL..'
time.sleep(3)
pass
def getSource(theurl, unicode = 1, moved = 0):
if moved == 1:
theurl = urllib2.urlopen(theurl).geturl()
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
htmlSource = htmlSource.decode('utf-8').encode('utf-8')
return htmlSource
basically what this code does is...it takes a list of URLs and downloads them, saves them to a DB. That's all.
A:
maybe your process uses too much memory and the server (perhaps shared host) just kills it because you exhaust your memory quota.
here you use a call that may eat up a lot of memory:
links_list = char.getLinks(words)
for source_url in links_list:
...
Looks like you might be building a whole list in memory and then work with items. Instead it might be better to use iterator, where objects are retrieved one at at time. But this is a guess because it's hard to tell from your code what char.getLinks does
if you are using Django in debug mode, then memory usage will go up, as Mark suggests.
A:
If you are doing this in Django, make sure DEBUG is False, otherwise it will cache every query.
See FAQ
A:
The easiest way to check is to go to the task manager (on Windows - or equivalent on other platforms) and check the memory requirements of the Python process. If it stays constant, there are no memory leaks. If not, you have a memory leak somewhere and you will need to debug
A:
Perhaps you should get a job server such as beanstalkd and think about doing just one at a time.
The job server will requeue the ones that fail, allowing the rest to complete. You can also run more than one client concurrently should you need to (even on more than one machine).
Simpler design, easier to understand and test, more fault tolerant, retryable, more scalable, etc...
|
Does my code leak memory (python)?
|
links_list = char.getLinks(words)
for source_url in links_list:
try:
print 'Downloading URL: ' + source_url
urldict = hash_url(source_url)
source_url_short = urldict['url_short']
source_url_hash = urldict['url_short_hash']
if Url.objects.filter(source_url_short = source_url_short).count() == 0:
try:
htmlSource = getSource(source_url)
except:
htmlSource = '-'
print '\thtmlSource got an error...'
new_u = Url(source_url = source_url, source_url_short = source_url_short, source_url_hash = source_url_hash, html = htmlSource)
new_u.save()
time.sleep(3)
else:
print '\tAlready in database'
except:
print '\tError with downloading URL..'
time.sleep(3)
pass
def getSource(theurl, unicode = 1, moved = 0):
if moved == 1:
theurl = urllib2.urlopen(theurl).geturl()
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
htmlSource = htmlSource.decode('utf-8').encode('utf-8')
return htmlSource
basically what this code does is...it takes a list of URLs and downloads them, saves them to a DB. That's all.
|
[
"maybe your process uses too much memory and the server (perhaps shared host) just kills it because you exhaust your memory quota.\nhere you use a call that may eat up a lot of memory:\nlinks_list = char.getLinks(words)\nfor source_url in links_list:\n ...\n\nLooks like you might be building a whole list in memory and then work with items. Instead it might be better to use iterator, where objects are retrieved one at at time. But this is a guess because it's hard to tell from your code what char.getLinks does\nif you are using Django in debug mode, then memory usage will go up, as Mark suggests.\n",
"If you are doing this in Django, make sure DEBUG is False, otherwise it will cache every query.\nSee FAQ\n",
"The easiest way to check is to go to the task manager (on Windows - or equivalent on other platforms) and check the memory requirements of the Python process. If it stays constant, there are no memory leaks. If not, you have a memory leak somewhere and you will need to debug\n",
"Perhaps you should get a job server such as beanstalkd and think about doing just one at a time.\nThe job server will requeue the ones that fail, allowing the rest to complete. You can also run more than one client concurrently should you need to (even on more than one machine).\nSimpler design, easier to understand and test, more fault tolerant, retryable, more scalable, etc...\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"memory",
"memory_management",
"python"
] |
stackoverflow_0001811413_memory_memory_management_python.txt
|
Q:
How to write the grammar for this in pyparsing: match a set of words but not containing a given pattern
I am new to Python and pyparsing. I need to accomplish the following.
My sample line of text is like this:
12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009
Washing service (3 Shirt) 23 Mar 2009
I need to extract the item description, period
tok_date_in_ddmmmyyyy = Combine(Word(nums,min=1,max=2)+ " " + Word(alphas, exact=3) + " " + Word(nums,exact=4))
tok_period = Combine((tok_date_in_ddmmmyyyy + " to " + tok_date_in_ddmmmyyyy)|tok_date_in_ddmmmyyyy)
tok_desc = Word(alphanums+"-()") but stop before tok_period
How to do this?
A:
I would suggest looking at SkipTo as the pyparsing class that is most appropriate, since you have a good definition of the unwanted text, but will accept pretty much anything before that. Here are a couple of ways to use SkipTo:
text = """\
12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009
Washing service (3 Shirt) 23 Mar 2009"""
# using tok_period as defined in the OP
# parse each line separately
for tx in text.splitlines():
print SkipTo(tok_period).parseString(tx)[0]
# or have pyparsing search through the whole input string using searchString
for [[td,_]] in SkipTo(tok_period,include=True).searchString(text):
print td
Both for loops print the following:
12 items - Ironing Service
Washing service (3 Shirt)
A:
M K Saravanan, this particular parsing problem is not so hard to do with good 'ole re:
import re
import string
text='''
12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009
Washing service (3 Shirt) 23 Mar 2009
This line does not match
'''
date_pat=re.compile(
r'(\d{1,2}\s+[a-zA-Z]{3}\s+\d{4}(?:\s+to\s+\d{1,2}\s+[a-zA-Z]{3}\s+\d{4})?)')
for line in text.splitlines():
if line:
try:
description,period=map(string.strip,date_pat.split(line)[:2])
print((description,period))
except ValueError:
# The line does not match
pass
yields
# ('12 items - Ironing Service', '11 Mar 2009 to 10 Apr 2009')
# ('Washing service (3 Shirt)', '23 Mar 2009')
The main workhorse here is of course the re pattern. Let's break it apart:
\d{1,2}\s+[a-zA-Z]{3}\s+\d{4} is the regexp for a date, the equivalent of tok_date_in_ddmmmyyyy. \d{1,2} matches one or two digits, \s+ matches one or more whitespaces, [a-zA-Z]{3} matches 3 letters, etc.
(?:\s+to\s+\d{1,2}\s+[a-zA-Z]{3}\s+\d{4})? is a regexp surrounded by (?:...).
This indicates a non-grouping regexp. Using this, no group (e.g. match.group(2)) is assigned to this regexp. This matters because date_pat.split() returns a list with each group being a member of the list. By suppressing the grouping, we keep the entire period 11 Mar 2009 to 10 Apr 2009 together. The question mark at the end indicates that this pattern may occur zero or once. This allows the regexp to match both
23 Mar 2009 and 11 Mar 2009 to 10 Apr 2009.
text.splitlines() splits text on \n.
date_pat.split('12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009')
splits the string on the date_pat regexp. The match is included in the returned list.
Thus we get:
['12 items - Ironing Service ', '11 Mar 2009 to 10 Apr 2009', '']
map(string.strip,date_pat.split(line)[:2]) prettifies the result.
If line does not match date_pat, then date_pat.split(line) returns [line,],
so
description,period=map(string.strip,date_pat.split(line)[:2])
raises a ValueError because we can't unpack a list with only one element into a 2-tuple. We catch this exception but simply pass on to the next line.
|
How to write the grammar for this in pyparsing: match a set of words but not containing a given pattern
|
I am new to Python and pyparsing. I need to accomplish the following.
My sample line of text is like this:
12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009
Washing service (3 Shirt) 23 Mar 2009
I need to extract the item description, period
tok_date_in_ddmmmyyyy = Combine(Word(nums,min=1,max=2)+ " " + Word(alphas, exact=3) + " " + Word(nums,exact=4))
tok_period = Combine((tok_date_in_ddmmmyyyy + " to " + tok_date_in_ddmmmyyyy)|tok_date_in_ddmmmyyyy)
tok_desc = Word(alphanums+"-()") but stop before tok_period
How to do this?
|
[
"I would suggest looking at SkipTo as the pyparsing class that is most appropriate, since you have a good definition of the unwanted text, but will accept pretty much anything before that. Here are a couple of ways to use SkipTo:\ntext = \"\"\"\\\n12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009\nWashing service (3 Shirt) 23 Mar 2009\"\"\"\n\n# using tok_period as defined in the OP\n\n# parse each line separately\nfor tx in text.splitlines():\n print SkipTo(tok_period).parseString(tx)[0]\n\n# or have pyparsing search through the whole input string using searchString\nfor [[td,_]] in SkipTo(tok_period,include=True).searchString(text):\n print td\n\nBoth for loops print the following:\n12 items - Ironing Service \nWashing service (3 Shirt) \n\n",
"M K Saravanan, this particular parsing problem is not so hard to do with good 'ole re:\nimport re\nimport string\n\ntext='''\n12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009\nWashing service (3 Shirt) 23 Mar 2009\nThis line does not match\n'''\n\ndate_pat=re.compile(\n r'(\\d{1,2}\\s+[a-zA-Z]{3}\\s+\\d{4}(?:\\s+to\\s+\\d{1,2}\\s+[a-zA-Z]{3}\\s+\\d{4})?)')\nfor line in text.splitlines():\n if line:\n try:\n description,period=map(string.strip,date_pat.split(line)[:2])\n print((description,period))\n except ValueError:\n # The line does not match\n pass\n\nyields\n# ('12 items - Ironing Service', '11 Mar 2009 to 10 Apr 2009')\n# ('Washing service (3 Shirt)', '23 Mar 2009')\n\nThe main workhorse here is of course the re pattern. Let's break it apart:\n\\d{1,2}\\s+[a-zA-Z]{3}\\s+\\d{4} is the regexp for a date, the equivalent of tok_date_in_ddmmmyyyy. \\d{1,2} matches one or two digits, \\s+ matches one or more whitespaces, [a-zA-Z]{3} matches 3 letters, etc.\n(?:\\s+to\\s+\\d{1,2}\\s+[a-zA-Z]{3}\\s+\\d{4})? is a regexp surrounded by (?:...).\nThis indicates a non-grouping regexp. Using this, no group (e.g. match.group(2)) is assigned to this regexp. This matters because date_pat.split() returns a list with each group being a member of the list. By suppressing the grouping, we keep the entire period 11 Mar 2009 to 10 Apr 2009 together. The question mark at the end indicates that this pattern may occur zero or once. This allows the regexp to match both\n23 Mar 2009 and 11 Mar 2009 to 10 Apr 2009.\ntext.splitlines() splits text on \\n.\ndate_pat.split('12 items - Ironing Service 11 Mar 2009 to 10 Apr 2009')\nsplits the string on the date_pat regexp. The match is included in the returned list.\nThus we get:\n['12 items - Ironing Service ', '11 Mar 2009 to 10 Apr 2009', '']\nmap(string.strip,date_pat.split(line)[:2]) prettifies the result.\nIf line does not match date_pat, then date_pat.split(line) returns [line,],\nso \ndescription,period=map(string.strip,date_pat.split(line)[:2])\nraises a ValueError because we can't unpack a list with only one element into a 2-tuple. We catch this exception but simply pass on to the next line.\n"
] |
[
5,
3
] |
[] |
[] |
[
"pyparsing",
"python"
] |
stackoverflow_0001805309_pyparsing_python.txt
|
Q:
How to pass this command to subprocess.call?
Command:
root@host:~#convert source.jpg -resize x500 -resize "500x<" -gravity center +repage target.jpg
Python code:
>> command_list = ['convert', 'source.jpg', '-resize', 'x500', '-resize', '\'500x<\'', '-gravity', 'center', 'target.jpg']
>> p = subprocess.call(command_list)
convert: invalid argument for option `'500x<'': -resize.
What's wrong in above code?
A:
Why the extra quotes on 500x<? Subprocess will correctly quote any arguments.
Keep in mind that the shell will NOT pass the outer quotes to the application, just the quoted value, but subprocess will pass the quotes if you force it to.
A:
Have you tried '"500x<"' instead of '\'500x<\''?
|
How to pass this command to subprocess.call?
|
Command:
root@host:~#convert source.jpg -resize x500 -resize "500x<" -gravity center +repage target.jpg
Python code:
>> command_list = ['convert', 'source.jpg', '-resize', 'x500', '-resize', '\'500x<\'', '-gravity', 'center', 'target.jpg']
>> p = subprocess.call(command_list)
convert: invalid argument for option `'500x<'': -resize.
What's wrong in above code?
|
[
"Why the extra quotes on 500x<? Subprocess will correctly quote any arguments. \nKeep in mind that the shell will NOT pass the outer quotes to the application, just the quoted value, but subprocess will pass the quotes if you force it to.\n",
"Have you tried '\"500x<\"' instead of '\\'500x<\\''?\n"
] |
[
5,
0
] |
[] |
[] |
[
"python",
"subprocess"
] |
stackoverflow_0001811683_python_subprocess.txt
|
Q:
Python wx (Python Card) logging subprocess output to window
There are similar questions to this one, but I'd like to see a clarified answer. I'm building a simple GUI with PythonCard to wrap a command line process. Specifically, it's a wrapper for a series of ANT Tasks and other custom operations so non-devs can use it.
I'd like to redirect the output of the subprocess to a TextArea in the window. It looks like the way to do this is to use subprocess.Popen(command, stdout=subprocess.PIPE) and load the output to a variable.
The question is how do I live update the window with the output of the subprocess? Any hints would be welcome
Thanks
A:
Just about every subprocess you can wrap will buffer its output unless you manage to fool it into believing it's actually connected to a terminal -- and subprocess can't do that. Rather, look into pexpect (runs well on every platform that lets you have a pseudoterminal, i.e., every platform except Microsoft Windows; on Windows you might try wexpect but I have no experience with the latter).
These modules give you the subprocess's output as soon as it's produced, and strive to fool the module into producing that output ASAP and without buffering, so they should make it easy for you to receive that output in real time and append it to the text field you want to keep updating.
A:
I was searching for a solution for this too. It turns out the solution is remarkably simple:
proc = subprocess.Popen("whatever program", cwd="startup dir", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
while True:
txt = proc.stdout.readline()
if not txt: break
txt=txt.replace("\r\n","\n").replace("\r\n","\n").replace("\\","\")
self.components.taStdout.appendText(txt)
|
Python wx (Python Card) logging subprocess output to window
|
There are similar questions to this one, but I'd like to see a clarified answer. I'm building a simple GUI with PythonCard to wrap a command line process. Specifically, it's a wrapper for a series of ANT Tasks and other custom operations so non-devs can use it.
I'd like to redirect the output of the subprocess to a TextArea in the window. It looks like the way to do this is to use subprocess.Popen(command, stdout=subprocess.PIPE) and load the output to a variable.
The question is how do I live update the window with the output of the subprocess? Any hints would be welcome
Thanks
|
[
"Just about every subprocess you can wrap will buffer its output unless you manage to fool it into believing it's actually connected to a terminal -- and subprocess can't do that. Rather, look into pexpect (runs well on every platform that lets you have a pseudoterminal, i.e., every platform except Microsoft Windows; on Windows you might try wexpect but I have no experience with the latter).\nThese modules give you the subprocess's output as soon as it's produced, and strive to fool the module into producing that output ASAP and without buffering, so they should make it easy for you to receive that output in real time and append it to the text field you want to keep updating.\n",
"I was searching for a solution for this too. It turns out the solution is remarkably simple:\n\nproc = subprocess.Popen(\"whatever program\", cwd=\"startup dir\", shell=True, \n stdout=subprocess.PIPE, stderr=subprocess.STDOUT )\n\nwhile True:\n\n txt = proc.stdout.readline()\n\n if not txt: break\n\n txt=txt.replace(\"\\r\\n\",\"\\n\").replace(\"\\r\\n\",\"\\n\").replace(\"\\\\\",\"\\\")\n\n self.components.taStdout.appendText(txt)\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"pythoncard",
"wxpython"
] |
stackoverflow_0001200610_python_pythoncard_wxpython.txt
|
Q:
Is it possible to unpack a tuple without using variables?
I'm using the os.path.split() function on a path in my program to get the filename and pathname of a file then passing them into another method, but my current solution seems rather ugly:
path = os.path.split(somefile)
some_class(path[0], path[1])
Is it possible to unpack the path tuple in a cleaner way within the call to some_class? Something like:
some_class(os.path.split(somefile).unpack())
Or should I simply be going about this another way? Maybe a more pythonic way?
A:
Yes, Python has argument list unpacking. Try this:
some_class(*os.path.split(somefile))
|
Is it possible to unpack a tuple without using variables?
|
I'm using the os.path.split() function on a path in my program to get the filename and pathname of a file then passing them into another method, but my current solution seems rather ugly:
path = os.path.split(somefile)
some_class(path[0], path[1])
Is it possible to unpack the path tuple in a cleaner way within the call to some_class? Something like:
some_class(os.path.split(somefile).unpack())
Or should I simply be going about this another way? Maybe a more pythonic way?
|
[
"Yes, Python has argument list unpacking. Try this:\nsome_class(*os.path.split(somefile))\n\n"
] |
[
14
] |
[] |
[] |
[
"iterable_unpacking",
"python",
"tuples"
] |
stackoverflow_0001812020_iterable_unpacking_python_tuples.txt
|
Q:
Processing (possibly) optional arguments in Python
I am working on a series of command line tools which connect to the same server and do related but different things. I'd like users to be able to have a single configuration file where they can place common arguments such as connection information that can be shared across all the tools. Ideally, I'd like something that does the following for me:
If the server address is specified at the command line use this and ignore any other values
If the server address is not specified at the command line but is in a config file that is specified at the command line use this address. Ignore any other values.
If the server address is not specified at the command line or a config file specified at the command, but is available in a in a config file in the user's home directory (say .myapprc), use this value.
If the server address is not specified in any of the above mechinisms exit with an error message.
The closest I've seen to this is the configparse module, which from what I can tell offers an option parser that will also look at config files, but does not seem to have the notion of "Must be specified somewhere" which I need.
Does anyone know of an existing module that can cover my use case above? If not, a simple extension to optparse, configparse, or some other module I have not reviewed would also be greatly appreciated.
A:
This-party module configparse is written to extend optparse from the standard Python library. As the optparse docs I pointed to mention, "optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either" (though it follows with a couple of URLs that show you ways to do it). Simplest is to use the default value functionality: specify a default value that's not actually a legal value (for something like a server's address, that's pretty easy) -- then, once options are processed, verify that the specified value is legal (which is a good idea anyway!-) and raise the appropriate exception otherwise.
A:
I've used opster's middleware feature together with SafeConfigParser to achieve a similar (but slightly simpler) effect as you ask. You have to implement the specific logic you described yourself, but it assists you enough to make it relatively painless. An example of opster's middleware use is in its test/test.py example.
A:
use a dict to store options to your program.
first parse the option file in the user's directory and store every options in a dict (configparse or any other module is welcome). then parse the command line (using any module you want, optparse might fit well), if an arguments specifies a config file, parse the specified file in a dict and update your options from what you read (dict.update is really handy to merge 2 dict). then store all other arguments into another dict, and merge them again (dict.update again...).
this way, you are sure that the dict in which you stored the options contains the value you want, which was either read from the user's file, from the specified config file or directly from the command line. if it does not contain a required value, exit with an error.
|
Processing (possibly) optional arguments in Python
|
I am working on a series of command line tools which connect to the same server and do related but different things. I'd like users to be able to have a single configuration file where they can place common arguments such as connection information that can be shared across all the tools. Ideally, I'd like something that does the following for me:
If the server address is specified at the command line use this and ignore any other values
If the server address is not specified at the command line but is in a config file that is specified at the command line use this address. Ignore any other values.
If the server address is not specified at the command line or a config file specified at the command, but is available in a in a config file in the user's home directory (say .myapprc), use this value.
If the server address is not specified in any of the above mechinisms exit with an error message.
The closest I've seen to this is the configparse module, which from what I can tell offers an option parser that will also look at config files, but does not seem to have the notion of "Must be specified somewhere" which I need.
Does anyone know of an existing module that can cover my use case above? If not, a simple extension to optparse, configparse, or some other module I have not reviewed would also be greatly appreciated.
|
[
"This-party module configparse is written to extend optparse from the standard Python library. As the optparse docs I pointed to mention, \"optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either\" (though it follows with a couple of URLs that show you ways to do it). Simplest is to use the default value functionality: specify a default value that's not actually a legal value (for something like a server's address, that's pretty easy) -- then, once options are processed, verify that the specified value is legal (which is a good idea anyway!-) and raise the appropriate exception otherwise.\n",
"I've used opster's middleware feature together with SafeConfigParser to achieve a similar (but slightly simpler) effect as you ask. You have to implement the specific logic you described yourself, but it assists you enough to make it relatively painless. An example of opster's middleware use is in its test/test.py example.\n",
"use a dict to store options to your program. \nfirst parse the option file in the user's directory and store every options in a dict (configparse or any other module is welcome). then parse the command line (using any module you want, optparse might fit well), if an arguments specifies a config file, parse the specified file in a dict and update your options from what you read (dict.update is really handy to merge 2 dict). then store all other arguments into another dict, and merge them again (dict.update again...).\nthis way, you are sure that the dict in which you stored the options contains the value you want, which was either read from the user's file, from the specified config file or directly from the command line. if it does not contain a required value, exit with an error.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"command_line",
"configparser",
"optparse",
"python"
] |
stackoverflow_0001811540_command_line_configparser_optparse_python.txt
|
Q:
Python ctypes and function calls
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.
I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:
from ctypes import cast, CFUNCTYPE, c_char_p, c_long
buffer = ''.join(map(chr, [ #0000000000000000 <add>:
0x55, # push %rbp
0x48, 0x89, 0xe5, # mov %rsp,%rbp
0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)
0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax
0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax
0xc9, # leaveq
0xc3, # retq
]))
fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long))
print fptr(1234)
Now, why does this script keeps doing segmentation fault whenever I run it?
I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text
But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?
A:
As vincent mentioned, this is due to the allocated page being marked as non executable. Newer processors support this functionality, and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory.
To get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below:
libc = CDLL('libc.so')
# Some constants
PROT_READ = 1
PROT_WRITE = 2
PROT_EXEC = 4
def executable_code(buffer):
"""Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.
The pointer should be freed with libc.free() when finished"""
buf = c_char_p(buffer)
size = len(buffer)
# Need to align to a page boundary, so use valloc
addr = libc.valloc(size)
addr = c_void_p(addr)
if 0 == addr:
raise Exception("Failed to allocate memory")
memmove(addr, buf, size)
if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):
raise Exception("Failed to set protection on buffer")
return addr
code_ptr = executable_code(buffer)
fptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))
print fptr(1234)
libc.free(code_ptr)
Note: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit.
Also note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).
A:
Done some research with my friend and found out this is a platform-specific issue. We suspect that on some platforms malloc mmaps memory without PROT_EXEC and on others it does.
Therefore it is necessary to change the protection level with mprotect afterwards.
Lame thing, took a while to find out what to do.
from ctypes import (
cast, CFUNCTYPE, c_long, sizeof, addressof, create_string_buffer, pythonapi
)
PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC = 0, 1, 2, 4
mprotect = pythonapi.mprotect
buffer = ''.join(map(chr, [ #0000000000000000 <add>:
0x55, # push %rbp
0x48, 0x89, 0xe5, # mov %rsp,%rbp
0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)
0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax
0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax
0xc9, # leaveq
0xc3, # retq
]))
pagesize = pythonapi.getpagesize()
cbuffer = create_string_buffer(buffer)#c_char_p(buffer)
addr = addressof(cbuffer)
size = sizeof(cbuffer)
mask = pagesize - 1
if mprotect(~mask&addr, mask&addr + size, PROT_READ|PROT_WRITE|PROT_EXEC) < 0:
print "mprotect failed?"
else:
fptr = cast(cbuffer, CFUNCTYPE(c_long, c_long))
print repr(fptr(1234))
A:
I think you can't freely execute any allocated memory without first setting it as executable. I never tried myself, but you might want to check the unix function mprotect:
http://linux.about.com/library/cmd/blcmdl2_mprotect.htm
VirtualProtect seems to do the same thing on windows :
http://msdn.microsoft.com/en-us/library/aa366898(VS.85).aspx
A:
Does python even allow such usage? I should learn it then...
I think the interpreter doesn't expect any register to be changed. Try saving the registers that you use inside the function if you plan to use your assembler output like this.
Btw, call convention of x86_64 is different than regular x86. You may have trouble if you lose stack pointer alignment and mix external objects generated with other tools.
A:
There's simpler approach I've figured only but recently that doesn't involve mprotect. Plainly mmap the executable space for program directly. These days python has a module for doing exactly this, though I didn't find way to get the address of the code. In short you'd allocate memory calling mmap instead of using string buffers and setting the execution flag indirectly. This is easier and safer, you can be sure only your code can be executed now.
|
Python ctypes and function calls
|
My friend produced a small proof-of-concept assembler that worked on x86. I decided to port it for x86_64 as well, but I immediately hit a problem.
I wrote a small piece of program in C, then compiled and objdumped the code. After that I inserted it to my python script, therefore the x86_64 code is correct:
from ctypes import cast, CFUNCTYPE, c_char_p, c_long
buffer = ''.join(map(chr, [ #0000000000000000 <add>:
0x55, # push %rbp
0x48, 0x89, 0xe5, # mov %rsp,%rbp
0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)
0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax
0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax
0xc9, # leaveq
0xc3, # retq
]))
fptr = cast(c_char_p(buffer), CFUNCTYPE(c_long, c_long))
print fptr(1234)
Now, why does this script keeps doing segmentation fault whenever I run it?
I have yet a question about mprotect and no execution flag. It is said to protect against most basic security exploits like buffer overruns. But what is the real reason it's in use? You could just keep on writing until you hit the .text, then inject your instructions into a nice, PROT_EXEC -area. Unless, of course, you use a write protection in .text
But then, why have that PROT_EXEC everywhere anyway? Wouldn't it just help tremendously that your .text section is write protected?
|
[
"As vincent mentioned, this is due to the allocated page being marked as non executable. Newer processors support this functionality, and its used as an added layer of security by OS's which support it. The idea is to protect against certain buffer overflow attacks. Eg. A common attack is to overflow a stack variable, rewriting the return address to point to code you have inserted. With a non-executable stack this now only produces a segfault, rather than control of the process. Similar attacks also exist for heap memory.\nTo get around it, you need to alter the protection. This can only be performed on page aligned memory, so you'll probably need to change your code to something like the below:\nlibc = CDLL('libc.so')\n\n# Some constants\nPROT_READ = 1\nPROT_WRITE = 2\nPROT_EXEC = 4\n\ndef executable_code(buffer):\n \"\"\"Return a pointer to a page-aligned executable buffer filled in with the data of the string provided.\n The pointer should be freed with libc.free() when finished\"\"\"\n\n buf = c_char_p(buffer)\n size = len(buffer)\n # Need to align to a page boundary, so use valloc\n addr = libc.valloc(size)\n addr = c_void_p(addr)\n\n if 0 == addr: \n raise Exception(\"Failed to allocate memory\")\n\n memmove(addr, buf, size)\n if 0 != libc.mprotect(addr, len(buffer), PROT_READ | PROT_WRITE | PROT_EXEC):\n raise Exception(\"Failed to set protection on buffer\")\n return addr\n\ncode_ptr = executable_code(buffer)\nfptr = cast(code_ptr, CFUNCTYPE(c_long, c_long))\nprint fptr(1234)\nlibc.free(code_ptr)\n\nNote: It may be a good idea to unset the executable flag before freeing the page. Most C libraries don't actually return the memory to the OS when done, but keep it in their own pool. This could mean they will reuse the page elsewhere without clearing the EXEC bit, bypassing the security benefit. \nAlso note that this is fairly non-portable. I've tested it on linux, but not on any other OS. It won't work on windows, buy may do on other unixes (BSD, OsX?).\n",
"Done some research with my friend and found out this is a platform-specific issue. We suspect that on some platforms malloc mmaps memory without PROT_EXEC and on others it does.\nTherefore it is necessary to change the protection level with mprotect afterwards.\nLame thing, took a while to find out what to do.\nfrom ctypes import (\n cast, CFUNCTYPE, c_long, sizeof, addressof, create_string_buffer, pythonapi\n)\n\nPROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC = 0, 1, 2, 4\nmprotect = pythonapi.mprotect\n\nbuffer = ''.join(map(chr, [ #0000000000000000 <add>:\n 0x55, # push %rbp\n 0x48, 0x89, 0xe5, # mov %rsp,%rbp\n 0x48, 0x89, 0x7d, 0xf8, # mov %rdi,-0x8(%rbp)\n 0x48, 0x8b, 0x45, 0xf8, # mov -0x8(%rbp),%rax\n 0x48, 0x83, 0xc0, 0x0a, # add $0xa,%rax\n 0xc9, # leaveq \n 0xc3, # retq\n]))\n\npagesize = pythonapi.getpagesize()\ncbuffer = create_string_buffer(buffer)#c_char_p(buffer)\naddr = addressof(cbuffer)\nsize = sizeof(cbuffer)\nmask = pagesize - 1\nif mprotect(~mask&addr, mask&addr + size, PROT_READ|PROT_WRITE|PROT_EXEC) < 0:\n print \"mprotect failed?\"\nelse:\n fptr = cast(cbuffer, CFUNCTYPE(c_long, c_long))\n print repr(fptr(1234))\n\n",
"I think you can't freely execute any allocated memory without first setting it as executable. I never tried myself, but you might want to check the unix function mprotect:\nhttp://linux.about.com/library/cmd/blcmdl2_mprotect.htm\nVirtualProtect seems to do the same thing on windows :\nhttp://msdn.microsoft.com/en-us/library/aa366898(VS.85).aspx\n",
"Does python even allow such usage? I should learn it then...\nI think the interpreter doesn't expect any register to be changed. Try saving the registers that you use inside the function if you plan to use your assembler output like this.\nBtw, call convention of x86_64 is different than regular x86. You may have trouble if you lose stack pointer alignment and mix external objects generated with other tools.\n",
"There's simpler approach I've figured only but recently that doesn't involve mprotect. Plainly mmap the executable space for program directly. These days python has a module for doing exactly this, though I didn't find way to get the address of the code. In short you'd allocate memory calling mmap instead of using string buffers and setting the execution flag indirectly. This is easier and safer, you can be sure only your code can be executed now.\n"
] |
[
8,
7,
4,
0,
0
] |
[] |
[] |
[
"assembly",
"c",
"ctypes",
"python",
"x86_64"
] |
stackoverflow_0000275207_assembly_c_ctypes_python_x86_64.txt
|
Q:
Creating hierarchy tree from dictionary of pages' contents
The following key:value pairs are 'page' and 'page contents'.
{
'section-a.html':{'contents':'section-b.html section-c.html section-d.html'},
'section-b.html':{'contents':'section-d.html section-e.html'},
'section-c.html':{'contents':'product-a.html product-b.html product-c.html product-d.html'},
'section-d.html':{'contents':'product-a.html product-c.html'},
'section-e.html':{'contents':'product-b.html product-d.html'},
'product-a.html':{'contents':''},
'product-b.html':{'contents':''},
'product-c.html':{'contents':''},
'product-d.html':{'contents':''}
}
For any given 'item' how could I find the path(s) to said item? With my very limited knowledge of data structures in most cases, I'm assuming this would be a hierarchy tree. Please correct me if I'm wrong!
UPDATE: My apologies, I should have been more clear about the data and my expected outcome.
Assuming 'page-a' is an index, each 'page' is literally a page appearing on a website, where as each 'item' is something like a product page that would appear on Amazon, Newegg, etc.
Thus, my expected output for 'item-d' would be a path (or paths) to that item.
For example (delimiter is arbitrary, for illustration here):
item-d has the following paths:
page-a > page-b > page-e > item-d
page-a > page-c > item-d
UPDATE2: Updated my original dict to provide more accurate and real data. '.html' added for clarification.
A:
Here's a simple approach -- it's O(N squared), so, not all that highly scalable, but will serve you well for a reasonable book size (if you have, say, millions of pages, you need to be thinking about a very different and less simple approach;-).
First, make a more usable dict, mapping page to set of contents: e.g., if the original dict is d, make another dict mud as:
mud = dict((p, set(d[p]['contents'].split())) for p in d)
Then, make the dict mapping each page to its parent pages:
parent = dict((p, [k for k in mud if p in mud[k]]) for p in mud)
Here, I'm using lists of parent pages (sets would be fine too), but that's OK for pages with 0 or 1 parents as in your example, too -- you'll just be using an empty list to mean "no parent", else a list with the parent as the one and only item. This should be an acyclic directed graph (if you're in doubt, you can check, of course, but I'm skipping that check).
Now, given a page, finding the paths up its parent(s) to a parentless-parent ("root page") simply require "walking" the parent dict. E.g., in the 0/1 parent case:
path = [page]
while parent[path[-1]]:
path.append(parent[path[-1]][0])
If you can clarify your specs better (ranges of number of pages per book, number of parents per page, and so on), this code can no doubt be refined, but as a start I hope it can help.
Edit: as the OP clarified that cases with > 1 parent (and so, multiple paths) are indeed of interest, let me show how do deal with that:
partial_paths = [ [page] ]
while partial_paths:
path = partial_paths.pop()
if parent[path[-1]]:
# add as many partial paths as open from here
for p in parent[path[-1]]:
partial_paths.append(path + [p])
else:
# we've reached a root (parentless node)
print(path)
Of course, instead of printing, you can yield each path when it reaches a root (making the function whose body this is into a generator), or otherwise treat it in whatever way you require.
Edit again: a commenter is worried about cycles in the graph. If that worry's warranted, it's not hard to keep track of nodes already seen in a path and detect and warn about any cycles. Fastest is to keep a set alongside each list representing a partial path (we need the list for ordering, but checking for membership is O(1) in sets vs O(N) in lists):
partial_paths = [ ([page], set([page])) ]
while partial_paths:
path, pset = partial_paths.pop()
if parent[path[-1]]:
# add as many partial paths as open from here
for p in parent[path[-1]]:
if p in pset:
print('Cycle: %s (%s)' % (path, p))
continue
partial_paths.append((path + [p], pset.union([p])))
else:
# we've reached a root (parentless node)
print('Path: %s' % (path,))
It's probably worthwhile, for clarity, packing the list and set representing a partial path into a small utility class Path with suitable methods.
A:
Here's an illustration for your question. It is easier to reason about graphs when you have a picture.
First, abbreviate the data:
#!/usr/bin/perl -pe
s/section-([a-e])\.html/uc$1/eg; s/product-([a-e])\.html/$1/g
Result:
# graph as adj list
DATA = {
'A':{'contents':'B C D'},
'B':{'contents':'D E'},
'C':{'contents':'a b c d'},
'D':{'contents':'a c'},
'E':{'contents':'b d'},
'a':{'contents':''},
'b':{'contents':''},
'c':{'contents':''},
'd':{'contents':''}
}
Convert to graphviz's format:
with open('data.dot', 'w') as f:
print >> f, 'digraph {'
for node, v in data.iteritems():
for child in v['contents'].split():
print >> f, '%s -> %s;' % (node, child),
if v['contents']: # don't print empty lines
print >> f
print >> f, '}'
Result:
digraph {
A -> C; A -> B; A -> D;
C -> a; C -> b; C -> c; C -> d;
B -> E; B -> D;
E -> b; E -> d;
D -> a; D -> c;
}
Plot the graph:
$ dot -Tpng -O data.dot
A:
EDIT With the question explained a bit better I think the following might be what you need, or could at least provide something of a starting point.
data = {
'section-a.html':{'contents':'section-b.html section-c.html section-d.html'},
'section-b.html':{'contents':'section-d.html section-e.html'},
'section-c.html':{'contents':\
'product-a.html product-b.html product-c.html product-d.html'},
'section-d.html':{'contents':'product-a.html product-c.html'},
'section-e.html':{'contents':'product-b.html product-d.html'},
'product-a.html':{'contents':''},
'product-b.html':{'contents':''},
'product-c.html':{'contents':''},
'product-d.html':{'contents':''}
}
def findSingleItemInData(item):
return map( lambda x: (item, x), \
[key for key in data if data[key]['contents'].find(item) <> -1])
def trace(text):
searchResult = findSingleItemInData(text)
if not searchResult:
return text
retval = []
for item in searchResult:
retval.append([text, trace(item[-1])])
return retval
print trace('product-d.html')
OLD
I don't really know what you expect to see, but maybe something like
this will work.
data = {
'page-a':{'contents':'page-b page-c'},
'page-b':{'contents':'page-d page-e'},
'page-c':{'contents':'item-a item-b item-c item-d'},
'page-d':{'contents':'item-a item-c'},
'page-e':{'contents':'item-b item-d'}
}
itemToFind = 'item-c'
for key in data:
for index, item in enumerate(data[key]['contents'].split()):
if item == itemToFind:
print key, 'at position', index
It would be easier, and I think more correct, if you'd use a slightly
different data structure:
data = {
'page-a':{'contents':['page-b', 'page-c']},
'page-b':{'contents':['page-d', 'page-e']},
'page-c':{'contents':['item-a', 'item-b item-c item-d']},
'page-d':{'contents':['item-a', 'item-c']},
'page-e':{'contents':['item-b', 'item-d']}
}
Then you wouldn't need to split.
Given that last case, it can even be expressed a bit shorter:
for key in data:
print [ (key, index, value) for index,value in \
enumerate(data[key]['contents']) if value == 'item-c' ]
And even shorter, with the empty lists removed:
print filter(None, [[ (key, index, value) for index,value in \
enumerate(data[key]['contents']) if value == 'item-c' ] for key in data])
That should be a single line, but I used \ as line break indicator so it can be read
without scrollbars.
|
Creating hierarchy tree from dictionary of pages' contents
|
The following key:value pairs are 'page' and 'page contents'.
{
'section-a.html':{'contents':'section-b.html section-c.html section-d.html'},
'section-b.html':{'contents':'section-d.html section-e.html'},
'section-c.html':{'contents':'product-a.html product-b.html product-c.html product-d.html'},
'section-d.html':{'contents':'product-a.html product-c.html'},
'section-e.html':{'contents':'product-b.html product-d.html'},
'product-a.html':{'contents':''},
'product-b.html':{'contents':''},
'product-c.html':{'contents':''},
'product-d.html':{'contents':''}
}
For any given 'item' how could I find the path(s) to said item? With my very limited knowledge of data structures in most cases, I'm assuming this would be a hierarchy tree. Please correct me if I'm wrong!
UPDATE: My apologies, I should have been more clear about the data and my expected outcome.
Assuming 'page-a' is an index, each 'page' is literally a page appearing on a website, where as each 'item' is something like a product page that would appear on Amazon, Newegg, etc.
Thus, my expected output for 'item-d' would be a path (or paths) to that item.
For example (delimiter is arbitrary, for illustration here):
item-d has the following paths:
page-a > page-b > page-e > item-d
page-a > page-c > item-d
UPDATE2: Updated my original dict to provide more accurate and real data. '.html' added for clarification.
|
[
"Here's a simple approach -- it's O(N squared), so, not all that highly scalable, but will serve you well for a reasonable book size (if you have, say, millions of pages, you need to be thinking about a very different and less simple approach;-).\nFirst, make a more usable dict, mapping page to set of contents: e.g., if the original dict is d, make another dict mud as:\nmud = dict((p, set(d[p]['contents'].split())) for p in d)\n\nThen, make the dict mapping each page to its parent pages:\nparent = dict((p, [k for k in mud if p in mud[k]]) for p in mud)\n\nHere, I'm using lists of parent pages (sets would be fine too), but that's OK for pages with 0 or 1 parents as in your example, too -- you'll just be using an empty list to mean \"no parent\", else a list with the parent as the one and only item. This should be an acyclic directed graph (if you're in doubt, you can check, of course, but I'm skipping that check).\nNow, given a page, finding the paths up its parent(s) to a parentless-parent (\"root page\") simply require \"walking\" the parent dict. E.g., in the 0/1 parent case:\npath = [page]\nwhile parent[path[-1]]:\n path.append(parent[path[-1]][0])\n\nIf you can clarify your specs better (ranges of number of pages per book, number of parents per page, and so on), this code can no doubt be refined, but as a start I hope it can help.\nEdit: as the OP clarified that cases with > 1 parent (and so, multiple paths) are indeed of interest, let me show how do deal with that:\npartial_paths = [ [page] ]\nwhile partial_paths:\n path = partial_paths.pop()\n if parent[path[-1]]:\n # add as many partial paths as open from here\n for p in parent[path[-1]]:\n partial_paths.append(path + [p])\n else:\n # we've reached a root (parentless node)\n print(path)\n\nOf course, instead of printing, you can yield each path when it reaches a root (making the function whose body this is into a generator), or otherwise treat it in whatever way you require.\nEdit again: a commenter is worried about cycles in the graph. If that worry's warranted, it's not hard to keep track of nodes already seen in a path and detect and warn about any cycles. Fastest is to keep a set alongside each list representing a partial path (we need the list for ordering, but checking for membership is O(1) in sets vs O(N) in lists):\npartial_paths = [ ([page], set([page])) ]\nwhile partial_paths:\n path, pset = partial_paths.pop()\n if parent[path[-1]]:\n # add as many partial paths as open from here\n for p in parent[path[-1]]:\n if p in pset:\n print('Cycle: %s (%s)' % (path, p))\n continue\n partial_paths.append((path + [p], pset.union([p])))\n else:\n # we've reached a root (parentless node)\n print('Path: %s' % (path,))\n\nIt's probably worthwhile, for clarity, packing the list and set representing a partial path into a small utility class Path with suitable methods.\n",
"Here's an illustration for your question. It is easier to reason about graphs when you have a picture.\nFirst, abbreviate the data:\n#!/usr/bin/perl -pe\ns/section-([a-e])\\.html/uc$1/eg; s/product-([a-e])\\.html/$1/g\n\nResult:\n# graph as adj list\nDATA = {\n 'A':{'contents':'B C D'},\n 'B':{'contents':'D E'},\n 'C':{'contents':'a b c d'},\n 'D':{'contents':'a c'},\n 'E':{'contents':'b d'},\n 'a':{'contents':''},\n 'b':{'contents':''},\n 'c':{'contents':''},\n 'd':{'contents':''}\n}\n\nConvert to graphviz's format:\nwith open('data.dot', 'w') as f:\n print >> f, 'digraph {'\n for node, v in data.iteritems():\n for child in v['contents'].split():\n print >> f, '%s -> %s;' % (node, child),\n if v['contents']: # don't print empty lines\n print >> f\n print >> f, '}'\n\nResult:\ndigraph {\nA -> C; A -> B; A -> D;\nC -> a; C -> b; C -> c; C -> d;\nB -> E; B -> D;\nE -> b; E -> d;\nD -> a; D -> c;\n}\n\nPlot the graph:\n\n$ dot -Tpng -O data.dot\n\n\n",
"EDIT With the question explained a bit better I think the following might be what you need, or could at least provide something of a starting point.\ndata = {\n 'section-a.html':{'contents':'section-b.html section-c.html section-d.html'},\n 'section-b.html':{'contents':'section-d.html section-e.html'},\n 'section-c.html':{'contents':\\\n 'product-a.html product-b.html product-c.html product-d.html'},\n 'section-d.html':{'contents':'product-a.html product-c.html'},\n 'section-e.html':{'contents':'product-b.html product-d.html'},\n 'product-a.html':{'contents':''},\n 'product-b.html':{'contents':''},\n 'product-c.html':{'contents':''},\n 'product-d.html':{'contents':''}\n}\n\ndef findSingleItemInData(item):\n return map( lambda x: (item, x), \\\n [key for key in data if data[key]['contents'].find(item) <> -1])\n\ndef trace(text):\n searchResult = findSingleItemInData(text)\n if not searchResult:\n return text\n\n retval = [] \n for item in searchResult:\n retval.append([text, trace(item[-1])]) \n\n return retval\n\nprint trace('product-d.html')\n\nOLD\nI don't really know what you expect to see, but maybe something like\nthis will work.\ndata = {\n 'page-a':{'contents':'page-b page-c'},\n 'page-b':{'contents':'page-d page-e'},\n 'page-c':{'contents':'item-a item-b item-c item-d'},\n 'page-d':{'contents':'item-a item-c'},\n 'page-e':{'contents':'item-b item-d'}\n}\n\nitemToFind = 'item-c'\n\nfor key in data:\n for index, item in enumerate(data[key]['contents'].split()):\n if item == itemToFind:\n print key, 'at position', index\n\nIt would be easier, and I think more correct, if you'd use a slightly\ndifferent data structure:\n data = {\n 'page-a':{'contents':['page-b', 'page-c']},\n 'page-b':{'contents':['page-d', 'page-e']},\n 'page-c':{'contents':['item-a', 'item-b item-c item-d']},\n 'page-d':{'contents':['item-a', 'item-c']},\n 'page-e':{'contents':['item-b', 'item-d']}\n }\n\nThen you wouldn't need to split.\nGiven that last case, it can even be expressed a bit shorter:\nfor key in data:\n print [ (key, index, value) for index,value in \\\n enumerate(data[key]['contents']) if value == 'item-c' ]\n\nAnd even shorter, with the empty lists removed:\nprint filter(None, [[ (key, index, value) for index,value in \\ \n enumerate(data[key]['contents']) if value == 'item-c' ] for key in data])\n\nThat should be a single line, but I used \\ as line break indicator so it can be read\nwithout scrollbars.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"data_structures",
"hierarchical_trees",
"python",
"tree"
] |
stackoverflow_0001809758_data_structures_hierarchical_trees_python_tree.txt
|
Q:
Replacing elements with lxml.html
I'm fairly new to lxml and HTML Parsers as a whole.
I was wondering if there is a way to replace an element within a tree with another element...
For example I have:
body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """
doc = lxml.html.fromstring(body)
codeblocks = doc.cssselect('code')
for block in codeblocks:
lexer = guess_lexer(block.text_content())
hilited = highlight(block.text_content(), lexer, HtmlFormatter())
doc.replace(block, hilited)
I want to do something along those lines, but this results in a "TypeError" because "hilited" isn't an lxml.etree._Element.
Is this feasible?
Regards,
A:
Regarding lxml,
In doc.replace(block, hilited)
block is the lxml's Element object, hilited is string, you cannot replace that.
There is 2 ways to do that
block.text=hilited
or
body=body.replace(block.text,hilited)
A:
If you're new to python HTML parsers, you might try out BeautifulSoup, a html/xml parser, which lets you modify the parse tree easily.
|
Replacing elements with lxml.html
|
I'm fairly new to lxml and HTML Parsers as a whole.
I was wondering if there is a way to replace an element within a tree with another element...
For example I have:
body = """<code> def function(arg): print arg </code> Blah blah blah <code> int main() { return 0; } </code> """
doc = lxml.html.fromstring(body)
codeblocks = doc.cssselect('code')
for block in codeblocks:
lexer = guess_lexer(block.text_content())
hilited = highlight(block.text_content(), lexer, HtmlFormatter())
doc.replace(block, hilited)
I want to do something along those lines, but this results in a "TypeError" because "hilited" isn't an lxml.etree._Element.
Is this feasible?
Regards,
|
[
"Regarding lxml,\nIn doc.replace(block, hilited)\nblock is the lxml's Element object, hilited is string, you cannot replace that.\nThere is 2 ways to do that\nblock.text=hilited \n\nor\nbody=body.replace(block.text,hilited)\n\n",
"If you're new to python HTML parsers, you might try out BeautifulSoup, a html/xml parser, which lets you modify the parse tree easily.\n"
] |
[
6,
1
] |
[] |
[] |
[
"lxml",
"python"
] |
stackoverflow_0001812764_lxml_python.txt
|
Q:
What should i use for a Remote Desktop Control?
Hi everybody i'm new to stackoverflow and to python programming :-)
Can somebody point me in the right direction or suggest me a good way to do this..?
The software I'd like to write is a kind of "multiple remote control", it has:
One Server ... whose task is to send his screen to all the clients
Many Clients ... they show the Server's screen and they are all able to control it (there exist a lot of remote control applications which can do this,but not all the clients together i think .. practically one server with many mice :p .. however all the clients will be managed by the server)
Given that I'm new to python i started looking and using these libraries:
wxWidget for the gui
Twisted for the network connection, because it's an easy way to implement a multicast UDP .. but is udp the right choise to send images to all the clients? =/
PIL (Python Imaging Libary) images stuff and to grab the screenshots on the Server machine to send to the clients .. this is the point where I stopped to think to all the possible solutions ... (I wasn't able to send the image to the client, I tried converting it to string but the UDP message was not that big :) )
I've seen many suggest the use of a VNC application .. is it easy to develop my software as described around it (actually i have no idea how..), or grabbing the screen continuously with PIL and sending somehow the images to the clients is an acceptable solution?
Thanks in advance for any help :-)
A:
Take a look at the VNC viewer implemented in Python.
A:
Teamtalk is a Python IM software that also has Remote Desktop access. You can download the source and look at the implementation.
|
What should i use for a Remote Desktop Control?
|
Hi everybody i'm new to stackoverflow and to python programming :-)
Can somebody point me in the right direction or suggest me a good way to do this..?
The software I'd like to write is a kind of "multiple remote control", it has:
One Server ... whose task is to send his screen to all the clients
Many Clients ... they show the Server's screen and they are all able to control it (there exist a lot of remote control applications which can do this,but not all the clients together i think .. practically one server with many mice :p .. however all the clients will be managed by the server)
Given that I'm new to python i started looking and using these libraries:
wxWidget for the gui
Twisted for the network connection, because it's an easy way to implement a multicast UDP .. but is udp the right choise to send images to all the clients? =/
PIL (Python Imaging Libary) images stuff and to grab the screenshots on the Server machine to send to the clients .. this is the point where I stopped to think to all the possible solutions ... (I wasn't able to send the image to the client, I tried converting it to string but the UDP message was not that big :) )
I've seen many suggest the use of a VNC application .. is it easy to develop my software as described around it (actually i have no idea how..), or grabbing the screen continuously with PIL and sending somehow the images to the clients is an acceptable solution?
Thanks in advance for any help :-)
|
[
"Take a look at the VNC viewer implemented in Python.\n",
"Teamtalk is a Python IM software that also has Remote Desktop access. You can download the source and look at the implementation.\n"
] |
[
4,
2
] |
[] |
[] |
[
"python",
"python_imaging_library",
"twisted"
] |
stackoverflow_0001812890_python_python_imaging_library_twisted.txt
|
Q:
I want to develop a framework in Python for desktop based applications. How should I go about it?
I want to develop a desktop application framework in Python, much like QT, but how to go about it? Any tutorials or links related to it would be helpful!
A:
There is so many great freameworks like wxPython (Tutorial), PyQt (Tutorial), PyGtk (Tutorial) already.
You just need to try your favorite one.
A:
You can get a pretty comprehensive list of Gui programming frameworks for Python here, http://wiki.python.org/moin/GuiProgramming
A:
theres WxPython tutorial http://www.wxpython.org/tutorial.php
or PyQt http://zetcode.com/tutorials/pyqt4/
or the ever stylish Tk http://www.pythonware.com/library/tkinter/introduction/
A:
Well the best way to start is to look at the source code of the framework the other answers are talking about.
First, try to use them all to build the same application with the functionalities you expect from a framework. Them, look at how it works under the hood.
Secondly, build your framework, starting by writing your first widgets, then notice the problems with your current architecture, and re factor. Start again, until you have something stable and usable.
Eventually, find out this was nice as training experience, but useless as a contribution to the software communities since you will never reach out the qualities of existing tools.
Then give up and try to code your own MMORPG.
|
I want to develop a framework in Python for desktop based applications. How should I go about it?
|
I want to develop a desktop application framework in Python, much like QT, but how to go about it? Any tutorials or links related to it would be helpful!
|
[
"There is so many great freameworks like wxPython (Tutorial), PyQt (Tutorial), PyGtk (Tutorial) already.\nYou just need to try your favorite one.\n",
"You can get a pretty comprehensive list of Gui programming frameworks for Python here, http://wiki.python.org/moin/GuiProgramming \n",
"theres WxPython tutorial http://www.wxpython.org/tutorial.php\nor PyQt http://zetcode.com/tutorials/pyqt4/\nor the ever stylish Tk http://www.pythonware.com/library/tkinter/introduction/\n",
"Well the best way to start is to look at the source code of the framework the other answers are talking about.\nFirst, try to use them all to build the same application with the functionalities you expect from a framework. Them, look at how it works under the hood.\nSecondly, build your framework, starting by writing your first widgets, then notice the problems with your current architecture, and re factor. Start again, until you have something stable and usable.\nEventually, find out this was nice as training experience, but useless as a contribution to the software communities since you will never reach out the qualities of existing tools.\nThen give up and try to code your own MMORPG.\n"
] |
[
4,
3,
2,
2
] |
[] |
[] |
[
"desktop",
"frameworks",
"python"
] |
stackoverflow_0001811940_desktop_frameworks_python.txt
|
Q:
Making a Python script Object-Oriented
I'm writing an application in Python that is going to have a lot of different functions, so logically I thought it would be best to split up my script into different modules. Currently my script reads in a text file that contains code which has been converted into tokens and spellings. The script then reconstructs the code into a string, with blank lines where comments would have been in the original code.
I'm having a problem making the script object-oriented though. Whatever I try I can't seem to get the program running the same way it would as if it was just a single script file. Ideally I'd like to have two script files, one that contains a class and function that cleans and reconstructs the file. The second script would simply call the function from the class in the other file on a file given as an argument from the command line. This is my current script:
import sys
tokenList = open(sys.argv[1], 'r')
cleanedInput = ''
prevLine = 0
for line in tokenList:
if line.startswith('LINE:'):
lineNo = int(line.split(':', 1)[1].strip())
diff = lineNo - prevLine - 1
if diff == 0:
cleanedInput += '\n'
if diff == 1:
cleanedInput += '\n\n'
else:
cleanedInput += '\n' * diff
prevLine = lineNo
continue
cleanedLine = line.split(':', 1)[1].strip()
cleanedInput += cleanedLine + ' '
print cleanedInput
After following Alex Martelli advice below, I now have the following code which gives me the same output as my original code.
def main():
tokenList = open(sys.argv[1], 'r')
cleanedInput = []
prevLine = 0
for line in tokenList:
if line.startswith('LINE:'):
lineNo = int(line.split(':', 1)[1].strip())
diff = lineNo - prevLine - 1
if diff == 0:
cleanedInput.append('\n')
if diff == 1:
cleanedInput.append('\n\n')
else:
cleanedInput.append('\n' * diff)
prevLine = lineNo
continue
cleanedLine = line.split(':', 1)[1].strip()
cleanedInput.append(cleanedLine + ' ')
print cleanedInput
if __name__ == '__main__':
main()
I would still like to split my code into multiple modules though. A 'cleaned file' in my program will have other functions performed on it so naturally a cleaned file should be a class in its own right?
A:
To speed up your existing code measurably, add def main(): before the assignment to tokenList, indent everything after that 4 spaces, and at the end put the usual idiom
if __name__ == '__main__':
main()
(The guard is not actually necessary, but it's a good habit to have nevertheless since, for scripts with reusable functions, it makes them importable from other modules).
This has little to do with "object oriented" anything: it's simply faster, in Python, to keep all your substantial code in functions, not as top-level module code.
Second speedup, change cleanedInput into a list, i.e., its first assignment should be = [], and wherever you now have +=, use .append instead. At the end, ''.join(cleanedInput) to get the final resulting string. This makes your code take linear time as a function of input size (O(N) is the normal way of expressing this) while it currently takes quadratic time (O(N squared)).
Then, correctness: the two statements right after continue never execute. Do you need them or not? Remove them (and the continue) if not needed, remove the continue if those two statements are actually needed. And the tests starting with if diff will fail dramatically unless the previous if was executed, because diff would be undefined then. Does your code as posted perhaps have indentation errors, i.e., is the indentation of what you posted different from that of your actual code?
Considering these important needed enhancements, and the fact that it's hard to see what advantage you are pursuing in making this tiny code OO (and/or modular), I suggest clarifying the indenting / correctness situation, applying the enhancements I've proposed, and leaving it at that;-).
Edit: as the OP has now applied most of my suggestions, let me follow up with one reasonable way to hive off most functionality to a class in a separate module. In a new file, for example foobar.py, in the same directory as the original script (or in site-packages, or elsewhere on sys.path), place this code:
def token_of(line):
return line.partition(':')[-1].strip()
class FileParser(object):
def __init__(self, filename):
self.tokenList = open(filename, 'r')
def cleaned_input(self):
cleanedInput = []
prevLine = 0
for line in self.tokenList:
if line.startswith('LINE:'):
lineNo = int(token_of(line))
diff = lineNo - prevLine - 1
cleanedInput.append('\n' * (diff if diff>1 else diff+1))
prevLine = lineNo
else:
cleanedLine = token_of(line)
cleanedInput.append(cleanedLine + ' ')
return cleanedInput
Your main script then becomes just:
import sys
import foobar
def main():
thefile = foobar.FileParser(sys.argv[1])
print thefile.cleaned_input()
if __name__ == '__main__':
main()
A:
When I do this particular refactoring, I usually start with an initial transformation within the first file. Step 1: move the functionality into a method in a new class. Step 2: add
the magic invocation below to get the file to run like a script again:
class LineCleaner:
def cleanFile(filename):
cleanInput = ""
prevLine = 0
for line in open(filename,'r'):
<... as in original script ..>
if __name__ == '__main__':
cleaner = LineCleaner()
cleaner.cleanFile(sys.argv[1])
A:
You can get away with creating a function and putting all your logic in it. For full "object orientedness" though, you can do something like this:
ps - your posted code has a bug on the continue line - it is always executed and the last 2 lines will never execute.
class Cleaner:
def __init__(...):
...init logic...
def Clean(self):
for line in open(self.tokenList):
...cleaning logic...
return cleanedInput
def main(argv):
cleaner = Cleaner(argv[1])
print cleaner.Clean()
return 0
if '__main__' == __name__:
sys.exit(main(sys.argv))
A:
If presented code is all code Just don't add any class !!
Your code is too simply for that !!
OOP approach would add unnecessary complexity.
But if still wont.
Put all code into function eg.
def parse_tokenized_input(file):
tokenList = open(file, 'r')
cleanedInput = ''
prevLine = 0
#rest of code
at end add:
if __name__ == '__main__':
parse_tokenized_input(sys.argv[1])
If code works correct put def of function to new file (and all needed imports!)
eg. mymodyle.py
your script now will be:
from mymodule.py import parse_tokenized_input
if __name__ == '__main__':
parse_tokenized_input(sys.argv[1])
Oh and think out better name for your function and module (module should have general name).
|
Making a Python script Object-Oriented
|
I'm writing an application in Python that is going to have a lot of different functions, so logically I thought it would be best to split up my script into different modules. Currently my script reads in a text file that contains code which has been converted into tokens and spellings. The script then reconstructs the code into a string, with blank lines where comments would have been in the original code.
I'm having a problem making the script object-oriented though. Whatever I try I can't seem to get the program running the same way it would as if it was just a single script file. Ideally I'd like to have two script files, one that contains a class and function that cleans and reconstructs the file. The second script would simply call the function from the class in the other file on a file given as an argument from the command line. This is my current script:
import sys
tokenList = open(sys.argv[1], 'r')
cleanedInput = ''
prevLine = 0
for line in tokenList:
if line.startswith('LINE:'):
lineNo = int(line.split(':', 1)[1].strip())
diff = lineNo - prevLine - 1
if diff == 0:
cleanedInput += '\n'
if diff == 1:
cleanedInput += '\n\n'
else:
cleanedInput += '\n' * diff
prevLine = lineNo
continue
cleanedLine = line.split(':', 1)[1].strip()
cleanedInput += cleanedLine + ' '
print cleanedInput
After following Alex Martelli advice below, I now have the following code which gives me the same output as my original code.
def main():
tokenList = open(sys.argv[1], 'r')
cleanedInput = []
prevLine = 0
for line in tokenList:
if line.startswith('LINE:'):
lineNo = int(line.split(':', 1)[1].strip())
diff = lineNo - prevLine - 1
if diff == 0:
cleanedInput.append('\n')
if diff == 1:
cleanedInput.append('\n\n')
else:
cleanedInput.append('\n' * diff)
prevLine = lineNo
continue
cleanedLine = line.split(':', 1)[1].strip()
cleanedInput.append(cleanedLine + ' ')
print cleanedInput
if __name__ == '__main__':
main()
I would still like to split my code into multiple modules though. A 'cleaned file' in my program will have other functions performed on it so naturally a cleaned file should be a class in its own right?
|
[
"To speed up your existing code measurably, add def main(): before the assignment to tokenList, indent everything after that 4 spaces, and at the end put the usual idiom\nif __name__ == '__main__':\n main()\n\n(The guard is not actually necessary, but it's a good habit to have nevertheless since, for scripts with reusable functions, it makes them importable from other modules).\nThis has little to do with \"object oriented\" anything: it's simply faster, in Python, to keep all your substantial code in functions, not as top-level module code.\nSecond speedup, change cleanedInput into a list, i.e., its first assignment should be = [], and wherever you now have +=, use .append instead. At the end, ''.join(cleanedInput) to get the final resulting string. This makes your code take linear time as a function of input size (O(N) is the normal way of expressing this) while it currently takes quadratic time (O(N squared)).\nThen, correctness: the two statements right after continue never execute. Do you need them or not? Remove them (and the continue) if not needed, remove the continue if those two statements are actually needed. And the tests starting with if diff will fail dramatically unless the previous if was executed, because diff would be undefined then. Does your code as posted perhaps have indentation errors, i.e., is the indentation of what you posted different from that of your actual code?\nConsidering these important needed enhancements, and the fact that it's hard to see what advantage you are pursuing in making this tiny code OO (and/or modular), I suggest clarifying the indenting / correctness situation, applying the enhancements I've proposed, and leaving it at that;-).\nEdit: as the OP has now applied most of my suggestions, let me follow up with one reasonable way to hive off most functionality to a class in a separate module. In a new file, for example foobar.py, in the same directory as the original script (or in site-packages, or elsewhere on sys.path), place this code:\ndef token_of(line):\n return line.partition(':')[-1].strip()\n\nclass FileParser(object):\n def __init__(self, filename):\n self.tokenList = open(filename, 'r')\n\n def cleaned_input(self):\n cleanedInput = []\n prevLine = 0\n\n for line in self.tokenList:\n if line.startswith('LINE:'):\n lineNo = int(token_of(line))\n diff = lineNo - prevLine - 1\n cleanedInput.append('\\n' * (diff if diff>1 else diff+1))\n prevLine = lineNo\n else:\n cleanedLine = token_of(line)\n cleanedInput.append(cleanedLine + ' ')\n\n return cleanedInput\n\nYour main script then becomes just:\nimport sys\nimport foobar\n\ndef main():\n thefile = foobar.FileParser(sys.argv[1])\n print thefile.cleaned_input()\n\nif __name__ == '__main__':\n main()\n\n",
"When I do this particular refactoring, I usually start with an initial transformation within the first file. Step 1: move the functionality into a method in a new class. Step 2: add \nthe magic invocation below to get the file to run like a script again:\nclass LineCleaner:\n\n def cleanFile(filename):\n cleanInput = \"\"\n prevLine = 0\n for line in open(filename,'r'): \n <... as in original script ..>\n\nif __name__ == '__main__':\n cleaner = LineCleaner()\n cleaner.cleanFile(sys.argv[1]) \n\n",
"You can get away with creating a function and putting all your logic in it. For full \"object orientedness\" though, you can do something like this:\nps - your posted code has a bug on the continue line - it is always executed and the last 2 lines will never execute.\nclass Cleaner:\n def __init__(...):\n ...init logic...\n def Clean(self):\n for line in open(self.tokenList):\n ...cleaning logic...\n return cleanedInput\n\ndef main(argv):\n cleaner = Cleaner(argv[1])\n print cleaner.Clean()\n return 0\n\nif '__main__' == __name__:\n sys.exit(main(sys.argv))\n\n",
"If presented code is all code Just don't add any class !!\nYour code is too simply for that !!\nOOP approach would add unnecessary complexity.\nBut if still wont.\nPut all code into function eg.\ndef parse_tokenized_input(file):\n tokenList = open(file, 'r')\n cleanedInput = ''\n prevLine = 0\n #rest of code\n\nat end add:\nif __name__ == '__main__':\n parse_tokenized_input(sys.argv[1])\n\nIf code works correct put def of function to new file (and all needed imports!)\neg. mymodyle.py\nyour script now will be:\nfrom mymodule.py import parse_tokenized_input\n\nif __name__ == '__main__':\n parse_tokenized_input(sys.argv[1])\n\nOh and think out better name for your function and module (module should have general name).\n"
] |
[
56,
1,
0,
0
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0001813117_oop_python.txt
|
Q:
How to Make sure the code is still working after refactoring ( Dynamic language)
How to make sure that code is still working after refactoring ( i.e, after variable name change)?
In static language, if a class is renamed but other referring class is not, then I will get a compilation error.
But in dynamic language there is no such safety net, and your code can break during refactoring if you are not careful enough. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.
How to solve this problem?
A:
Before you start refactoring you should create tests that will be able to test what you're going to change - if you say unit tests will not be enought, or they will be hard to create, then by all means create higher level tests possibly even excersising the whole of your product.
If you have code coverage tools for your language use them to measure the quality of the tests that you've created - after it's reached a reasonably high value and if the tests are kept up to date and extended you'll be able to do anything with your code very efficiently and be rather sure things are not going in the wrong direction.
A:
I've been teaching a class on unit tests, refactoring and so forth, and this is probably the thing that most people get wrong. Refactoring is not just changing the code. It is changing the code without changing the external functional behavior. That is a very important point.
In other words, you need to have some way to verify that the external functional behavior is intact after the refactoring. Lacking divine insight I find unit tests very useful for that. In his book on Refactoring, Martin Fowler stresses the use of automated tests for this verification.
If your code was developed using TDD you will have the necessary test suite as it is developed during the development of the code itself. If you need to refactor code for which no tests are available, your best approach would be to set up automated tests before you make any changes to the code. I realize that setting up tests for existing code can be hard, but you will learn a lot about the code while doing so.
You may also want to check Bruce Eckel's essay on strong typing versus strong testing as it discusses the feedback you get from the compiler versus the feedback you get from your test suite.
A:
Your code can break during refactoring even with a compiled language. Relying on that alone will get you into trouble. Automated testing is the best way to be sure that the program works as it should.
If you say what dynamic language you are using we can maybe offer some advice on tools that can help you with testing. Everything can be tested.
EDIT:
You responded and said you use PHP and Python.
If this is a web app use selenium to create the tests in the browser. At first you just need Selenium IDE. Put all your tests in a single Test Suite so that you can easily execute them all. As the list grows you can start looking into Selenium RC and Selenium Grid.
A:
1) For Python use PyUnit for PHP phpunit.
2) TDD approach is good but also making tests after writing code is acceptable.
3) Also use refactoring tools that are available for Your IDE they do only safe refactorings.
In Python You have rope (this is library but have plugins for most IDEs).
4) Good books are:
'Test-Driven Development by example' Best
'Expert Python Programing' Tarek Ziade (explain both TDD and refactoring)
google tdd and database to find a good book about TDD approach for developing databases.
Add info for mocks you are using. AFAIK mocks are needed only when database or network is involved. But normally unit test should cover small pice of code (one class only) sometimes two classes so no mockup needed !!
|
How to Make sure the code is still working after refactoring ( Dynamic language)
|
How to make sure that code is still working after refactoring ( i.e, after variable name change)?
In static language, if a class is renamed but other referring class is not, then I will get a compilation error.
But in dynamic language there is no such safety net, and your code can break during refactoring if you are not careful enough. You can use unit test, but when you are using mocks it's pretty hard to know the name changes and as a consequence, it may not help.
How to solve this problem?
|
[
"Before you start refactoring you should create tests that will be able to test what you're going to change - if you say unit tests will not be enought, or they will be hard to create, then by all means create higher level tests possibly even excersising the whole of your product. \nIf you have code coverage tools for your language use them to measure the quality of the tests that you've created - after it's reached a reasonably high value and if the tests are kept up to date and extended you'll be able to do anything with your code very efficiently and be rather sure things are not going in the wrong direction.\n",
"I've been teaching a class on unit tests, refactoring and so forth, and this is probably the thing that most people get wrong. Refactoring is not just changing the code. It is changing the code without changing the external functional behavior. That is a very important point. \nIn other words, you need to have some way to verify that the external functional behavior is intact after the refactoring. Lacking divine insight I find unit tests very useful for that. In his book on Refactoring, Martin Fowler stresses the use of automated tests for this verification.\nIf your code was developed using TDD you will have the necessary test suite as it is developed during the development of the code itself. If you need to refactor code for which no tests are available, your best approach would be to set up automated tests before you make any changes to the code. I realize that setting up tests for existing code can be hard, but you will learn a lot about the code while doing so.\nYou may also want to check Bruce Eckel's essay on strong typing versus strong testing as it discusses the feedback you get from the compiler versus the feedback you get from your test suite. \n",
"Your code can break during refactoring even with a compiled language. Relying on that alone will get you into trouble. Automated testing is the best way to be sure that the program works as it should.\nIf you say what dynamic language you are using we can maybe offer some advice on tools that can help you with testing. Everything can be tested.\nEDIT:\nYou responded and said you use PHP and Python.\nIf this is a web app use selenium to create the tests in the browser. At first you just need Selenium IDE. Put all your tests in a single Test Suite so that you can easily execute them all. As the list grows you can start looking into Selenium RC and Selenium Grid.\n",
"1) For Python use PyUnit for PHP phpunit.\n2) TDD approach is good but also making tests after writing code is acceptable.\n3) Also use refactoring tools that are available for Your IDE they do only safe refactorings.\nIn Python You have rope (this is library but have plugins for most IDEs).\n4) Good books are:\n'Test-Driven Development by example' Best\n'Expert Python Programing' Tarek Ziade (explain both TDD and refactoring)\ngoogle tdd and database to find a good book about TDD approach for developing databases.\nAdd info for mocks you are using. AFAIK mocks are needed only when database or network is involved. But normally unit test should cover small pice of code (one class only) sometimes two classes so no mockup needed !!\n"
] |
[
17,
10,
1,
0
] |
[] |
[] |
[
"dynamic_languages",
"php",
"python"
] |
stackoverflow_0000688740_dynamic_languages_php_python.txt
|
Q:
Help ctypes.windll.dnsapi.DnsQuery_A
I have trouble with [DnsQuery](http://msdn.microsoft.com/en-us/library/ms682016(VS.85).aspx) API, the *ppQueryResultsSet parameter troubles me. Can anyone show me an example of how to make correct DLL calls in python?
import ctypes
from ctypes import wintypes
from windns_types import DNS_RECORD, IP4_ARRAY #declared here http://pastebin.com/f39d8b997
def DnsQuery(host, type, server, opt=0):
server_arr = IP4_ARRAY()
rr = DNS_RECORD()
server_arr.AddrCount=1
server_arr.AddrArray[0] = ctypes.windll.Ws2_32.inet_addr(server)
ctypes.windll.dnsapi.DnsQuery_A(host, type, opt, server_arr, rr, 0)
# WindowsError: exception: access violation reading 0x00000001
return rr
print DnsQuery("www.google.com", 1, "208.67.222.222")
A:
Isn't it a pointer to pointer to DNS_RECORD? This means you have to initialize rr as POINTER(DNS_RECORD)() and pass it by reference: ctypes.byref(rr).
Update: But I think the problem you see is from passing server_arr: you pass a structure with first field being 0x00000001 instead of reference to this structure, so C code tries to dereference AddrCount field and gives you access violation. The same technique should be used for server_arr too.
|
Help ctypes.windll.dnsapi.DnsQuery_A
|
I have trouble with [DnsQuery](http://msdn.microsoft.com/en-us/library/ms682016(VS.85).aspx) API, the *ppQueryResultsSet parameter troubles me. Can anyone show me an example of how to make correct DLL calls in python?
import ctypes
from ctypes import wintypes
from windns_types import DNS_RECORD, IP4_ARRAY #declared here http://pastebin.com/f39d8b997
def DnsQuery(host, type, server, opt=0):
server_arr = IP4_ARRAY()
rr = DNS_RECORD()
server_arr.AddrCount=1
server_arr.AddrArray[0] = ctypes.windll.Ws2_32.inet_addr(server)
ctypes.windll.dnsapi.DnsQuery_A(host, type, opt, server_arr, rr, 0)
# WindowsError: exception: access violation reading 0x00000001
return rr
print DnsQuery("www.google.com", 1, "208.67.222.222")
|
[
"Isn't it a pointer to pointer to DNS_RECORD? This means you have to initialize rr as POINTER(DNS_RECORD)() and pass it by reference: ctypes.byref(rr).\nUpdate: But I think the problem you see is from passing server_arr: you pass a structure with first field being 0x00000001 instead of reference to this structure, so C code tries to dereference AddrCount field and gives you access violation. The same technique should be used for server_arr too.\n"
] |
[
2
] |
[] |
[] |
[
"ctypes",
"dns",
"python",
"winapi"
] |
stackoverflow_0001812564_ctypes_dns_python_winapi.txt
|
Q:
Python: execfile from other file's working directory?
I have some code that loads a default configuration file and then allows users to supply their own Python files as additional supplemental configuration or overrides of the defaults:
# foo.py
def load(cfg_path=None):
# load default configuration
exec(default_config)
# load user-specific configuration
if cfg_path:
execfile(cfg_path)
There is a problem, though: execfile() executes directives in the file specified by cfg_path as if it were in the working directory of foo.py, not its own working directory. Thus, import directives might fail if the cfg_path file does, say, from m import x where m is a module in the same directory as cfg_path.
How do I execfile() from the working directory of its argument, or otherwise achieve an equivalent result? Also, I've been told that execfile is deprecated in Python 3 and that I should be using exec, so if there's a better way that I should be doing this, I'm all ears.
Note: I don't think solutions which merely change the working directory are correct. That won't put those modules on the interpreter's module-lookup path, as far as I can tell.
A:
os.chdir lets you change the working directory as you wish (you can extract the working directory of cfg_path with os.path.dirname); be sure to first get the current directory with os.getcwd if you want to restore it when you're done exec'ing cfg_path.
Python 3 does indeed remove execfile (in favor of a sequence where you read the file, compile the contents, then exec them), but you need not worry about that, if you're currently coding in Python 2.6, since the 2to3 source to source translation deals with all this smoothly and seamlessly.
Edit: the OP says, in a comment, that execfile launches a separate process and does not respect the current working directory. This is false, and here's an example showing that it is:
import os
def makeascript(where):
f = open(where, 'w')
f.write('import os\nprint "Dir in file:", os.getcwd()\n')
f.close()
def main():
where = '/tmp/bah.py'
makeascript(where)
execfile(where)
os.chdir('/tmp')
execfile(where)
if __name__ == '__main__':
main()
Running this on my machine produces output such as:
Dir in file: /Users/aleax/stko
Dir in file: /private/tmp
clearly showing that execfile does keep using the working directory that's set at the time execfile executes. (If the file executed changes the working directory, that will be reflected after execfile returns -- exactly because everything is taking place in the same process!).
So, whatever problems the OP is still observing are not tied to the current working directory (it's hard to diagnose what they may actually be, without seeing the code and the exact details of the observed problems;-).
|
Python: execfile from other file's working directory?
|
I have some code that loads a default configuration file and then allows users to supply their own Python files as additional supplemental configuration or overrides of the defaults:
# foo.py
def load(cfg_path=None):
# load default configuration
exec(default_config)
# load user-specific configuration
if cfg_path:
execfile(cfg_path)
There is a problem, though: execfile() executes directives in the file specified by cfg_path as if it were in the working directory of foo.py, not its own working directory. Thus, import directives might fail if the cfg_path file does, say, from m import x where m is a module in the same directory as cfg_path.
How do I execfile() from the working directory of its argument, or otherwise achieve an equivalent result? Also, I've been told that execfile is deprecated in Python 3 and that I should be using exec, so if there's a better way that I should be doing this, I'm all ears.
Note: I don't think solutions which merely change the working directory are correct. That won't put those modules on the interpreter's module-lookup path, as far as I can tell.
|
[
"os.chdir lets you change the working directory as you wish (you can extract the working directory of cfg_path with os.path.dirname); be sure to first get the current directory with os.getcwd if you want to restore it when you're done exec'ing cfg_path.\nPython 3 does indeed remove execfile (in favor of a sequence where you read the file, compile the contents, then exec them), but you need not worry about that, if you're currently coding in Python 2.6, since the 2to3 source to source translation deals with all this smoothly and seamlessly.\nEdit: the OP says, in a comment, that execfile launches a separate process and does not respect the current working directory. This is false, and here's an example showing that it is:\nimport os\n\ndef makeascript(where):\n f = open(where, 'w')\n f.write('import os\\nprint \"Dir in file:\", os.getcwd()\\n')\n f.close()\n\ndef main():\n where = '/tmp/bah.py'\n makeascript(where)\n execfile(where)\n os.chdir('/tmp')\n execfile(where)\n\nif __name__ == '__main__':\n main()\n\nRunning this on my machine produces output such as:\nDir in file: /Users/aleax/stko\nDir in file: /private/tmp\n\nclearly showing that execfile does keep using the working directory that's set at the time execfile executes. (If the file executed changes the working directory, that will be reflected after execfile returns -- exactly because everything is taking place in the same process!).\nSo, whatever problems the OP is still observing are not tied to the current working directory (it's hard to diagnose what they may actually be, without seeing the code and the exact details of the observed problems;-).\n"
] |
[
7
] |
[] |
[] |
[
"execfile",
"python",
"working_directory"
] |
stackoverflow_0001813282_execfile_python_working_directory.txt
|
Q:
Puzzling App Engine Datastore Issue (ListProperty)
Ok so I have the same python code locally and in the gae cloud.
when I store an entity locally, the ListProperty field of set element type datetime.datetime looks like so in the Datastore Viewer:
2009-01-01 00:00:00,2010-03-10 00:00:00
when I store same on the cloud, the viewer displays:
[datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2010, 3, 9, 0, 0)]
why the different representation?
This wouldn't bother me, only when I query on this field on the cloud the query fails to find the matched entity (it should and it does locally) - leading me to believe it's this differing representation that is causing the trouble. I should repeat - the code is identical.
Anyone think of a reason why this is happening and a solution to it?
UPDATE:
my query is as follows (using filters):
from x import y
from datetime import datetime
from google.appengine.ext import db
q = y.EntityType.all().filter('displayDateRange <=',datetime.now()).filter('displayDateRange >=',datetime.now())
usersResult = q.fetch(100)
print `len(usersResult)`
result should be 1, instead it's 0.
Actually it's just the ListProperty with specified value datetime.datetime that is the issue - queries on the StringListProperty is working as expected on the cloud.
I tried the raw filter via interactive console on both local and cloud and cloud gives me no results. So it is a datastore thing, I'm assuming it must have something to do with the storage format - I only have one entity value in both datastores with the ListProperty looking like:
2009-01-01 00:00:00,2010-03-09 00:00:00
[datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2010, 3, 9, 0, 0)]
on local and cloud respectively.
Any ideas?
Further Update
Replaced the datetime.now() with hardcoded datetime obj - example filter now looks like:
y.EntityType.all().filter('displayDateRange <=',datetime(2009,11,24)).filter('displayDateRange >=',datetime(2009,11,24))
Note with the above datetime ListProperty range from 1.1.2009 to 3.9.2010 this should return the above entity - I tried this identical filter on localhost dev server and it did so. The cloud, with it's different representation of the datetime.datetime ListProperty, does not.
Note this is taken from the current best practice for filtering on date range
Any ideas what could be wrong?
A:
Ok long story short: it's now classed as a bug in the app engine dev server version and is no longer supported in the production cloud datastore.
Filled out a further explanation in a blog post, check out point 3.
A:
The problem your see is clearly a conversion to string (calling __str__ or __unicode__) in the local case, while the representation (repr) of your data is displayed on the cloud. But this difference in printing out the results should not be the cause of your failed query on the cloud.
What is your exact query?
UPDATE after knowing the query:
I don't really understand why do you use these filter conditions:
.filter('displayDateRange <=',datetime.now()).filter('displayDateRange >=',datetime.now())
There are two problems with this:
You call datetime.now() twice, which can give you different results, which would result in an empty result set. It is especially true on a loaded server with multiple threads/processes of execution active at the same time.
What you might intended to do with the above pair of filters is checking for equality. But it won't work if the precision of the datetime instance returned by datetime.now() and the precision of the datetime stored in the database differs. It is not a good idea to check for equality in the case of floating point numbers and sub-second precision time values in general.
What do you want to achieve with such a pair of filter conditions?
|
Puzzling App Engine Datastore Issue (ListProperty)
|
Ok so I have the same python code locally and in the gae cloud.
when I store an entity locally, the ListProperty field of set element type datetime.datetime looks like so in the Datastore Viewer:
2009-01-01 00:00:00,2010-03-10 00:00:00
when I store same on the cloud, the viewer displays:
[datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2010, 3, 9, 0, 0)]
why the different representation?
This wouldn't bother me, only when I query on this field on the cloud the query fails to find the matched entity (it should and it does locally) - leading me to believe it's this differing representation that is causing the trouble. I should repeat - the code is identical.
Anyone think of a reason why this is happening and a solution to it?
UPDATE:
my query is as follows (using filters):
from x import y
from datetime import datetime
from google.appengine.ext import db
q = y.EntityType.all().filter('displayDateRange <=',datetime.now()).filter('displayDateRange >=',datetime.now())
usersResult = q.fetch(100)
print `len(usersResult)`
result should be 1, instead it's 0.
Actually it's just the ListProperty with specified value datetime.datetime that is the issue - queries on the StringListProperty is working as expected on the cloud.
I tried the raw filter via interactive console on both local and cloud and cloud gives me no results. So it is a datastore thing, I'm assuming it must have something to do with the storage format - I only have one entity value in both datastores with the ListProperty looking like:
2009-01-01 00:00:00,2010-03-09 00:00:00
[datetime.datetime(2009, 1, 1, 0, 0), datetime.datetime(2010, 3, 9, 0, 0)]
on local and cloud respectively.
Any ideas?
Further Update
Replaced the datetime.now() with hardcoded datetime obj - example filter now looks like:
y.EntityType.all().filter('displayDateRange <=',datetime(2009,11,24)).filter('displayDateRange >=',datetime(2009,11,24))
Note with the above datetime ListProperty range from 1.1.2009 to 3.9.2010 this should return the above entity - I tried this identical filter on localhost dev server and it did so. The cloud, with it's different representation of the datetime.datetime ListProperty, does not.
Note this is taken from the current best practice for filtering on date range
Any ideas what could be wrong?
|
[
"Ok long story short: it's now classed as a bug in the app engine dev server version and is no longer supported in the production cloud datastore.\nFilled out a further explanation in a blog post, check out point 3.\n",
"The problem your see is clearly a conversion to string (calling __str__ or __unicode__) in the local case, while the representation (repr) of your data is displayed on the cloud. But this difference in printing out the results should not be the cause of your failed query on the cloud.\nWhat is your exact query?\nUPDATE after knowing the query:\nI don't really understand why do you use these filter conditions:\n.filter('displayDateRange <=',datetime.now()).filter('displayDateRange >=',datetime.now())\n\nThere are two problems with this:\n\nYou call datetime.now() twice, which can give you different results, which would result in an empty result set. It is especially true on a loaded server with multiple threads/processes of execution active at the same time.\nWhat you might intended to do with the above pair of filters is checking for equality. But it won't work if the precision of the datetime instance returned by datetime.now() and the precision of the datetime stored in the database differs. It is not a good idea to check for equality in the case of floating point numbers and sub-second precision time values in general.\n\nWhat do you want to achieve with such a pair of filter conditions?\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"google_cloud_datastore",
"listproperty",
"python"
] |
stackoverflow_0001780618_google_app_engine_google_cloud_datastore_listproperty_python.txt
|
Q:
Custom/Owner draw control in PyQt?
I am learning PyQt and wonder if one can create custom/owner draw control like one show in the figure below:
alt text http://lh5.ggpht.com/_5XDoB4MglkY/SpoT51SXR1I/AAAAAAAAFcU/ZXjzmhRyDVA/s400/SearchBox.png
The search box has magnifier icon on its right border. Is this kind of thing possible with PyQt? Thanks!
A:
If you only need to show an icon, an easy way is to use style-sheets:
lineedit = QtGui.QLineEdit()
lineedit.setStyleSheet("""QLineEdit {
background-image: url(:/images/magnifier.png);
background-repeat: no-repeat;
background-position: right;
background-clip: padding;
padding-right: 16px;
}""")
A:
Antas Aasma - good anser!
m3rLinEz
Maybe its worth packing all buttons and text labels into one widget. In constructor of that widget connect all buttons. Expose only necessary signals and slots.
Just to reduce code you write (and possibly increase reuse of this widget).
|
Custom/Owner draw control in PyQt?
|
I am learning PyQt and wonder if one can create custom/owner draw control like one show in the figure below:
alt text http://lh5.ggpht.com/_5XDoB4MglkY/SpoT51SXR1I/AAAAAAAAFcU/ZXjzmhRyDVA/s400/SearchBox.png
The search box has magnifier icon on its right border. Is this kind of thing possible with PyQt? Thanks!
|
[
"If you only need to show an icon, an easy way is to use style-sheets:\nlineedit = QtGui.QLineEdit() \nlineedit.setStyleSheet(\"\"\"QLineEdit {\n background-image: url(:/images/magnifier.png);\n background-repeat: no-repeat;\n background-position: right;\n background-clip: padding;\n padding-right: 16px;\n}\"\"\")\n\n",
"Antas Aasma - good anser!\nm3rLinEz\nMaybe its worth packing all buttons and text labels into one widget. In constructor of that widget connect all buttons. Expose only necessary signals and slots.\nJust to reduce code you write (and possibly increase reuse of this widget).\n"
] |
[
6,
0
] |
[] |
[] |
[
"ownerdrawn",
"pyqt",
"python",
"qt",
"user_interface"
] |
stackoverflow_0001353181_ownerdrawn_pyqt_python_qt_user_interface.txt
|
Q:
What is the best way to escape Python strings in PHP?
I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.
subject_prefix = 'This String From User Input'
msg_footer = """This one too."""
The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:
echo "subject_prefix = '".$subject_prefix."'\n";
So. Any ideas?
(Rewriting the app in Python isn't possible due to time constraints. :P )
Edit, years later:
This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.
This was also a really bad idea.
A:
Do not try write this function in PHP. You will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit.
First, consider what problem you are actually solving. I presume you are just trying to get data from PHP to Python. You might try to write a .ini file rather than a .py file. Python has an excellent ini syntax parser, ConfigParser. You can write the obvious, and potentially incorrect, quoting function in PHP and nothing serious will happen if (read: when) you get it wrong.
You could also write an XML file. There are too many XML parsers and emitters for PHP and Python for me to even list here.
If I really can't convince you that this is a terrible, terrible idea, then you can at least use the pre-existing function that Python has for doing such a thing: repr().
Here's a handy PHP function which will run a Python script to do this for you:
<?php
function py_escape($input) {
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w")
);
$process = proc_open(
"python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'",
$descriptorspec, $pipes);
fwrite($pipes[0], $input);
fclose($pipes[0]);
$chunk_size = 8192;
$escaped = fread($pipes[1], $chunk_size);
if (strlen($escaped) == $chunk_size) {
// This is important for security.
die("That string's too big.\n");
}
proc_close($process);
return $escaped;
}
// Example usage:
$x = "string \rfull \nof\t crappy stuff";
print py_escape($x);
The chunk_size check is intended to prevent an attack whereby your input ends up being two really long strings, which look like ("hello " + ("." * chunk_size)) and '; os.system("do bad stuff") respectively. Now, that naive attack won't work exactly, because Python won't let a single-quoted string end in the middle of a line, and those quotes in the system() call will themselves be quoted, but if the attacker manages to get a line continuation ("\") into the right place and use something like os.system(map(chr, ...)) then they can inject some code that will run.
I opted to simply read one chunk and give up if there was more output, rather than continuing to read and accumulate, because there are also limits on Python source file line length; for all I know, that could be another attack vector. Python is not intended to be secure against arbitrary people writing arbitrary source code on your system so this area is unlikely to be audited.
The fact that I had to think of all this for this trivial example is just another example of why you shouldn't use python source code as a data interchange format.
A:
I'd start by standardizing the string type I was using in python, to use triple-quoted strings ("""). This should reduce the incidents of problems from stray quotes in the input. You'll still need to escape it of course, but it should reduce the number of issues that are a concern.
What I did to escape the strings would somewhat depend on what I'm worried about getting slipped in, and the context that they are getting printed out again. If you're just worried about quotes causing problems, you could simply check for and occurrences of """ and escape them. On the other hand if I was worried about the input itself being malicious (and it's user input, so you probably should), then I would look at options like strip_tags() or other similar functions.
A:
Another option may be to export the data as array or object as JSON string and modify the python code slightly to handle the new input. While the escaping via JSON is not 100% bulletproof it will be still better than own escaping routines.
And you'll be able to handle errors if the JSON string is malformatted.
There's a package for Python to encode and decode JSON: python-json 3.4
A:
I needed to code this to escape a string in the "ntriples" format, which uses python escaping.
The following function takes a utf-8 string and returns it escaped for python (or ntriples format).
It may do odd things if given illegal utf-8 data. It doesn't understand about Unicode characters past xFFFF. It does not (currently) wrap the string in double quotes.
The uniord function comes from a comment on php.net.
function python_string_escape( $string ) {
$string = preg_replace( "/\\\\/", "\\\\", $string ); # \\ (first to avoid string re-escaping)
$string = preg_replace( "/\n/", "\\n", $string ); # \n
$string = preg_replace( "/\r/", "\\r", $string ); # \r
$string = preg_replace( "/\t/", "\\t", $string ); # \t
$string = preg_replace( "/\"/", "\\\"", $string ); # \"
$string = preg_replace( "/([\x{00}-\x{1F}]|[\x{7F}-\x{FFFF}])/ue",
"sprintf(\"\\u%04X\",uniord(\"$1\"))",
$string );
return $string;
}
function uniord($c) {
$h = ord($c{0});
if ($h <= 0x7F) {
return $h;
} else if ($h < 0xC2) {
return false;
} else if ($h <= 0xDF) {
return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);
} else if ($h <= 0xEF) {
return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);
} else if ($h <= 0xF4) {
return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);
} else {
return false;
}
}
|
What is the best way to escape Python strings in PHP?
|
I have a PHP application which needs to output a python script, more specifically a bunch of variable assignment statements, eg.
subject_prefix = 'This String From User Input'
msg_footer = """This one too."""
The contents of subject_prefix et al need to be written to take user input; as such, I need to escape the contents of the strings. Writing something like the following isn't going to cut it; we're stuffed as soon as someone uses a quote or newline or anything else that I'm not aware of that could be hazardous:
echo "subject_prefix = '".$subject_prefix."'\n";
So. Any ideas?
(Rewriting the app in Python isn't possible due to time constraints. :P )
Edit, years later:
This was for integration between a web-app (written in PHP) and Mailman (written in Python). I couldn't modify the install of the latter, so I needed to come up with a way to talk in its language to manage its configuration.
This was also a really bad idea.
|
[
"Do not try write this function in PHP. You will inevitably get it wrong and your application will inevitably have an arbitrary remote execution exploit.\nFirst, consider what problem you are actually solving. I presume you are just trying to get data from PHP to Python. You might try to write a .ini file rather than a .py file. Python has an excellent ini syntax parser, ConfigParser. You can write the obvious, and potentially incorrect, quoting function in PHP and nothing serious will happen if (read: when) you get it wrong.\nYou could also write an XML file. There are too many XML parsers and emitters for PHP and Python for me to even list here.\nIf I really can't convince you that this is a terrible, terrible idea, then you can at least use the pre-existing function that Python has for doing such a thing: repr().\nHere's a handy PHP function which will run a Python script to do this for you:\n<?php\n\nfunction py_escape($input) {\n $descriptorspec = array(\n 0 => array(\"pipe\", \"r\"),\n 1 => array(\"pipe\", \"w\")\n );\n $process = proc_open(\n \"python -c 'import sys; sys.stdout.write(repr(sys.stdin.read()))'\",\n $descriptorspec, $pipes);\n fwrite($pipes[0], $input);\n fclose($pipes[0]);\n $chunk_size = 8192;\n $escaped = fread($pipes[1], $chunk_size);\n if (strlen($escaped) == $chunk_size) {\n // This is important for security.\n die(\"That string's too big.\\n\");\n }\n proc_close($process);\n return $escaped;\n}\n\n// Example usage:\n$x = \"string \\rfull \\nof\\t crappy stuff\";\nprint py_escape($x);\n\nThe chunk_size check is intended to prevent an attack whereby your input ends up being two really long strings, which look like (\"hello \" + (\".\" * chunk_size)) and '; os.system(\"do bad stuff\") respectively. Now, that naive attack won't work exactly, because Python won't let a single-quoted string end in the middle of a line, and those quotes in the system() call will themselves be quoted, but if the attacker manages to get a line continuation (\"\\\") into the right place and use something like os.system(map(chr, ...)) then they can inject some code that will run.\nI opted to simply read one chunk and give up if there was more output, rather than continuing to read and accumulate, because there are also limits on Python source file line length; for all I know, that could be another attack vector. Python is not intended to be secure against arbitrary people writing arbitrary source code on your system so this area is unlikely to be audited.\nThe fact that I had to think of all this for this trivial example is just another example of why you shouldn't use python source code as a data interchange format.\n",
"I'd start by standardizing the string type I was using in python, to use triple-quoted strings (\"\"\"). This should reduce the incidents of problems from stray quotes in the input. You'll still need to escape it of course, but it should reduce the number of issues that are a concern.\nWhat I did to escape the strings would somewhat depend on what I'm worried about getting slipped in, and the context that they are getting printed out again. If you're just worried about quotes causing problems, you could simply check for and occurrences of \"\"\" and escape them. On the other hand if I was worried about the input itself being malicious (and it's user input, so you probably should), then I would look at options like strip_tags() or other similar functions.\n",
"Another option may be to export the data as array or object as JSON string and modify the python code slightly to handle the new input. While the escaping via JSON is not 100% bulletproof it will be still better than own escaping routines.\nAnd you'll be able to handle errors if the JSON string is malformatted.\nThere's a package for Python to encode and decode JSON: python-json 3.4\n",
"I needed to code this to escape a string in the \"ntriples\" format, which uses python escaping. \nThe following function takes a utf-8 string and returns it escaped for python (or ntriples format).\nIt may do odd things if given illegal utf-8 data. It doesn't understand about Unicode characters past xFFFF. It does not (currently) wrap the string in double quotes.\nThe uniord function comes from a comment on php.net.\nfunction python_string_escape( $string ) {\n $string = preg_replace( \"/\\\\\\\\/\", \"\\\\\\\\\", $string ); # \\\\ (first to avoid string re-escaping)\n $string = preg_replace( \"/\\n/\", \"\\\\n\", $string ); # \\n\n $string = preg_replace( \"/\\r/\", \"\\\\r\", $string ); # \\r \n $string = preg_replace( \"/\\t/\", \"\\\\t\", $string ); # \\t \n $string = preg_replace( \"/\\\"/\", \"\\\\\\\"\", $string ); # \\\"\n $string = preg_replace( \"/([\\x{00}-\\x{1F}]|[\\x{7F}-\\x{FFFF}])/ue\",\n \"sprintf(\\\"\\\\u%04X\\\",uniord(\\\"$1\\\"))\",\n $string );\n return $string;\n}\n\nfunction uniord($c) {\n $h = ord($c{0});\n if ($h <= 0x7F) {\n return $h;\n } else if ($h < 0xC2) {\n return false;\n } else if ($h <= 0xDF) {\n return ($h & 0x1F) << 6 | (ord($c{1}) & 0x3F);\n } else if ($h <= 0xEF) {\n return ($h & 0x0F) << 12 | (ord($c{1}) & 0x3F) << 6 | (ord($c{2}) & 0x3F);\n } else if ($h <= 0xF4) {\n return ($h & 0x0F) << 18 | (ord($c{1}) & 0x3F) << 12 | (ord($c{2}) & 0x3F) << 6 | (ord($c{3}) & 0x3F);\n } else {\n return false;\n }\n}\n\n"
] |
[
2,
0,
0,
0
] |
[
"I suggest writing a function that will take two arguments: the text to be escaped and the type of quotes the string is in. Then, for example, if the type of quotes are single quotes, the function will escape the single quotes in the string and any other characters that need to be escaped (backslash?).\nfunction escape_string($text, $type) {\n // Escape backslashes for all types of strings?\n $text = str_replace('\\\\', '\\\\\\\\', $text);\n\n switch($type) {\n case 'single':\n $text = str_replace(\"'\", \"\\\\'\", $text);\n break;\n case 'double':\n $text = str_replace('\"', '\\\\\"', $text);\n break;\n // etc...\n }\n\n return $text;\n}\n\nI'm assuming that for single-quoted strings you want to escape the single quotes, and with double-quoted strings you want to escape the double quotes...\n"
] |
[
-2
] |
[
"php",
"python",
"user_input"
] |
stackoverflow_0000196771_php_python_user_input.txt
|
Q:
PyQT events between multiple objects
I am creating a GUI program in Python/PyQT and would like to know how I can connect an event which happens in a child object to the parent?
For example, if someone clicks a 'Submit' button, how would i trigger something to happen in the parent object (lets say update a QLabel on the parent)
Any help would be greatly appreciated
L
A:
It is done like in C++ Qt by connecting signals to slots, you will find all the information on this page (and here for the old way).
A:
You must connect these methods every time you set new parent (and remove old connections!!)
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#connect
(If widget parent change and You still wont that new parent to recive signals)
But if your layout is static just give good names for your widgets. Then connect each signal to callable (any python function) and that function will change QLable.
In this case relation parent children change nothing since you refer to widgets by names not relations.
|
PyQT events between multiple objects
|
I am creating a GUI program in Python/PyQT and would like to know how I can connect an event which happens in a child object to the parent?
For example, if someone clicks a 'Submit' button, how would i trigger something to happen in the parent object (lets say update a QLabel on the parent)
Any help would be greatly appreciated
L
|
[
"It is done like in C++ Qt by connecting signals to slots, you will find all the information on this page (and here for the old way).\n",
"You must connect these methods every time you set new parent (and remove old connections!!)\nhttp://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qobject.html#connect\n(If widget parent change and You still wont that new parent to recive signals)\nBut if your layout is static just give good names for your widgets. Then connect each signal to callable (any python function) and that function will change QLable.\nIn this case relation parent children change nothing since you refer to widgets by names not relations.\n"
] |
[
4,
0
] |
[] |
[] |
[
"events",
"pyqt",
"python"
] |
stackoverflow_0001627148_events_pyqt_python.txt
|
Q:
Remove Duplicate Items in Dictionary
I'm trying to remove duplicate items in a list through a dictionary:
def RemoveDuplicates(list):
d = dict()
for i in xrange(0, len(list)):
dict[list[i]] = 1 <------- error here
return d.keys()
But it is raising me the following error:
TypeError: 'type' object does not support item assignment
What is the problem?
A:
You should have written:
d[list[i]] = 1
But why not do this?
def RemoveDuplicates(l):
return list(set(l))
Also, don't use built-in function names as variable names. It can lead to confusing bugs.
A:
In addition to what others have said, it is unpythonic to do this:
for i in xrange(0, len(lst)):
do stuff with lst[i]
when you can do this instead:
for item in lst:
do stuff with item
A:
dict is the type, you mean d[list[i]] = 1.
Addition: This points out the actual error in your code. But the answers provided by others provide better way to achieve what you are aiming at.
A:
def remove_duplicates(myList):
return list (set(myList))
From looking at your code it seems that you are not bothered about the ordering of elements and concerned only about the uniqueness. In such a case, a set() could be a better data structure.
The problem in your code is just to use a function argument name which is not the name of the built-in type list and later on the type dict in the expression dict[list[i]].
A:
Note that using list(set(seq)) will likely change the ordering of the remaining items. If retaining their order is important, you need to make a copy of the list:
items = set()
copy = []
for item in seq:
if not item in items:
copy.add(item)
items.append(item)
seq = copy
|
Remove Duplicate Items in Dictionary
|
I'm trying to remove duplicate items in a list through a dictionary:
def RemoveDuplicates(list):
d = dict()
for i in xrange(0, len(list)):
dict[list[i]] = 1 <------- error here
return d.keys()
But it is raising me the following error:
TypeError: 'type' object does not support item assignment
What is the problem?
|
[
"You should have written:\nd[list[i]] = 1\n\nBut why not do this?\ndef RemoveDuplicates(l):\n return list(set(l))\n\nAlso, don't use built-in function names as variable names. It can lead to confusing bugs.\n",
"In addition to what others have said, it is unpythonic to do this:\nfor i in xrange(0, len(lst)):\n do stuff with lst[i]\n\nwhen you can do this instead:\nfor item in lst:\n do stuff with item\n\n",
"dict is the type, you mean d[list[i]] = 1.\nAddition: This points out the actual error in your code. But the answers provided by others provide better way to achieve what you are aiming at.\n",
"def remove_duplicates(myList):\n return list (set(myList))\n\nFrom looking at your code it seems that you are not bothered about the ordering of elements and concerned only about the uniqueness. In such a case, a set() could be a better data structure. \nThe problem in your code is just to use a function argument name which is not the name of the built-in type list and later on the type dict in the expression dict[list[i]]. \n",
"Note that using list(set(seq)) will likely change the ordering of the remaining items. If retaining their order is important, you need to make a copy of the list:\nitems = set()\ncopy = []\nfor item in seq:\n if not item in items:\n copy.add(item)\n items.append(item)\nseq = copy\n\n"
] |
[
11,
4,
3,
3,
0
] |
[] |
[] |
[
"duplicate_removal",
"python"
] |
stackoverflow_0001813469_duplicate_removal_python.txt
|
Q:
How to deal with "None" DB values in Django queries
I have the following filter query which is doing an SQL OR statement:
results = Stores.objects.filter(Q(title__icontains=prefs.address1) | Q(title__icontains=prefs.address2))
This works fine but if the prefs.address1 and prefs.address2 values (which come from another model) are blank in mySQL, Django complains with the following error:
Cannot use None as a query value
Is there an elegant way to check to see if my filter values are not blank before constructing the OR filter query?
Many thanks.
A:
You could do this which is easily generalisable to more queries
query = Q()
for search in (prefs.address1, prefs.address2):
if search:
query |= Q(title__icontains=search)
results = Stores.objects.filter(query)
A:
This?
thefilter = Q(title__icontains=prefs.address1)
if prefs.address2 is not None:
thefilter = thefilter | Q(title__icontains=prefs.address2)
results = Stores.objects.filter( thefilter)
|
How to deal with "None" DB values in Django queries
|
I have the following filter query which is doing an SQL OR statement:
results = Stores.objects.filter(Q(title__icontains=prefs.address1) | Q(title__icontains=prefs.address2))
This works fine but if the prefs.address1 and prefs.address2 values (which come from another model) are blank in mySQL, Django complains with the following error:
Cannot use None as a query value
Is there an elegant way to check to see if my filter values are not blank before constructing the OR filter query?
Many thanks.
|
[
"You could do this which is easily generalisable to more queries\nquery = Q()\nfor search in (prefs.address1, prefs.address2):\n if search:\n query |= Q(title__icontains=search)\nresults = Stores.objects.filter(query)\n\n",
"This?\nthefilter = Q(title__icontains=prefs.address1)\nif prefs.address2 is not None:\n thefilter = thefilter | Q(title__icontains=prefs.address2)\nresults = Stores.objects.filter( thefilter)\n\n"
] |
[
12,
3
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001813653_django_python.txt
|
Q:
Django, how to generate an admin panel without models?
I'm building a rather large project, that basically consists of this:
Server 1:
Ice based services.
Glacier2 for session handling.
Firewall allowing access to Glacier2.
Server 2:
Web interface (read, public) for Ice services via Glacier2.
Admin interface for Ice services via Glacier 2.
The point I'm concerned with is the web interface. I want to use Django, because it's both written in python and has that incredibly useful automatic admin panel generator.
The web interface doesn't access any database. It connects to an Ice service on Server #1 via the Glacier2 router and uses the API exposed by those services to manipulate data.
And as you probably know, the admin generation in Django depends on the use of Django's ORM; which I'm not using since I have no database to access.
So I need to generate the admin panel, but, instead of having an standard data access like the ORM normally does, I need to intercept any "db-access" calls and transform them into Ice service calls, and then take the service's output (if any), transform it into whatever the ORM normally returns and return control to Django.
Anyone knows how I could do this? what would I need to subclass? Any specific ideas?
Thanks for your time.
A:
I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.
Take a look at models.py, admin.py and urls.py here: django-webfaction
To create an entry on the admin index page use a dummy model that has managed=False
Register that model with the admin.
You can then intercept the admin urls and direct them to your own views.
This makes sense if the add/edit/delete actions the admin provides make sense for your app. Otherwise you are better off overriding the admin index or changelist templates to include your own custom actions
A:
The real power of the contrib.admin is django Forms. In essence, the admin tool is basically auto-generating a Form to match a Model with a little bit of urls.py routing thrown in. In the end it would probably just be easier to use django Forms apart from the admin tool.
A:
you can "mock" some class so it look like a model but it does proxy to your APIs
f.e.
class QuerysetMock(object):
def all():
return call_to_your_api()
[...]
class MetaMock(object):
def fields():
return fields_mock_objects..
verbose_name = ''
[...]
class ModelMock(object):
_meta = MetaMock()
objects = QuerysetMock()
admin.site.register(ModelMock)
This may work.. but you need to do a lot django.model compatible stuff
A:
The django ORM has a pluggable backent, which means that you can write a backend for things that aren't RDBMSes. It's probably a rather large task, but a good place to get started is with Malcolm Tredinnick's talk from DjangoCon 2008, Inside the ORM.
Otherwise, you could bypass the ORM altogether, and write the forms manually for the access you need.
|
Django, how to generate an admin panel without models?
|
I'm building a rather large project, that basically consists of this:
Server 1:
Ice based services.
Glacier2 for session handling.
Firewall allowing access to Glacier2.
Server 2:
Web interface (read, public) for Ice services via Glacier2.
Admin interface for Ice services via Glacier 2.
The point I'm concerned with is the web interface. I want to use Django, because it's both written in python and has that incredibly useful automatic admin panel generator.
The web interface doesn't access any database. It connects to an Ice service on Server #1 via the Glacier2 router and uses the API exposed by those services to manipulate data.
And as you probably know, the admin generation in Django depends on the use of Django's ORM; which I'm not using since I have no database to access.
So I need to generate the admin panel, but, instead of having an standard data access like the ORM normally does, I need to intercept any "db-access" calls and transform them into Ice service calls, and then take the service's output (if any), transform it into whatever the ORM normally returns and return control to Django.
Anyone knows how I could do this? what would I need to subclass? Any specific ideas?
Thanks for your time.
|
[
"I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.\nTake a look at models.py, admin.py and urls.py here: django-webfaction\nTo create an entry on the admin index page use a dummy model that has managed=False\nRegister that model with the admin.\nYou can then intercept the admin urls and direct them to your own views. \nThis makes sense if the add/edit/delete actions the admin provides make sense for your app. Otherwise you are better off overriding the admin index or changelist templates to include your own custom actions\n",
"The real power of the contrib.admin is django Forms. In essence, the admin tool is basically auto-generating a Form to match a Model with a little bit of urls.py routing thrown in. In the end it would probably just be easier to use django Forms apart from the admin tool.\n",
"you can \"mock\" some class so it look like a model but it does proxy to your APIs\nf.e.\nclass QuerysetMock(object):\n def all():\n return call_to_your_api()\n [...]\n\n\nclass MetaMock(object):\n def fields():\n return fields_mock_objects..\n verbose_name = ''\n [...]\n\nclass ModelMock(object):\n _meta = MetaMock()\n objects = QuerysetMock()\n\nadmin.site.register(ModelMock)\n\nThis may work.. but you need to do a lot django.model compatible stuff\n",
"The django ORM has a pluggable backent, which means that you can write a backend for things that aren't RDBMSes. It's probably a rather large task, but a good place to get started is with Malcolm Tredinnick's talk from DjangoCon 2008, Inside the ORM. \nOtherwise, you could bypass the ORM altogether, and write the forms manually for the access you need.\n"
] |
[
7,
3,
1,
0
] |
[] |
[] |
[
"django",
"django_admin",
"ice",
"python"
] |
stackoverflow_0001813637_django_django_admin_ice_python.txt
|
Q:
How does python webdriver work?
I want to add some features to webdriver, but since I don't know Java at all, I want to understand the way it works first. So as I get it, there is a firefox plugin (javascript) and there is java code that starts firefox with that extension installed, then this java code listens to a local port and when it gets some command, java signals it to the firefox plugin, which does the actual job. And the python code is just a set of shortcuts to the port interface. It this correct?
Update:
Thanks for the response, malatio. But could anyone please explain, why when I add
alert('Hello world!');
after
FirefoxDriver.prototype.deleteCookie = function(respond, cookieString) {
in
D:\webdriver-read-only\firefox\src\extension\components\firefoxDriver.js
and then run
from webdriver_firefox.webdriver import WebDriver
wd = WebDriver()
wd.delete_all_cookies()
I still don't see the Hello world! alert (and get an error, by the way)
A:
Yeah you've got it. The Java server controls a browser with a special JavaScript environment that allows the server to control it. The server listens for commands given to it through http, when it receives commands, it pulls the strings on the browser to make it do stuff. The Python API for webdriver is code that constructs the right http commands to send to the webdriver server. There may or may not be good descriptions or diagrams for this for Webdriver, but the architecture is very similar for Selenium (in fact, Webdriver and Selenium are being merged into each other as "Selenium 2"). Here's a rundown of the same architecture from the Selenium docs: how-selenium-rc-works
(source: openqa.org)
|
How does python webdriver work?
|
I want to add some features to webdriver, but since I don't know Java at all, I want to understand the way it works first. So as I get it, there is a firefox plugin (javascript) and there is java code that starts firefox with that extension installed, then this java code listens to a local port and when it gets some command, java signals it to the firefox plugin, which does the actual job. And the python code is just a set of shortcuts to the port interface. It this correct?
Update:
Thanks for the response, malatio. But could anyone please explain, why when I add
alert('Hello world!');
after
FirefoxDriver.prototype.deleteCookie = function(respond, cookieString) {
in
D:\webdriver-read-only\firefox\src\extension\components\firefoxDriver.js
and then run
from webdriver_firefox.webdriver import WebDriver
wd = WebDriver()
wd.delete_all_cookies()
I still don't see the Hello world! alert (and get an error, by the way)
|
[
"Yeah you've got it. The Java server controls a browser with a special JavaScript environment that allows the server to control it. The server listens for commands given to it through http, when it receives commands, it pulls the strings on the browser to make it do stuff. The Python API for webdriver is code that constructs the right http commands to send to the webdriver server. There may or may not be good descriptions or diagrams for this for Webdriver, but the architecture is very similar for Selenium (in fact, Webdriver and Selenium are being merged into each other as \"Selenium 2\"). Here's a rundown of the same architecture from the Selenium docs: how-selenium-rc-works\n\n(source: openqa.org) \n"
] |
[
4
] |
[] |
[] |
[
"firefox",
"java",
"javascript",
"python",
"webdriver"
] |
stackoverflow_0001813824_firefox_java_javascript_python_webdriver.txt
|
Q:
Losing session data when user logs in
I have been working on a shop that is built in Python on the back of the django framework, everything was working fine until I noticed that when a user proceeds to the checkout and is requested to log in they do so and their basket empties...obvioulsy this is not a great thing for a basket to do, I was wondering what is causing this, could some look over my code and give me some advice at what it could be? I am at my wits end.
=====Edit - Below is my code I would appreciate it if someone could give me a hit at how i can stop the basket clearing when a users logins=====
def basket(request):
"""
Display the current state of the basket and allow the customer to modify
the discount and quantities of each row of the basket
"""
data = {}
basket = Basket(request)
discount_form = DiscountCodeForm(basket)
if request.method == "POST":
if 'update' in request.POST:
basket.post_update(request)
discount_form = DiscountCodeForm(basket, request.POST)
if discount_form.is_valid():
cleaned_data = discount_form.cleaned_data
if cleaned_data['discount_code']:
basket.set_discount(Offer.objects.get(code=cleaned_data['discount_code']))
if 'delete' in request.POST:
basket.post_delete(request)
if 'remove_discount' in request.POST:
basket.remove_discount()
data['discount_form'] = discount_form
data['logged_in'] = persistent_account(request)
data['pageclass'] = 'basket'
data['category'] = Category.objects.root_category()
data['products'] = Product.objects.all()
data['regions'] = Zone.objects.all()
data['currency'] = Currency.get_default_currency()
return render_to_response('basket.html', data, RequestContext(request))
def login(request):
"""
Log the user in.
The form is where the actual login occurs. If already logged in, then
forward to the last attempted page, or, if came directly to the login page,
the account page.
@todo: Incorrect guesses limit of 10 then deactive account
"""
data = {}
redirect_to = request.GET.get('next', reverse('account'))
account = persistent_account(request)
if account:
return HttpResponseRedirect(reverse('account'))
if request.method == "POST":
login_form = LoginForm(request, request.POST)
# This next line will also cause a login
if login_form.is_valid():
login_form.user.message_set.create(message="You have successfully logged in. Welcome back.")
return HttpResponseRedirect(redirect_to)
else:
login_form = LoginForm(request)
data['shop_login_form'] = login_form
data['pageclass'] = 'customer_login'
return render_to_response('login.html', data, RequestContext(request))
What i have given you is my login view and basket view hope that is enough, if not feel free to shout me.
A:
Are you running two django instances on the same machine? If so, check that SESSION_COOKIE_NAME is set to something different for each instance.
We had the problem that instances using sessions using the same SESSION_COOKIE_NAME had very sporadic (read bizarre) behaviour.
A:
This will probably be something to do with session management.
A user arrives at your site without first logging in, adds a few things to their basket, and then proceeds to the checkout. Upon first arrival at your site a session is established for this user. This might be done through cookies, a session id that is present in the URI, or a combination of both. The session associates the user's shopping basket with the user and is tracked on the server.
Now, in order to checkout on your system the user must log in. This creates a brand new session for the user and your system is losing track of the original session that the user had. The net effect of this is that their basket empties - because they effectively have a new basket.
I have absolutely no idea how sessions are being managed in your system (because, other than django, you provide no details whatsoever), but this is where I'd start looking.
I don't think that you'll find anyone that will do a free code review for you, so you need to figure out how sessions are being managed in your system and then post a more specific question. Good luck.
|
Losing session data when user logs in
|
I have been working on a shop that is built in Python on the back of the django framework, everything was working fine until I noticed that when a user proceeds to the checkout and is requested to log in they do so and their basket empties...obvioulsy this is not a great thing for a basket to do, I was wondering what is causing this, could some look over my code and give me some advice at what it could be? I am at my wits end.
=====Edit - Below is my code I would appreciate it if someone could give me a hit at how i can stop the basket clearing when a users logins=====
def basket(request):
"""
Display the current state of the basket and allow the customer to modify
the discount and quantities of each row of the basket
"""
data = {}
basket = Basket(request)
discount_form = DiscountCodeForm(basket)
if request.method == "POST":
if 'update' in request.POST:
basket.post_update(request)
discount_form = DiscountCodeForm(basket, request.POST)
if discount_form.is_valid():
cleaned_data = discount_form.cleaned_data
if cleaned_data['discount_code']:
basket.set_discount(Offer.objects.get(code=cleaned_data['discount_code']))
if 'delete' in request.POST:
basket.post_delete(request)
if 'remove_discount' in request.POST:
basket.remove_discount()
data['discount_form'] = discount_form
data['logged_in'] = persistent_account(request)
data['pageclass'] = 'basket'
data['category'] = Category.objects.root_category()
data['products'] = Product.objects.all()
data['regions'] = Zone.objects.all()
data['currency'] = Currency.get_default_currency()
return render_to_response('basket.html', data, RequestContext(request))
def login(request):
"""
Log the user in.
The form is where the actual login occurs. If already logged in, then
forward to the last attempted page, or, if came directly to the login page,
the account page.
@todo: Incorrect guesses limit of 10 then deactive account
"""
data = {}
redirect_to = request.GET.get('next', reverse('account'))
account = persistent_account(request)
if account:
return HttpResponseRedirect(reverse('account'))
if request.method == "POST":
login_form = LoginForm(request, request.POST)
# This next line will also cause a login
if login_form.is_valid():
login_form.user.message_set.create(message="You have successfully logged in. Welcome back.")
return HttpResponseRedirect(redirect_to)
else:
login_form = LoginForm(request)
data['shop_login_form'] = login_form
data['pageclass'] = 'customer_login'
return render_to_response('login.html', data, RequestContext(request))
What i have given you is my login view and basket view hope that is enough, if not feel free to shout me.
|
[
"Are you running two django instances on the same machine? If so, check that SESSION_COOKIE_NAME is set to something different for each instance.\nWe had the problem that instances using sessions using the same SESSION_COOKIE_NAME had very sporadic (read bizarre) behaviour.\n",
"This will probably be something to do with session management.\nA user arrives at your site without first logging in, adds a few things to their basket, and then proceeds to the checkout. Upon first arrival at your site a session is established for this user. This might be done through cookies, a session id that is present in the URI, or a combination of both. The session associates the user's shopping basket with the user and is tracked on the server.\nNow, in order to checkout on your system the user must log in. This creates a brand new session for the user and your system is losing track of the original session that the user had. The net effect of this is that their basket empties - because they effectively have a new basket.\nI have absolutely no idea how sessions are being managed in your system (because, other than django, you provide no details whatsoever), but this is where I'd start looking.\nI don't think that you'll find anyone that will do a free code review for you, so you need to figure out how sessions are being managed in your system and then post a more specific question. Good luck.\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"e_commerce",
"python",
"session"
] |
stackoverflow_0001791818_django_e_commerce_python_session.txt
|
Q:
python and securing pyc files on disk
I set django's settings.py file to chmod 600 to keep felonious folks from spying my database connection info, but on import python compiles this file and writes out settings.pyc as mode 644. It doesn't take much sleuthing for the bad guys to get the info they need from this compiled version. I fear my blog entries are in grave danger.
Beyond the obvious os.chmod, what techniques folks use to keep your compiled python secure on disk?
A:
You can set the umask directly in python. The interpreter uses this umask to create the pyc files:
import os
os.umask(077) # Only keep rights for owner
import test
Verify the test.pyc created:
$> ls -l test.py*
-rw-r--r-- 1 shad users 0 2009-11-29 00:15 test.py
-rw------- 1 shad users 94 2009-11-29 00:15 test.pyc
A:
To add a little bit to S.Lott's comment: The code portion of your blog should be stored in a location where it can be executed (e.g. via a web request), but not read directly. Any reasonable web server providing CGI support will allow this to be set up.
|
python and securing pyc files on disk
|
I set django's settings.py file to chmod 600 to keep felonious folks from spying my database connection info, but on import python compiles this file and writes out settings.pyc as mode 644. It doesn't take much sleuthing for the bad guys to get the info they need from this compiled version. I fear my blog entries are in grave danger.
Beyond the obvious os.chmod, what techniques folks use to keep your compiled python secure on disk?
|
[
"You can set the umask directly in python. The interpreter uses this umask to create the pyc files:\nimport os\nos.umask(077) # Only keep rights for owner\nimport test\n\nVerify the test.pyc created:\n$> ls -l test.py*\n-rw-r--r-- 1 shad users 0 2009-11-29 00:15 test.py\n-rw------- 1 shad users 94 2009-11-29 00:15 test.pyc\n\n",
"To add a little bit to S.Lott's comment: The code portion of your blog should be stored in a location where it can be executed (e.g. via a web request), but not read directly. Any reasonable web server providing CGI support will allow this to be set up.\n"
] |
[
6,
1
] |
[] |
[] |
[
"python",
"security"
] |
stackoverflow_0001814053_python_security.txt
|
Q:
How to delete Firefox cookies from webdriver in python?
when I can't delete FF cookies from webdriver. When I use the .delete_all_cookies method, it returns None. And when I try to get_cookies, I get the following error:
webdriver_common.exceptions.ErrorInResponseException: Error occurred when processing
packet:Content-Length: 120
{"elementId": "null", "context": "{9b44672f-d547-43a8-a01e-a504e617cfc1}", "parameters": [], "commandName": "getCookie"}
response:Length: 266
{"commandName":"getCookie","isError":true,"response":{"lineNumber":576,"message":"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMLocation.host]","name":"NS_ERROR_FAILURE"},"elementId":"null","context":"{9b44672f-d547-43a8-a01e-a504e617cfc1} "}
How can I fix it?
Update:
This happens with clean installation of webdriver with no modifications. The changes I've mentioned in another post were made later than this post being posted (I was trying to fix the issue myself).
A:
Hmm, I actually haven't worked with Webdriver so this may be of no help at all... but in your other post you mention that you're experimenting with modifying the delete cookie webdriver js function. Did get_cookies fail before you were modifying the delete function? What happens when you get cookies before deleting them? I would guess that the modification you're making to the delete function in webdriver-read-only\firefox\src\extension\components\firefoxDriver.js could break the delete function. Are you doing it just for debugging or do you actually want the browser itself to show a pop up when the driver tells it to delete cookies? It wouldn't surprise me if this modification broke.
My real advice though would be actually to start using Selenium instead of Webdriver since it's being discontinued in it's current incarnation, or morphed into Selenium. Selenium is more actively developed and has pretty active and responsive forms. It will continue to be developed and stable while the merge is happening, while I take it Webdriver might not have as many bugfixes going forward. I've had success using the Selenium commands that control cookies. They seem to be revamping their documentation and for some reason there isn't any link to the Python API, but if you download selenium rc, you can find the Python API doc in selenium-client-driver-python, you'll see there are a good 5 or so useful methods for controlling cookies, which you use in your own custom Python methods if you want to, say, delete all the cookies with a name matching a certain regexp. If for some reason you do want the browser to alert() some info about the deleted cookies too, you could do that by getting the cookie names/values from the python method, and then passing them to selenium's getEval() statement which will execute arbitrary js you feed it (like "alert()"). ... If you do go the selenium route feel free to contact me if you get a blocker, I might be able to assist.
|
How to delete Firefox cookies from webdriver in python?
|
when I can't delete FF cookies from webdriver. When I use the .delete_all_cookies method, it returns None. And when I try to get_cookies, I get the following error:
webdriver_common.exceptions.ErrorInResponseException: Error occurred when processing
packet:Content-Length: 120
{"elementId": "null", "context": "{9b44672f-d547-43a8-a01e-a504e617cfc1}", "parameters": [], "commandName": "getCookie"}
response:Length: 266
{"commandName":"getCookie","isError":true,"response":{"lineNumber":576,"message":"Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMLocation.host]","name":"NS_ERROR_FAILURE"},"elementId":"null","context":"{9b44672f-d547-43a8-a01e-a504e617cfc1} "}
How can I fix it?
Update:
This happens with clean installation of webdriver with no modifications. The changes I've mentioned in another post were made later than this post being posted (I was trying to fix the issue myself).
|
[
"Hmm, I actually haven't worked with Webdriver so this may be of no help at all... but in your other post you mention that you're experimenting with modifying the delete cookie webdriver js function. Did get_cookies fail before you were modifying the delete function? What happens when you get cookies before deleting them? I would guess that the modification you're making to the delete function in webdriver-read-only\\firefox\\src\\extension\\components\\firefoxDriver.js could break the delete function. Are you doing it just for debugging or do you actually want the browser itself to show a pop up when the driver tells it to delete cookies? It wouldn't surprise me if this modification broke.\nMy real advice though would be actually to start using Selenium instead of Webdriver since it's being discontinued in it's current incarnation, or morphed into Selenium. Selenium is more actively developed and has pretty active and responsive forms. It will continue to be developed and stable while the merge is happening, while I take it Webdriver might not have as many bugfixes going forward. I've had success using the Selenium commands that control cookies. They seem to be revamping their documentation and for some reason there isn't any link to the Python API, but if you download selenium rc, you can find the Python API doc in selenium-client-driver-python, you'll see there are a good 5 or so useful methods for controlling cookies, which you use in your own custom Python methods if you want to, say, delete all the cookies with a name matching a certain regexp. If for some reason you do want the browser to alert() some info about the deleted cookies too, you could do that by getting the cookie names/values from the python method, and then passing them to selenium's getEval() statement which will execute arbitrary js you feed it (like \"alert()\"). ... If you do go the selenium route feel free to contact me if you get a blocker, I might be able to assist.\n"
] |
[
0
] |
[] |
[] |
[
"firefox",
"python",
"webdriver"
] |
stackoverflow_0001813044_firefox_python_webdriver.txt
|
Q:
A puzzle concerning Q objects and Foreign Keys
I've got a model like this:
class Thing(models.Model):
property1 = models.IntegerField()
property2 = models.IntegerField()
property3 = models.IntegerField()
class Subthing(models.Model):
subproperty = models.IntegerField()
thing = modelsForeignkey(Thing)
main = models.BooleanField()
I've got a function that is passed a list of filters where each filter is of the form {'type':something, 'value':x}. This function needs to return a set of results ANDing all the filters together:
final_q = Q()
for filter in filters:
q = None
if filter['type'] =='thing-property1':
q = Q(property1=filter['value'])
elif filter['type'] =='thing-property2':
q = Q(property2=filter['value'])
elif filter['type'] =='thing-property2':
q = Q(property3=filter['value'])
if q:
final_q = final_q & q
return Thing.objects.filter(final_q).distinct()
Each Subthing has a Boolean property 'main'. Every Thing has 1 and only 1 Subthing where main==True.
I now need to add filter that returns all the Things which have a Subthing where main==True and subproperty==filter['value']
Can I do this as part of the Q object I'm constructing? If not how else? The queryset I get before my new filter can be quite large so I would like a method that doesn't involve looping over the results.
A:
It's a bit easier to understand if you explicitly give your Subthings a "related_name" in their relationship to the Thing
class Subthing(models.Model):
...
thing = models.ForeignKey(Thing, related_name='subthings')
...
Now, you use Django join syntax to build your Q object:
Q(subthings__main=True) & Q(subthings__subproperty=filter['value'])
The reverse relationship has the default name 'subthing_set', but I find that it's easier to follow if you give it a better name like 'subthings'.
A:
Using (instead of final_q=Q() in the beginning)
final_q=Q(subthing_set__main=True)
sub_vals = map(lambda v: v['value'], filters)
if sub_vals:
final_q = final_q & Q(subthing_set__subproperty__in=sub_vals)
should get you what you want, you can also adjust your loop to build the sub_vals list and apply it after the loop.
subthing_set is and automatically added related field added to the Thing to access related Subthings.
you can assign another related name, e.g.
thing=models.ForeignKey(Thing,related_name='subthings')
|
A puzzle concerning Q objects and Foreign Keys
|
I've got a model like this:
class Thing(models.Model):
property1 = models.IntegerField()
property2 = models.IntegerField()
property3 = models.IntegerField()
class Subthing(models.Model):
subproperty = models.IntegerField()
thing = modelsForeignkey(Thing)
main = models.BooleanField()
I've got a function that is passed a list of filters where each filter is of the form {'type':something, 'value':x}. This function needs to return a set of results ANDing all the filters together:
final_q = Q()
for filter in filters:
q = None
if filter['type'] =='thing-property1':
q = Q(property1=filter['value'])
elif filter['type'] =='thing-property2':
q = Q(property2=filter['value'])
elif filter['type'] =='thing-property2':
q = Q(property3=filter['value'])
if q:
final_q = final_q & q
return Thing.objects.filter(final_q).distinct()
Each Subthing has a Boolean property 'main'. Every Thing has 1 and only 1 Subthing where main==True.
I now need to add filter that returns all the Things which have a Subthing where main==True and subproperty==filter['value']
Can I do this as part of the Q object I'm constructing? If not how else? The queryset I get before my new filter can be quite large so I would like a method that doesn't involve looping over the results.
|
[
"It's a bit easier to understand if you explicitly give your Subthings a \"related_name\" in their relationship to the Thing\nclass Subthing(models.Model):\n ...\n thing = models.ForeignKey(Thing, related_name='subthings')\n ...\n\nNow, you use Django join syntax to build your Q object:\nQ(subthings__main=True) & Q(subthings__subproperty=filter['value'])\n\nThe reverse relationship has the default name 'subthing_set', but I find that it's easier to follow if you give it a better name like 'subthings'.\n",
"Using (instead of final_q=Q() in the beginning)\nfinal_q=Q(subthing_set__main=True)\nsub_vals = map(lambda v: v['value'], filters)\nif sub_vals:\n final_q = final_q & Q(subthing_set__subproperty__in=sub_vals)\n\nshould get you what you want, you can also adjust your loop to build the sub_vals list and apply it after the loop.\nsubthing_set is and automatically added related field added to the Thing to access related Subthings.\nyou can assign another related name, e.g.\nthing=models.ForeignKey(Thing,related_name='subthings')\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"django_models",
"django_q",
"django_queryset",
"python"
] |
stackoverflow_0001813777_django_django_models_django_q_django_queryset_python.txt
|
Q:
Django, displaying a view in an another view?
I would like to know if I can display a view inside another view with django.
This is what I tried to do:
def displayRow(request, row_id):
row = Event.objects.get(pk=row_id)
return render_to_response('row.html', {'row': row})
def listEventsSummary(request):
listEventsSummary = Event.objects.all().order_by('-id')[:20]
response = ''
for event in listEventsSummary:
response += str(displayRow('',event.id))
return HttpResponse(response)
The output looks like what I was expecting but I have had to replace the request value with an empty string. Is that fine or is there a better way to do it?
A:
http response contains headers along with html, or anything else, so you can't just add them up like strings.
if you want to modularize your view function, then have sub-procedure calls return strings and then you can do it the way you propose
Probably in your case it would be better to put a loop showing rows into the template, then you won't need the sub-view and the loop in your main view.
def listEventsSummary(request):
listEventsSummary = Event.objects.all().order_by('-id')[:20]
return render_to_response('stuff.html',{'events':listEventsSummary})
and in stuff.html
{% for event in events %}
<p>{{event.date}} and whatever else...</p>
{% endfor %}
|
Django, displaying a view in an another view?
|
I would like to know if I can display a view inside another view with django.
This is what I tried to do:
def displayRow(request, row_id):
row = Event.objects.get(pk=row_id)
return render_to_response('row.html', {'row': row})
def listEventsSummary(request):
listEventsSummary = Event.objects.all().order_by('-id')[:20]
response = ''
for event in listEventsSummary:
response += str(displayRow('',event.id))
return HttpResponse(response)
The output looks like what I was expecting but I have had to replace the request value with an empty string. Is that fine or is there a better way to do it?
|
[
"http response contains headers along with html, or anything else, so you can't just add them up like strings.\nif you want to modularize your view function, then have sub-procedure calls return strings and then you can do it the way you propose\nProbably in your case it would be better to put a loop showing rows into the template, then you won't need the sub-view and the loop in your main view.\ndef listEventsSummary(request):\n listEventsSummary = Event.objects.all().order_by('-id')[:20]\n return render_to_response('stuff.html',{'events':listEventsSummary})\n\nand in stuff.html\n{% for event in events %}\n <p>{{event.date}} and whatever else...</p>\n{% endfor %}\n\n"
] |
[
4
] |
[] |
[] |
[
"django",
"django_views",
"python"
] |
stackoverflow_0001814255_django_django_views_python.txt
|
Q:
What is the idiomatic way of invoking a list of functions in Python?
I have a list of callback functions that I need to invoke when an event is fired.
Is this idiomatic python?
def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
A:
Use map only for functions without side effects (like print). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic:
for f in lst:
f("event_info")
Edit: also, as of Python 3.0, map returns an iterator instead of a list. Hence in Python 3.0 the code given in the question will not call any function, unless all elements in the generator are evaluated explicitly (e.g. by encapsulating the call to map inside list). Luckily the 2to3 tool will warn about this:
File map.py:
map(lambda x: x, range(10))
2to3-3.0 map.py output:
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
--- map.py (original)
+++ map.py (refactored)
@@ -1,1 +1,1 @@
-map(lambda x: x, range(10))
+list(map(lambda x: x, list(range(10))))
RefactoringTool: Files that need to be modified:
RefactoringTool: map.py
RefactoringTool: Warnings/messages while refactoring:
RefactoringTool: ### In file map.py ###
RefactoringTool: Line 1: You should use a for loop here
A:
You could also write a list comprehension:
[f("event_info") for f in lst]
However, it does have the side-effect of returning a list of results.
A:
If you have dynamically created list of functions simple for is good:
for function in list_of_functions:
function(your_argument_here)
But if you use OOP and some classes should know that some event happens (generally changes) consider introducing Observer design pattern:
http://en.wikipedia.org/wiki/Observer_pattern,
Introducing pattern means refactoring working code to that pattern (and stopping when code look good even if not whole patter was introduced) read more in "Refactoring to patterns" Kerievsky.
A:
I have to ask if this is truly the OP's intent. When I hear "invoke a list of functions", I assume that just looping over the list of functions and calling each one is so obvious, that there must be more to the question. For instance, given these two string manipulators:
def reverse(s):
return s[::-1]
import random
def randomcase(s):
return ''.join(random.choice((str.upper, str.lower))(c) for c in s)
manips = [reverse, randomcase]
s = "Now is the time for all good men to come to."
# boring loop through list of manips
for fn in manips:
print fn(s)
# more interesting chain through list of manips
s_out = s
for fn in manips:
s_out = fn(s_out)
print s_out
The first loop prints:
.ot emoc ot nem doog lla rof emit eht si woN
NOW IS THe tIMe for aLL good meN TO COme To.
The second chains the output of the first function to the input of the next, printing:
.oT EMoC OT NeM DOog lla RoF emit EHt SI won
This second method allows you to compose more complex functions out of several simple ones.
|
What is the idiomatic way of invoking a list of functions in Python?
|
I have a list of callback functions that I need to invoke when an event is fired.
Is this idiomatic python?
def first_callback(m):
print 'first ' + m
def second_callback(m):
print 'second ' + m
lst = [first_callback, second_callback]
map(lambda x: x("event_info"),lst) #is this how you do it?
|
[
"Use map only for functions without side effects (like print). That is, use it only for functions that just return something. In this case a regular loop is more idiomatic:\nfor f in lst:\n f(\"event_info\")\n\nEdit: also, as of Python 3.0, map returns an iterator instead of a list. Hence in Python 3.0 the code given in the question will not call any function, unless all elements in the generator are evaluated explicitly (e.g. by encapsulating the call to map inside list). Luckily the 2to3 tool will warn about this:\nFile map.py:\nmap(lambda x: x, range(10))\n\n2to3-3.0 map.py output:\nRefactoringTool: Skipping implicit fixer: buffer\nRefactoringTool: Skipping implicit fixer: idioms\nRefactoringTool: Skipping implicit fixer: set_literal\nRefactoringTool: Skipping implicit fixer: ws_comma\n--- map.py (original)\n+++ map.py (refactored)\n@@ -1,1 +1,1 @@\n-map(lambda x: x, range(10))\n+list(map(lambda x: x, list(range(10))))\nRefactoringTool: Files that need to be modified:\nRefactoringTool: map.py\nRefactoringTool: Warnings/messages while refactoring:\nRefactoringTool: ### In file map.py ###\nRefactoringTool: Line 1: You should use a for loop here\n\n",
"You could also write a list comprehension:\n[f(\"event_info\") for f in lst]\n\nHowever, it does have the side-effect of returning a list of results.\n",
"If you have dynamically created list of functions simple for is good:\nfor function in list_of_functions:\n function(your_argument_here)\nBut if you use OOP and some classes should know that some event happens (generally changes) consider introducing Observer design pattern:\nhttp://en.wikipedia.org/wiki/Observer_pattern,\nIntroducing pattern means refactoring working code to that pattern (and stopping when code look good even if not whole patter was introduced) read more in \"Refactoring to patterns\" Kerievsky.\n",
"I have to ask if this is truly the OP's intent. When I hear \"invoke a list of functions\", I assume that just looping over the list of functions and calling each one is so obvious, that there must be more to the question. For instance, given these two string manipulators:\ndef reverse(s):\n return s[::-1]\n\nimport random\ndef randomcase(s):\n return ''.join(random.choice((str.upper, str.lower))(c) for c in s)\n\nmanips = [reverse, randomcase]\ns = \"Now is the time for all good men to come to.\"\n\n# boring loop through list of manips\nfor fn in manips:\n print fn(s)\n\n# more interesting chain through list of manips\ns_out = s\nfor fn in manips:\n s_out = fn(s_out)\nprint s_out\n\nThe first loop prints:\n.ot emoc ot nem doog lla rof emit eht si woN\nNOW IS THe tIMe for aLL good meN TO COme To.\n\nThe second chains the output of the first function to the input of the next, printing:\n.oT EMoC OT NeM DOog lla RoF emit EHt SI won\n\nThis second method allows you to compose more complex functions out of several simple ones.\n"
] |
[
18,
3,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0000897362_python.txt
|
Q:
Global disk resource becomes unavailable
If I've got a global disk resource (mount point on an isilon file server) that multiple servers use to access a lock file. What is a good way to handle the situation if that global disk becomes unavailable and the servers can't access the global lock file?
Thanks,
Doug
A:
If this happens intermittently, you might just want to try waiting a short period and retrying. Other than that... log the error and fail. Maybe throw an exception that someone higher up can catch and deal with more gracefully.
|
Global disk resource becomes unavailable
|
If I've got a global disk resource (mount point on an isilon file server) that multiple servers use to access a lock file. What is a good way to handle the situation if that global disk becomes unavailable and the servers can't access the global lock file?
Thanks,
Doug
|
[
"If this happens intermittently, you might just want to try waiting a short period and retrying. Other than that... log the error and fail. Maybe throw an exception that someone higher up can catch and deal with more gracefully.\n"
] |
[
1
] |
[] |
[] |
[
"fileserver",
"flock",
"linux",
"python"
] |
stackoverflow_0001814393_fileserver_flock_linux_python.txt
|
Q:
Python: How to shutdown a threaded HTTP server with persistent connections (how to kill readline() from another thread)?
I'm using python2.6 with HTTPServer and the ThreadingMixIn, which will handle each request in a separate thread. I'm also using HTTP1.1 persistent connections ('Connection: keep-alive'), so neither the server or client will close a connection after a request.
Here's roughly what the request handler looks like
request, client_address = sock.accept()
rfile = request.makefile('rb', rbufsize)
wfile = request.makefile('wb', wbufsize)
global server_stopping
while not server_stopping:
request_line = rfile.readline() # 'GET / HTTP/1.1'
# etc - parse the full request, write to wfile with server response, etc
wfile.close()
rfile.close()
request.close()
The problem is that if I stop the server, there will still be a few threads waiting on rfile.readline().
I would put a select([rfile, closefile], [], []) above the readline() and write to closefile when I want to shutdown the server, but I don't think it would work on windows because select only works with sockets.
My other idea is to keep track of all the running requests and rfile.close() but I get Broken pipe errors.
Ideas?
A:
You're almost there—the correct approach is to call rfile.close() and to catch the broken pipe errors and exit your loop when that happens.
A:
If you set daemon_threads to true in your HTTPServer subclass, the activity of the threads will not prevent the server from exiting.
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
A:
You could work around the Windows problem by making closefile a socket, too -- after all, since it's presumably something that's opened by your main thread, it's up to you to decide whether to open it as a socket or a file;-).
|
Python: How to shutdown a threaded HTTP server with persistent connections (how to kill readline() from another thread)?
|
I'm using python2.6 with HTTPServer and the ThreadingMixIn, which will handle each request in a separate thread. I'm also using HTTP1.1 persistent connections ('Connection: keep-alive'), so neither the server or client will close a connection after a request.
Here's roughly what the request handler looks like
request, client_address = sock.accept()
rfile = request.makefile('rb', rbufsize)
wfile = request.makefile('wb', wbufsize)
global server_stopping
while not server_stopping:
request_line = rfile.readline() # 'GET / HTTP/1.1'
# etc - parse the full request, write to wfile with server response, etc
wfile.close()
rfile.close()
request.close()
The problem is that if I stop the server, there will still be a few threads waiting on rfile.readline().
I would put a select([rfile, closefile], [], []) above the readline() and write to closefile when I want to shutdown the server, but I don't think it would work on windows because select only works with sockets.
My other idea is to keep track of all the running requests and rfile.close() but I get Broken pipe errors.
Ideas?
|
[
"You're almost there—the correct approach is to call rfile.close() and to catch the broken pipe errors and exit your loop when that happens.\n",
"If you set daemon_threads to true in your HTTPServer subclass, the activity of the threads will not prevent the server from exiting.\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n daemon_threads = True\n\n",
"You could work around the Windows problem by making closefile a socket, too -- after all, since it's presumably something that's opened by your main thread, it's up to you to decide whether to open it as a socket or a file;-).\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"multithreading",
"python",
"sockets"
] |
stackoverflow_0001814575_multithreading_python_sockets.txt
|
Q:
How to search a HTML page for an item in a given list
I have a list of schools
schools = ['Harvard Law School', 'Stanford Law School', 'Yale Law School', 'Columbia Law School', 'NYU School of Law', 'University of Chicago Law School']
and bios of lawyers that contain one of these schools:
html = "page that contains one of these schools"
like this
"<strong><em>Education</em></strong><br />JD, Columbia Law School, Harlan Fiske Stone Scholar, Parker School Recognition of Achievement in International and Foreign Law, 2005<br />BM, BM, University of Michigan - Ann Arbor, <EM>summa cum laude</EM>, 1997<br />"
I've been extracting the school info with regex. But I thought it would be better to have a lookup list of schools and search each page for the matching school. I'm new to Python so I was searching about how to do this and I found difflib.SequenceMatcher.
I've been playing with it, and it's fun but I don't think it is the right tool for what I want to do. Can anyone direct me to the right way of doing this?
Thanks!
A:
I don't know nothing about Python but I often create dynamic regex expressions into a string like:
"(school 1|school 2|school 3|school n)"
Then I instantiate a regex object, passing the string.
You can then match your schools, regardless of the form of the document unless a HTML tag is in the middle of a school name.
Mike
EDIT - example (sorry c#): "(" + String.Join("|", arrayOfSchools) + ")"
A:
This is a very basic screen scraping way to achieve what you want
import urllib
html = urllib.urlopen(pageToLawyersBio)
htmlstr=''
for line in html.readlines():
htmlstr += line.lower()
for school in listOfSchools:
if school.lower() in htmlstr:
print "This lawyer went to", school
A:
I hate to rain on your parade, but building a lookup list of law schools and then doing a set membership type of test in the source code probably will not work. The flawed approach:
schools = []
html = page.read()
for school in list:
if school in html:
schools.append(school)
The reason why is this: you're assuming law school names are represented uniformly on lawyer websites, but that assumption isn't reliable. For example, I went to a law school called University of California, Hastings College of the Law. Sometimes it appears on lawyer websites as Hastings College of Law, and others it appears as UC Hastings. Often the data about where a lawyer went to school is collected directly from the lawyer, so it will appear verbatim as he or she supplied it. You probably can't assume the data was later normalized.
As a result, any school names that deviate from your lookup list won't be found. To further complicate matters, the shortest version of my school's name--UC Hastings--might even confound a difflib 'get close matches' lookup unless you set the match ratio very low, which inevitably causes the routine to find a number of other false positives as well.
Here's my advice. Spider a list of all law school names and put it in a database table. Create a second table with known deviations from the list. Each time you spider a site, try a basic set membership test in the lookup list (or dynamically generated regex). In the probable event that such a lookup fails, make the script throw an error and print the unmatched school to a console. Add that school the table of known variants and key it to the correct school name in the main lookup table. Repeat this process until you feel confident you have most variants accounted for. From there, add a hack to check unfound school names against a list of the official lookup items and all known variants using
difflib.get_close_matches
Use this kind of method to return the closest valid match any time a school isn't found. It may be the best your clients can ask for. I use django for this kind of thing because the built-in database admin makes it easy to add in known variants.
A:
I would need to know which school matches.
Now I am extracting the school info with regex (I am still testing):
item = re.search('(JD)(.*?)(\d+)', html)
if item:
JD = item.group()
f = open('test1.txt', 'a')
f.write(JD)
else:
NoJD = ("empty cvs schema goes here")
f = open('test1.txt', 'a')
f.write(NoJD)
This picks up the relevant part from the html:
JD, Columbia Law School, Harlan Fiske Stone Scholar, Parker School Recognition of Achievement in International and Foreign Law, 2005
I still need to parse this to format properly so that I can write it into an items.csv file:
first,initial,last,title,firm,school,year
So, I thought that if i looked for matches for schools, I could pick up the school names (and year graduated) by looking up a school list. But if this is too complicated I'll go ahead with the regex.
Thanks.
A:
You should consider using beautifulSoup to parse the HTML. In regards to your question, you might want to try something like:
for line in html.split("<br \>"):
# This gives a lot of crap, filter it with
for values in line.split(", "):
try:
if values[0] in schools:
#This line contains a school, write it out.
except:
# Ignore badly formatted lines
pass
A:
inspectorG4dgt: This is great! thanks. I think this better than using regex. Because in some pages "JD" comes before school name, in others, after the school name. Same with the graduation dates.
I have been trying to get the line where the school names occurs but I couldn't do it. Something like this:
htmlstr = ''
for line in html.readlines():
htmlstr += line.lower()
for school in listOfSchools:
if school.lower() in htmlstr:
[ schoolLine = line with the school and date ]
To learn more about this stuff I've been studying this tutorial.
For instance, I tried to use readline() to loop on each line but that didn't work.
Or it may be better to search for listOfSchools and a list of years = [1956, ... 2008]. Since schools and dates are on the same lines. Any suggestions how I can do this? Thanks.
|
How to search a HTML page for an item in a given list
|
I have a list of schools
schools = ['Harvard Law School', 'Stanford Law School', 'Yale Law School', 'Columbia Law School', 'NYU School of Law', 'University of Chicago Law School']
and bios of lawyers that contain one of these schools:
html = "page that contains one of these schools"
like this
"<strong><em>Education</em></strong><br />JD, Columbia Law School, Harlan Fiske Stone Scholar, Parker School Recognition of Achievement in International and Foreign Law, 2005<br />BM, BM, University of Michigan - Ann Arbor, <EM>summa cum laude</EM>, 1997<br />"
I've been extracting the school info with regex. But I thought it would be better to have a lookup list of schools and search each page for the matching school. I'm new to Python so I was searching about how to do this and I found difflib.SequenceMatcher.
I've been playing with it, and it's fun but I don't think it is the right tool for what I want to do. Can anyone direct me to the right way of doing this?
Thanks!
|
[
"I don't know nothing about Python but I often create dynamic regex expressions into a string like:\n\"(school 1|school 2|school 3|school n)\"\nThen I instantiate a regex object, passing the string.\nYou can then match your schools, regardless of the form of the document unless a HTML tag is in the middle of a school name.\nMike\nEDIT - example (sorry c#): \"(\" + String.Join(\"|\", arrayOfSchools) + \")\"\n",
"This is a very basic screen scraping way to achieve what you want\nimport urllib\nhtml = urllib.urlopen(pageToLawyersBio)\n\nhtmlstr=''\nfor line in html.readlines():\n htmlstr += line.lower()\n\nfor school in listOfSchools:\n if school.lower() in htmlstr:\n print \"This lawyer went to\", school\n\n",
"I hate to rain on your parade, but building a lookup list of law schools and then doing a set membership type of test in the source code probably will not work. The flawed approach:\nschools = []\nhtml = page.read()\nfor school in list:\n if school in html:\n schools.append(school)\n\nThe reason why is this: you're assuming law school names are represented uniformly on lawyer websites, but that assumption isn't reliable. For example, I went to a law school called University of California, Hastings College of the Law. Sometimes it appears on lawyer websites as Hastings College of Law, and others it appears as UC Hastings. Often the data about where a lawyer went to school is collected directly from the lawyer, so it will appear verbatim as he or she supplied it. You probably can't assume the data was later normalized.\nAs a result, any school names that deviate from your lookup list won't be found. To further complicate matters, the shortest version of my school's name--UC Hastings--might even confound a difflib 'get close matches' lookup unless you set the match ratio very low, which inevitably causes the routine to find a number of other false positives as well. \nHere's my advice. Spider a list of all law school names and put it in a database table. Create a second table with known deviations from the list. Each time you spider a site, try a basic set membership test in the lookup list (or dynamically generated regex). In the probable event that such a lookup fails, make the script throw an error and print the unmatched school to a console. Add that school the table of known variants and key it to the correct school name in the main lookup table. Repeat this process until you feel confident you have most variants accounted for. From there, add a hack to check unfound school names against a list of the official lookup items and all known variants using \ndifflib.get_close_matches\n\nUse this kind of method to return the closest valid match any time a school isn't found. It may be the best your clients can ask for. I use django for this kind of thing because the built-in database admin makes it easy to add in known variants. \n",
"I would need to know which school matches.\nNow I am extracting the school info with regex (I am still testing):\n item = re.search('(JD)(.*?)(\\d+)', html)\n if item:\n JD = item.group()\n f = open('test1.txt', 'a')\n f.write(JD)\n else:\n NoJD = (\"empty cvs schema goes here\")\n f = open('test1.txt', 'a')\n f.write(NoJD) \n\nThis picks up the relevant part from the html:\nJD, Columbia Law School, Harlan Fiske Stone Scholar, Parker School Recognition of Achievement in International and Foreign Law, 2005\nI still need to parse this to format properly so that I can write it into an items.csv file:\nfirst,initial,last,title,firm,school,year\nSo, I thought that if i looked for matches for schools, I could pick up the school names (and year graduated) by looking up a school list. But if this is too complicated I'll go ahead with the regex.\nThanks.\n",
"You should consider using beautifulSoup to parse the HTML. In regards to your question, you might want to try something like:\nfor line in html.split(\"<br \\>\"):\n # This gives a lot of crap, filter it with\n for values in line.split(\", \"):\n try: \n if values[0] in schools:\n #This line contains a school, write it out.\n except:\n # Ignore badly formatted lines\n pass\n\n",
"inspectorG4dgt: This is great! thanks. I think this better than using regex. Because in some pages \"JD\" comes before school name, in others, after the school name. Same with the graduation dates. \nI have been trying to get the line where the school names occurs but I couldn't do it. Something like this:\nhtmlstr = ''\nfor line in html.readlines():\n htmlstr += line.lower()\n\nfor school in listOfSchools:\n if school.lower() in htmlstr:\n [ schoolLine = line with the school and date ]\n\nTo learn more about this stuff I've been studying this tutorial.\nFor instance, I tried to use readline() to loop on each line but that didn't work. \nOr it may be better to search for listOfSchools and a list of years = [1956, ... 2008]. Since schools and dates are on the same lines. Any suggestions how I can do this? Thanks.\n"
] |
[
1,
1,
1,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001813921_python.txt
|
Q:
New transport and reader type in Twisted
I'm trying to add a new transport to Twisted, which will read data from a stream - either a file in a tail -f way, or from a pipe, but I have some problems with Twisted architecture.
I've got the transport itself (implements ITransport) ready - it handles all file opening. I've got streaming functions/deferreds ready. How do I put it together now? I'd like to report the new data back to some protocol's dataReceived().
I could of course create a new object that will set up the I/O monitors with proper callbacks, register a callback on reactor shutting down (to close the files / protocols) and start everything up manually - but is that "the right way"? Is there any nicer abstraction I could use? I've seen reactor.connectWith(), but it doesn't really provide much of an abstraction...
Also - how am I supposed to pass the data from my reader to the protocol? ITransport doesn't define any interface for it, even though it seems like exactly the transport's responsibility.
A:
It sounds like you've mostly figured out how to do this. You might be interested in twisted.internet.fdesc.readFromFD, but it's only a few lines long and it's not doing anything particularly complicated (it's a few lines you don't have to maintain, though). Aside from that - yes, you have to do the I/O monitoring in this case, because regular file descriptors aren't supported by select/poll/epoll (they always get reported as ready, not what you want).
Some work has been done on supporting inotify in Twisted (http://twistedmatrix.com/trac/ticket/972) but this isn't complete yet, so it's not going to be directly useful to you now (unless you want to help finish it and then use it). Assuming you just use time-based polling, much of what's in the reactor isn't going to help you out much, since that code is focused on using a system-provided readiness API (ie, select/poll/epoll) to trigger events.
For the pipe case, though, you should be able to use and benefit from IReactorFDSet's methods - addReader et al.
Your time-based polling transport may still benefit from implementing ITransport - although I'm not sure how you would implement write for a tail -f-like transport. You will definitely benefit from having your transport deliver data via the IProtocol interface, since this simplifies code-reuse. IProtocol.dataReceived is exactly how you want to pass data from your reader (I think that's the same as your transport, isn't it?). This isn't defined on ITransport because it's a method you call on some other object which is not the transport.
reactor.connectWith probably isn't going to buy you anything. As you say, it's not much of an abstraction; I'd say it's more of a mistake. :)
Don't worry too much about not being able to add methods directly to the reactor. A free-function which accepts a reactor as a parameter is just as easy to use.
For the shutdown callback, addReader should actually get you most of the way there. Any reader in the reactor at shutdown time will have connectionLost called on it (part of IFileDescriptor). You should implement this to clean up the files and protocol.
|
New transport and reader type in Twisted
|
I'm trying to add a new transport to Twisted, which will read data from a stream - either a file in a tail -f way, or from a pipe, but I have some problems with Twisted architecture.
I've got the transport itself (implements ITransport) ready - it handles all file opening. I've got streaming functions/deferreds ready. How do I put it together now? I'd like to report the new data back to some protocol's dataReceived().
I could of course create a new object that will set up the I/O monitors with proper callbacks, register a callback on reactor shutting down (to close the files / protocols) and start everything up manually - but is that "the right way"? Is there any nicer abstraction I could use? I've seen reactor.connectWith(), but it doesn't really provide much of an abstraction...
Also - how am I supposed to pass the data from my reader to the protocol? ITransport doesn't define any interface for it, even though it seems like exactly the transport's responsibility.
|
[
"It sounds like you've mostly figured out how to do this. You might be interested in twisted.internet.fdesc.readFromFD, but it's only a few lines long and it's not doing anything particularly complicated (it's a few lines you don't have to maintain, though). Aside from that - yes, you have to do the I/O monitoring in this case, because regular file descriptors aren't supported by select/poll/epoll (they always get reported as ready, not what you want).\nSome work has been done on supporting inotify in Twisted (http://twistedmatrix.com/trac/ticket/972) but this isn't complete yet, so it's not going to be directly useful to you now (unless you want to help finish it and then use it). Assuming you just use time-based polling, much of what's in the reactor isn't going to help you out much, since that code is focused on using a system-provided readiness API (ie, select/poll/epoll) to trigger events.\nFor the pipe case, though, you should be able to use and benefit from IReactorFDSet's methods - addReader et al.\nYour time-based polling transport may still benefit from implementing ITransport - although I'm not sure how you would implement write for a tail -f-like transport. You will definitely benefit from having your transport deliver data via the IProtocol interface, since this simplifies code-reuse. IProtocol.dataReceived is exactly how you want to pass data from your reader (I think that's the same as your transport, isn't it?). This isn't defined on ITransport because it's a method you call on some other object which is not the transport.\nreactor.connectWith probably isn't going to buy you anything. As you say, it's not much of an abstraction; I'd say it's more of a mistake. :)\nDon't worry too much about not being able to add methods directly to the reactor. A free-function which accepts a reactor as a parameter is just as easy to use.\nFor the shutdown callback, addReader should actually get you most of the way there. Any reader in the reactor at shutdown time will have connectionLost called on it (part of IFileDescriptor). You should implement this to clean up the files and protocol.\n"
] |
[
5
] |
[] |
[] |
[
"architecture",
"protocols",
"python",
"transport",
"twisted"
] |
stackoverflow_0001814467_architecture_protocols_python_transport_twisted.txt
|
Q:
Display gaps in dates with Python and Django
I'm building an application that requires each user to make a post on a daily basis. I'd like to display the gaps in dates where users haven't made posts. Since it doesn't seem like a good idea to insert empty database rows for empty posts, I'm only inserting a record when the user adds a post.
The model contains a field named log_date. I'm at a loss for how to display the gaps in the Django template. This is how I'd like the output in the template to look like:
2009-11-25
2009-11-24
2009-11-23 NO ENTRY
2009-11-22 NO ENTRY
2009-11-21
Thanks in advance for any help. Let me know if I can provide additional details.
A:
I recommend building a set of dates that a user has posted, then start at the earliest date and iterate until the current day. For each day, print the date and check whether a post exists for that day. By using a set we can do this check in constant time, not that this will likely matter.
days = set( Post.objects.filter(user=TARGET).values_list("log_date", flat=True) )
curr = min(days)
while curr <= date.today():
print curr,
if curr not in days:
print "NO ENTRY",
print
curr += timedelta(days=1)
I realize that this isn't Django template code, but this should give you a good starting point from which to build a good template.
|
Display gaps in dates with Python and Django
|
I'm building an application that requires each user to make a post on a daily basis. I'd like to display the gaps in dates where users haven't made posts. Since it doesn't seem like a good idea to insert empty database rows for empty posts, I'm only inserting a record when the user adds a post.
The model contains a field named log_date. I'm at a loss for how to display the gaps in the Django template. This is how I'd like the output in the template to look like:
2009-11-25
2009-11-24
2009-11-23 NO ENTRY
2009-11-22 NO ENTRY
2009-11-21
Thanks in advance for any help. Let me know if I can provide additional details.
|
[
"I recommend building a set of dates that a user has posted, then start at the earliest date and iterate until the current day. For each day, print the date and check whether a post exists for that day. By using a set we can do this check in constant time, not that this will likely matter.\ndays = set( Post.objects.filter(user=TARGET).values_list(\"log_date\", flat=True) )\ncurr = min(days)\nwhile curr <= date.today():\n print curr,\n if curr not in days:\n print \"NO ENTRY\",\n print\n curr += timedelta(days=1)\n\nI realize that this isn't Django template code, but this should give you a good starting point from which to build a good template.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001814664_django_python.txt
|
Q:
What is wrong with my "digit finder" in python?
I am learning python through the Project Euler problems. For problem 40 I wrote this code:
import math
i = 1
counter = 0
while counter <= 1000000:
MMM = int(math.log(i, 10)) + 1
counter = counter + MMM
V = math.log(i, 10)
print(i, counter, MMM, V)
i += 1
It is supposed to return the number containing the Nth digit. Basically, this is supposed to keep track of what would happen if I concatenated the integers from 1 through whatever into another number. The goal is to determine what a specific digit is. This code works below a certain threshold, however, by the time it gets to the millionth digit it is off by one. What am I missing here? I have seen other implementations that save time, but I am more interested in why the count becomes wrong at some point
Edit:
replacing
MMM = int(math.log(i, 10)) + 1
with
MMM = len(str(i))
works like a champ!
Although it would be nice to have an all numeric solution, It'll have to wait until I can trust log functions in Python.
A:
Floating point error somewhere along the way? It might be possible that at some point math.log is returning something that's barely less than (or greater, depending on the direction of your off-by-1 result) an integer boundary and thus int() is truncating it to the wrong value. Floating-point numbers are not precise for numbers which can't be represented using a certain number of binary digits.
A:
I think this is the problem line
MMM = int(math.log(i, 10)) + 1
Some examples
>>> int(math.log(1000000, 10)) + 1
6
>>> int(math.log(1000001, 10)) + 1
7
Whereas I suspect you really wanted
>>> len(str(1000000))
7
>>> len(str(1000001))
7
Edit Actually (as you suggested!) math.log10 seems to be the best solution and more in line with what you wrote originally
>>> int(math.log10(10000000))
7
>>> int(math.log10(10000001))
7
>>> int(math.log10(10**1000))
1000
>>> int(math.log10(10**10000))
10000
>>> int(math.log10(10**100000))
100000
math.log10 must keep the accuracy better than math.log(x, 10)
A:
The issue here is one of precision of floating point numbers which is not amazing. I gets fuzzier and fuzzier as the number of digits increase. This is the basic nature of floating point numbers, when you are doing this kind of math you need to be aware what precision you require.
The standard library module decimal allows you fine grained control of the precision of decimal values. Since this module is not hardware bases allows the user alter the precision of floating point number (the default is 28 places). You create decimal numbers like below:
import decimal
x = decimal.Decimal(1000000)
x.log10()
You can alter the precision you require like this: decimal.getcontext().prec = 8
|
What is wrong with my "digit finder" in python?
|
I am learning python through the Project Euler problems. For problem 40 I wrote this code:
import math
i = 1
counter = 0
while counter <= 1000000:
MMM = int(math.log(i, 10)) + 1
counter = counter + MMM
V = math.log(i, 10)
print(i, counter, MMM, V)
i += 1
It is supposed to return the number containing the Nth digit. Basically, this is supposed to keep track of what would happen if I concatenated the integers from 1 through whatever into another number. The goal is to determine what a specific digit is. This code works below a certain threshold, however, by the time it gets to the millionth digit it is off by one. What am I missing here? I have seen other implementations that save time, but I am more interested in why the count becomes wrong at some point
Edit:
replacing
MMM = int(math.log(i, 10)) + 1
with
MMM = len(str(i))
works like a champ!
Although it would be nice to have an all numeric solution, It'll have to wait until I can trust log functions in Python.
|
[
"Floating point error somewhere along the way? It might be possible that at some point math.log is returning something that's barely less than (or greater, depending on the direction of your off-by-1 result) an integer boundary and thus int() is truncating it to the wrong value. Floating-point numbers are not precise for numbers which can't be represented using a certain number of binary digits.\n",
"I think this is the problem line\nMMM = int(math.log(i, 10)) + 1\n\nSome examples\n>>> int(math.log(1000000, 10)) + 1\n6\n>>> int(math.log(1000001, 10)) + 1\n7\n\nWhereas I suspect you really wanted\n>>> len(str(1000000))\n7\n>>> len(str(1000001))\n7\n\nEdit Actually (as you suggested!) math.log10 seems to be the best solution and more in line with what you wrote originally\n>>> int(math.log10(10000000))\n7\n>>> int(math.log10(10000001))\n7\n>>> int(math.log10(10**1000))\n1000\n>>> int(math.log10(10**10000))\n10000\n>>> int(math.log10(10**100000))\n100000\n\nmath.log10 must keep the accuracy better than math.log(x, 10)\n",
"The issue here is one of precision of floating point numbers which is not amazing. I gets fuzzier and fuzzier as the number of digits increase. This is the basic nature of floating point numbers, when you are doing this kind of math you need to be aware what precision you require. \nThe standard library module decimal allows you fine grained control of the precision of decimal values. Since this module is not hardware bases allows the user alter the precision of floating point number (the default is 28 places). You create decimal numbers like below:\n import decimal\n x = decimal.Decimal(1000000)\n x.log10()\n\nYou can alter the precision you require like this: decimal.getcontext().prec = 8\n"
] |
[
4,
3,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001814933_python.txt
|
Q:
How do I check the index of a an element in a list? (Python)
list = [('ba',4), ('hh',5), ('gg', 25)]
How do I do:
list.index('hh') ...and returns 1?
Then, how do I sort it by the 25, 5, 4?
What if I have 2 lists:
list1 = [('ba',4), ('hh',5), ('gg', 25)]
list2 = [('ja',40), ('hgh',88), ('hh', 2)]
how do I do a for each?
for item in l1:
if item[0] in l2[0 of the tuple]:
A:
First of, don't use list as the name for a variable, as it shadows the built-in list function.
You can use enumerate to pair up list elements and their index:
>>> l = [('ba',4), ('hh',5), ('gg', 25)]
>>> [i for i, e in enumerate(l) if e[0] == 'hh']
[1]
For sorting you can use a lambda expression as shown by others, or you can pass an operator.itemgetter as the key argument to sorted:
>>> from operator import itemgetter
>>> sorted(l, key=itemgetter(1))
[('ba', 4), ('hh', 5), ('gg', 25)]
In-place sorting is also possible, using the sort method on lists:
>>> l.sort(key=itemgetter(1))
A:
For the finding
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> [ i for i,l in enumerate(L) if l[0] == 'hh' ][0]
1
You need to decide what to do if it is found multiple times or not at all - the above will throw IndexError if not found and return the first if it is found multiple times.
For the sorting
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=lambda x: x[1])
[('ba', 4), ('hh', 5), ('gg', 25)]
A:
I think Nick's sorting answer is good, but his find method unnecessarily iterates over the entire list, even after it has found a match. With a small change it can be fixed to stop iterating as soon as it finds the first element:
index = (i for i,l in enumerate(l) if l[0] == 'aa').next()
Or in Python 3:
index = next(i for i,l in enumerate(l) if l[0] == 'aa')
A:
to sort the list u can use a custom sort method some thing like this
x = [('ba',4), ('hh',5), ('gg', 25)]
def sortMethod(x,y):
if x[1] < y[1]:return 1
elif x[1] > y[1]:return -1
else: return 0
print x #unsorted
x.sort(sortMethod)
print x #sorted
A:
you can also have your list in dictionary form
list1 = [('ba',4), ('hh',5), ('gg', 25)]
dict1 = dict(list1)
print dict1['hh']
5
dicts are faster then list if you need to search like that.
btw, overriding built-in type list to variables are not good idea list = [('ba',4), ('hh',5), ('gg', 25)].
A:
For the sort, you should use itemgetter
>>> import operator
>>> L = [('ba',4), ('hh',5), ('gg', 25)]
>>> sorted(L, key=operator.itemgetter(1))
[('ba', 4), ('hh', 5), ('gg', 25)]
A:
from itertools import imap
def find(iterable, item, key=None):
"""Find `item` in `iterable`.
Return index of the found item or ``-1`` if there is none.
Apply `key` function to items before comparison with
`item`. ``key=None`` means an identity function.
"""
it = iter(iterable) if key is None else imap(key, iterable)
for i, e in enumerate(it):
if e == item:
return i
return -1
Example:
L = [('ba', 4), ('hh', 5), ('gg', 25)]
print find(L, 'hh', key=lambda x: x[0])
Output:
1
A:
For the last question, convert list2 into a set:
>>> list1 = [('ba',4), ('hh',5), ('gg', 25)]
>>> list2 = [('ja',40), ('hgh',88), ('hh', 2)]
>>>
>>> wanted = set(a for (a,b) in list2)
>>> for x in list1:
... if x[0] in wanted:
... print x
...
('hh', 5)
|
How do I check the index of a an element in a list? (Python)
|
list = [('ba',4), ('hh',5), ('gg', 25)]
How do I do:
list.index('hh') ...and returns 1?
Then, how do I sort it by the 25, 5, 4?
What if I have 2 lists:
list1 = [('ba',4), ('hh',5), ('gg', 25)]
list2 = [('ja',40), ('hgh',88), ('hh', 2)]
how do I do a for each?
for item in l1:
if item[0] in l2[0 of the tuple]:
|
[
"First of, don't use list as the name for a variable, as it shadows the built-in list function.\n\nYou can use enumerate to pair up list elements and their index:\n>>> l = [('ba',4), ('hh',5), ('gg', 25)]\n>>> [i for i, e in enumerate(l) if e[0] == 'hh']\n[1]\n\nFor sorting you can use a lambda expression as shown by others, or you can pass an operator.itemgetter as the key argument to sorted:\n>>> from operator import itemgetter\n>>> sorted(l, key=itemgetter(1))\n[('ba', 4), ('hh', 5), ('gg', 25)]\n\nIn-place sorting is also possible, using the sort method on lists:\n>>> l.sort(key=itemgetter(1))\n\n\n",
"For the finding\n>>> L = [('ba',4), ('hh',5), ('gg', 25)]\n>>> [ i for i,l in enumerate(L) if l[0] == 'hh' ][0]\n1\n\nYou need to decide what to do if it is found multiple times or not at all - the above will throw IndexError if not found and return the first if it is found multiple times.\nFor the sorting\n>>> L = [('ba',4), ('hh',5), ('gg', 25)]\n>>> sorted(L, key=lambda x: x[1])\n[('ba', 4), ('hh', 5), ('gg', 25)]\n\n",
"I think Nick's sorting answer is good, but his find method unnecessarily iterates over the entire list, even after it has found a match. With a small change it can be fixed to stop iterating as soon as it finds the first element:\nindex = (i for i,l in enumerate(l) if l[0] == 'aa').next()\n\nOr in Python 3:\nindex = next(i for i,l in enumerate(l) if l[0] == 'aa')\n\n",
"to sort the list u can use a custom sort method some thing like this\nx = [('ba',4), ('hh',5), ('gg', 25)]\n\ndef sortMethod(x,y):\n if x[1] < y[1]:return 1\n elif x[1] > y[1]:return -1\n else: return 0\n\n\nprint x #unsorted\nx.sort(sortMethod)\nprint x #sorted\n\n",
"you can also have your list in dictionary form\nlist1 = [('ba',4), ('hh',5), ('gg', 25)]\ndict1 = dict(list1)\n\nprint dict1['hh']\n5\n\ndicts are faster then list if you need to search like that.\nbtw, overriding built-in type list to variables are not good idea list = [('ba',4), ('hh',5), ('gg', 25)].\n",
"For the sort, you should use itemgetter\n>>> import operator\n>>> L = [('ba',4), ('hh',5), ('gg', 25)]\n>>> sorted(L, key=operator.itemgetter(1))\n[('ba', 4), ('hh', 5), ('gg', 25)]\n\n",
"from itertools import imap\n\ndef find(iterable, item, key=None):\n \"\"\"Find `item` in `iterable`.\n\n Return index of the found item or ``-1`` if there is none.\n\n Apply `key` function to items before comparison with\n `item`. ``key=None`` means an identity function.\n \"\"\"\n it = iter(iterable) if key is None else imap(key, iterable)\n for i, e in enumerate(it):\n if e == item:\n return i\n return -1\n\nExample:\nL = [('ba', 4), ('hh', 5), ('gg', 25)]\nprint find(L, 'hh', key=lambda x: x[0])\n\nOutput:\n1\n\n",
"For the last question, convert list2 into a set:\n>>> list1 = [('ba',4), ('hh',5), ('gg', 25)]\n>>> list2 = [('ja',40), ('hgh',88), ('hh', 2)]\n>>> \n>>> wanted = set(a for (a,b) in list2)\n>>> for x in list1:\n... if x[0] in wanted:\n... print x\n... \n('hh', 5)\n\n"
] |
[
5,
3,
2,
1,
1,
1,
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001815258_list_python.txt
|
Q:
How to pass an unicode char argument to ImageMagick?
Suppose the char of "▣" is in somefont.ttf's glyph table.
char = unichr(9635)
subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', '-label:%s' % char, 'output.png'])
subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', ('-label:%s' % char).encode('utf-8'), 'output.png'])
Both create an blank image with no char of "▣" on it. Is above code correct? Or the problem is on ImageMagick side which doesn't capture label in certain ranges?
The reason for using ImageMagick to draw text is it's more flexible than PIL to fix and align text to certain image size.
EDIT:
According to yuku's suggestion, I tried the following methods:
root@host:~@convert -font somefont.ttf -size 50x65 label:▣ output.png
root@host:~@convert -font somefont.ttf -size 50x65 label:'▣' output.png
Both outputs a question mark but not the correct character.
A:
According to this link, you need to pass the text encoded in UTF8.
It will be able to draw the correct character outside ASCII range.
A:
Try to get it working by hand using ASCII labels in your console.
$ convert -font somefont.ttf -size 50x50 -label:A output.png
convert: unrecognized option `-label:A' @ convert.c/ConvertImageCommand/1753.
1 ;(
$ convert -font somefont.ttf -size 50x50 -label A output.png
convert: missing an image filename `output.png' @ convert.c/ConvertImageComm\
and/2775.
1 ;(
Use subprocess.check_call instead of os.system.
import subprocess
if __name__=="__main__":
cmd = 'convert -font somefont.ttf -size 50x50'.split()
#XXX command arguments are invalid
subprocess.check_call(cmd + ['-label', unichr(9635), 'output.png'])
|
How to pass an unicode char argument to ImageMagick?
|
Suppose the char of "▣" is in somefont.ttf's glyph table.
char = unichr(9635)
subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', '-label:%s' % char, 'output.png'])
subprocess.call(['convert', '-font', 'somefont.ttf', '-size', '50x50', ('-label:%s' % char).encode('utf-8'), 'output.png'])
Both create an blank image with no char of "▣" on it. Is above code correct? Or the problem is on ImageMagick side which doesn't capture label in certain ranges?
The reason for using ImageMagick to draw text is it's more flexible than PIL to fix and align text to certain image size.
EDIT:
According to yuku's suggestion, I tried the following methods:
root@host:~@convert -font somefont.ttf -size 50x65 label:▣ output.png
root@host:~@convert -font somefont.ttf -size 50x65 label:'▣' output.png
Both outputs a question mark but not the correct character.
|
[
"According to this link, you need to pass the text encoded in UTF8.\nIt will be able to draw the correct character outside ASCII range.\n",
"\nTry to get it working by hand using ASCII labels in your console.\n\n\n $ convert -font somefont.ttf -size 50x50 -label:A output.png\n convert: unrecognized option `-label:A' @ convert.c/ConvertImageCommand/1753.\n 1 ;( \n $ convert -font somefont.ttf -size 50x50 -label A output.png\n convert: missing an image filename `output.png' @ convert.c/ConvertImageComm\\\n and/2775.\n 1 ;( \n\n\nUse subprocess.check_call instead of os.system.\nimport subprocess\n\nif __name__==\"__main__\":\n cmd = 'convert -font somefont.ttf -size 50x50'.split()\n #XXX command arguments are invalid \n subprocess.check_call(cmd + ['-label', unichr(9635), 'output.png'])\n\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"python",
"unicode"
] |
stackoverflow_0001815427_python_unicode.txt
|
Q:
What is the preferred technique to convert an object's properties to a sorted list of tuples?
I'm working with an open-source library and they define a class like so:
class Provider(object):
""" Defines for each of the supported providers """
DUMMY = 0
EC2 = 1
EC2_EU = 2
RACKSPACE = 3
SLICEHOST = 4
GOGRID = 5
VPSNET = 6
LINODE = 7
VCLOUD = 8
RIMUHOSTING = 9
I need to take the properties (DUMMY, EC2, etc.) and convert them to a sorted list of tuples that would look something like this:
[(0, 'DUMMY'), (1, 'EC2'), ...]
I want to sort on the name of the property itself. I've come up with a few ways to tackle this, including the following which seems like an inefficient way to handle this:
import operator
from libcloud.types import Provider
PROVIDER_CHOICES = [(v,k) for k, v in vars(Provider).items()
if not k.startswith('__')]
PROVIDER_CHOICES = sorted(PROVIDER_CHOICES, key=operator.itemgetter(1))
It works but seems inelegant and like there may be a better way. I also see flaws in the way I'm constructing the list by doing the if not k.startswith('__') - mainly what if the open-source lib adds methods to the Provider class?
Just looking for some opinions and other techniques that may work better for this.
A:
If you are looking for class variables that are of the type integer, you could do it like this:
import inspect
PROVIDER_CHOICES = inspect.getmembers(Foo, lambda x: isinstance(x, int))
Check out the inspect module for more information.
As an aside: you can use PROVIDER_CHOICES.sort(key=...) in your last line, which does an inplace sort.
Edit: getmembers returns a sorted list as stated in the documentation so sorted is unnecessary (thanks J.F. Sebastian)
A:
If you worry about methods and other types of attributes just filter them out too.
PROVIDER_CHOICES = [(v,k) for k, v in vars(Provider).iteritems()
if not k.startswith('_') and isinstance(v,int)]
PROVIDER_CHOICES.sort( key=itemgetter(1) )
You just have to run this once for every class in question, so speed shouldn't be a issue to begin with. If you really care, you can just store the list on the class itself.
|
What is the preferred technique to convert an object's properties to a sorted list of tuples?
|
I'm working with an open-source library and they define a class like so:
class Provider(object):
""" Defines for each of the supported providers """
DUMMY = 0
EC2 = 1
EC2_EU = 2
RACKSPACE = 3
SLICEHOST = 4
GOGRID = 5
VPSNET = 6
LINODE = 7
VCLOUD = 8
RIMUHOSTING = 9
I need to take the properties (DUMMY, EC2, etc.) and convert them to a sorted list of tuples that would look something like this:
[(0, 'DUMMY'), (1, 'EC2'), ...]
I want to sort on the name of the property itself. I've come up with a few ways to tackle this, including the following which seems like an inefficient way to handle this:
import operator
from libcloud.types import Provider
PROVIDER_CHOICES = [(v,k) for k, v in vars(Provider).items()
if not k.startswith('__')]
PROVIDER_CHOICES = sorted(PROVIDER_CHOICES, key=operator.itemgetter(1))
It works but seems inelegant and like there may be a better way. I also see flaws in the way I'm constructing the list by doing the if not k.startswith('__') - mainly what if the open-source lib adds methods to the Provider class?
Just looking for some opinions and other techniques that may work better for this.
|
[
"If you are looking for class variables that are of the type integer, you could do it like this:\nimport inspect\nPROVIDER_CHOICES = inspect.getmembers(Foo, lambda x: isinstance(x, int))\n\nCheck out the inspect module for more information.\n\nAs an aside: you can use PROVIDER_CHOICES.sort(key=...) in your last line, which does an inplace sort.\nEdit: getmembers returns a sorted list as stated in the documentation so sorted is unnecessary (thanks J.F. Sebastian)\n",
"If you worry about methods and other types of attributes just filter them out too.\nPROVIDER_CHOICES = [(v,k) for k, v in vars(Provider).iteritems()\n if not k.startswith('_') and isinstance(v,int)]\nPROVIDER_CHOICES.sort( key=itemgetter(1) )\n\nYou just have to run this once for every class in question, so speed shouldn't be a issue to begin with. If you really care, you can just store the list on the class itself.\n"
] |
[
6,
0
] |
[] |
[] |
[
"python",
"sorting"
] |
stackoverflow_0001815693_python_sorting.txt
|
Q:
What's an easy way to implement a --quiet option in a python script
Am working on a command line python script - throughout the script, I have a lot of information I am print-ing to the terminal window so that I may follow along with what is happening.
Using OptionParser I want to add a --quiet option so I can silence all the output. I am looking for a pythonic way to go about implementing this throughout the script so that I don't end up doing something like:
if not QUIET: # global variable set by OptionParser
print " my output "
Am new to python and sure there is a better way. Ideas?
A:
You could use logging and assign those things that should not be printed if QUIET a different log level.
Edit: THC4K's answer shows an example of how to do this, assuming that all output should be silent if QUIET is set. Note that in Python 3 from __future__ import print_function is not necessary:
print = logging.info
logging.basicConfig(level=logging.WARNING if QUIET else logging.INFO,
format="%(message)s")
For for important output that should not be silenced by --quiet, define e.g. iprint:
iprint = logging.warning
A:
can silence all the output by running it as python myscript.py > /dev/null
change the output streams in the script:
if QUIET:
sys.stdout = open(os.devnull, 'a')
sys.stderr = open(os.devnull, 'a')
print(something)
use a different print function
from __future__ import print_function
if QUIET:
def print(*args):
pass
print(something)
use logging and loglevels
from __future__ import print_function
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s")
print = logging.info
if QUIET:
logging.basicConfig(level=logging.ERROR)
print(something)
A:
Why don't you just modify your output function based on whether the program is in quiet mode, so you only do the check once?
if QUIET:
def DoOutput(stuff):
pass
else:
def DoOutput(stuff):
print(stuff)
Or, you could of course put the check for QUIET inside your output function:
def DoOutput(stuff):
if QUIET:
print(stuff)
The situation that you've described is actually one of the reasons that Python 3 has changed print from a keyword to an actual function: people's large projects were becoming very dependent on print being a keyword, and then when it came time to modify how output was recorded, it required a massive refactoring; whereas when print is a proper function, you can just redefine it, so that print(foo) would output to a log file, for instance. That's why it's better practice to wrap your output/logging in an actual function, rather than having print scattered about your script.
A:
You could replace stdout with a proxy that filters calls to write or writelines:
class FileProxy(object):
def __init__(self, real_file, quiet_flag):
self.real_file = real_file
self.quiet_flag = quiet_flag
def write(self, string):
if not self.quiet_flag:
self.real_file.write(string)
def writelines(self, strings):
if not self.quiet_flag:
self.real_file.write(strings)
def __getattr__(self, name):
return getattr(self.file, name)
import sys
sys.stdout = FileProxy(sys.stdout, QUIET)
The advantage of this is that it is cross platform (unlike writing to /dev/null) and it will still work for print statements in third-party libraries that you do not have control over.
You could also refine it further to give more control over exactly what is written, e.g. to add a timestamp, or redirect print statements to the logging system.
A:
If you want it quick and dirty and you want to get rid of all output then redirect stdout and stderr to /dev/null. Put:
sys.stdout = open("/dev/null", "a")
sys.stderr = open("/dev/null", "a")
At the point where you detect --quiet.
A:
if QUIET:
sys.stdout=open("/dev/null","w")
...
print 'my output'
On Windows, use "nul" instead of "/dev/null"
|
What's an easy way to implement a --quiet option in a python script
|
Am working on a command line python script - throughout the script, I have a lot of information I am print-ing to the terminal window so that I may follow along with what is happening.
Using OptionParser I want to add a --quiet option so I can silence all the output. I am looking for a pythonic way to go about implementing this throughout the script so that I don't end up doing something like:
if not QUIET: # global variable set by OptionParser
print " my output "
Am new to python and sure there is a better way. Ideas?
|
[
"You could use logging and assign those things that should not be printed if QUIET a different log level.\nEdit: THC4K's answer shows an example of how to do this, assuming that all output should be silent if QUIET is set. Note that in Python 3 from __future__ import print_function is not necessary:\nprint = logging.info\nlogging.basicConfig(level=logging.WARNING if QUIET else logging.INFO,\n format=\"%(message)s\")\n\nFor for important output that should not be silenced by --quiet, define e.g. iprint:\niprint = logging.warning\n\n",
"can silence all the output by running it as python myscript.py > /dev/null\nchange the output streams in the script:\nif QUIET:\n sys.stdout = open(os.devnull, 'a')\n sys.stderr = open(os.devnull, 'a')\nprint(something)\n\nuse a different print function\nfrom __future__ import print_function\nif QUIET:\n def print(*args):\n pass\nprint(something)\n\nuse logging and loglevels\nfrom __future__ import print_function\nimport logging\nlogging.basicConfig(level=logging.INFO, format=\"%(message)s\")\nprint = logging.info\nif QUIET:\n logging.basicConfig(level=logging.ERROR)\n\nprint(something)\n\n",
"Why don't you just modify your output function based on whether the program is in quiet mode, so you only do the check once?\nif QUIET:\n def DoOutput(stuff):\n pass\nelse:\n def DoOutput(stuff):\n print(stuff)\n\nOr, you could of course put the check for QUIET inside your output function:\ndef DoOutput(stuff):\n if QUIET:\n print(stuff)\n\nThe situation that you've described is actually one of the reasons that Python 3 has changed print from a keyword to an actual function: people's large projects were becoming very dependent on print being a keyword, and then when it came time to modify how output was recorded, it required a massive refactoring; whereas when print is a proper function, you can just redefine it, so that print(foo) would output to a log file, for instance. That's why it's better practice to wrap your output/logging in an actual function, rather than having print scattered about your script.\n",
"You could replace stdout with a proxy that filters calls to write or writelines:\nclass FileProxy(object):\n def __init__(self, real_file, quiet_flag):\n self.real_file = real_file\n self.quiet_flag = quiet_flag\n\n def write(self, string):\n if not self.quiet_flag:\n self.real_file.write(string)\n\n def writelines(self, strings):\n if not self.quiet_flag:\n self.real_file.write(strings)\n\n def __getattr__(self, name):\n return getattr(self.file, name)\n\nimport sys\nsys.stdout = FileProxy(sys.stdout, QUIET)\n\nThe advantage of this is that it is cross platform (unlike writing to /dev/null) and it will still work for print statements in third-party libraries that you do not have control over.\nYou could also refine it further to give more control over exactly what is written, e.g. to add a timestamp, or redirect print statements to the logging system.\n",
"If you want it quick and dirty and you want to get rid of all output then redirect stdout and stderr to /dev/null. Put:\nsys.stdout = open(\"/dev/null\", \"a\")\nsys.stderr = open(\"/dev/null\", \"a\")\n\nAt the point where you detect --quiet.\n",
"if QUIET:\n sys.stdout=open(\"/dev/null\",\"w\")\n...\nprint 'my output'\n\nOn Windows, use \"nul\" instead of \"/dev/null\"\n"
] |
[
30,
15,
2,
1,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001815760_python.txt
|
Q:
want to develop a app in python which interacts with the web and posts on facebook , twitter and gtalk?
i want to develop a python desktop app which interacts and posts its content on facebook , twitter or gtalk as a message . is it possible?... tutorials and ideas will help
A:
The Twitter API will help you for Twitter, since it's intended to help you post messages. The Facebook API isn't actually what you want - it helps you write applications which run on Facebook, but doesn't necessarily help you communicate with Facebook the way that a user would. To do that you might need to look at how Facebook communicates with a browser - using something like Firebug and Live HTTP Headers and then replicating the browser behaviour using urllib/urllib2 (there is an excellent tutorial here). For gtalk, the underlying implementation is Jabber/XMPP for which you should be able to find plenty of documentation (there's even a book published by O'Reilly).
A:
If you can't find a facebook API to suit your needs, you'll have to make one from scratch. Try using the Charles web debugging proxy to surf around facebook and post comments, add friends etc. It will reveal and log all the headers and GET/POST traffic. You can use the logged requests and responses to engineer your own API. It'll be a pain, but its a good exercise. If you get stuck, just post a query on this website. The issues are all common enough that people post solutions within a few minutes.
A few pointers:
Facebook requires a login, meaning you'll probably need to build your own urlopener using a cookie handler from cookielib. You'll also have to get comfortable programming HTTP POST requests.
Facebook probably won't tolerate traffic from automated scripts, so all your traffic with the website will have to emulate a browser--slowish request rates, and a strategically defined "user-agent" element in the HTTP request headers.
A:
You can check out APIs of Facebook, Twitter and Gtalk
|
want to develop a app in python which interacts with the web and posts on facebook , twitter and gtalk?
|
i want to develop a python desktop app which interacts and posts its content on facebook , twitter or gtalk as a message . is it possible?... tutorials and ideas will help
|
[
"The Twitter API will help you for Twitter, since it's intended to help you post messages. The Facebook API isn't actually what you want - it helps you write applications which run on Facebook, but doesn't necessarily help you communicate with Facebook the way that a user would. To do that you might need to look at how Facebook communicates with a browser - using something like Firebug and Live HTTP Headers and then replicating the browser behaviour using urllib/urllib2 (there is an excellent tutorial here). For gtalk, the underlying implementation is Jabber/XMPP for which you should be able to find plenty of documentation (there's even a book published by O'Reilly).\n",
"If you can't find a facebook API to suit your needs, you'll have to make one from scratch. Try using the Charles web debugging proxy to surf around facebook and post comments, add friends etc. It will reveal and log all the headers and GET/POST traffic. You can use the logged requests and responses to engineer your own API. It'll be a pain, but its a good exercise. If you get stuck, just post a query on this website. The issues are all common enough that people post solutions within a few minutes.\nA few pointers:\n\nFacebook requires a login, meaning you'll probably need to build your own urlopener using a cookie handler from cookielib. You'll also have to get comfortable programming HTTP POST requests.\nFacebook probably won't tolerate traffic from automated scripts, so all your traffic with the website will have to emulate a browser--slowish request rates, and a strategically defined \"user-agent\" element in the HTTP request headers.\n\n",
"You can check out APIs of Facebook, Twitter and Gtalk\n"
] |
[
5,
3,
2
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001816024_python.txt
|
Q:
Python: Extract HTML from an XML file
My XML file looks like this:
<strings>
<string>Bla <b>One & Two</b> Foo</string>
</strings>
I want to extract the content of each <string> while maintaining the inner tags. That is, I would like to see the following Python string: u"Bla <b>One & Two</b> Foo". Alternatively, I guess I could settle on u"Bla <b>One & Two</b> Foo", and then try to replace the entities myself.
I am currently using lxml, which allows me to iterate over the nested tags, missing out on the text not inside a tag, or alternatively over all text content (itertext), losing the tag information. I'm probably missing something.
If possible I'd prefer to keep lxml, though I can switch to another library if necessary.
A:
There may be a better way of conditionally handling objects returned by the xpath() function, but I'm not sufficiently conversant with lxml to know what it is, so I had to write a function to return the text value of a node. But that said, this shows a general approach to the problem:
>>> from lxml import etree
>>> from StringIO import StringIO
>>> def node_text(n):
try:
return etree.tostring(n, method='html', with_tail=False)
except TypeError:
return str(n)
>>> f = StringIO('<strings><string>This is <b>not</b> how I plan to escape.</string></strings>')
>>> x = etree.parse(f)
>>> ''.join(node_text(n) for n in x.xpath('/strings/string/node()'))
'This is <b>not</b> how I plan to escape.'
A:
try etree.tostring
outer = etree.tostring(string_elem, method='html')
inner = re.match("^[^>]+>(.*)<[^<]+$", outer).groups(1)[0]
A:
Regardless of the language, relatively simple XSLT template would do the trick.
Something like defining patterns to tags you want to keep, converting to text others.
You can of course use a recursive function with a compliant DOM implementation (minidom maybe?) and process tags by hand.
(pseudocode)
def Function(tag):
if tag.NodeType = "#text": return tag.innerText
text=""
if tag.ElementName in allowedTags:
text="<%s>"%tag.ElementName
text += [Function(subtag) for subtag in tag.childs]
if tag.ElementName in allowedTags:
text+="</%s>"%tag.ElementName
return text
|
Python: Extract HTML from an XML file
|
My XML file looks like this:
<strings>
<string>Bla <b>One & Two</b> Foo</string>
</strings>
I want to extract the content of each <string> while maintaining the inner tags. That is, I would like to see the following Python string: u"Bla <b>One & Two</b> Foo". Alternatively, I guess I could settle on u"Bla <b>One & Two</b> Foo", and then try to replace the entities myself.
I am currently using lxml, which allows me to iterate over the nested tags, missing out on the text not inside a tag, or alternatively over all text content (itertext), losing the tag information. I'm probably missing something.
If possible I'd prefer to keep lxml, though I can switch to another library if necessary.
|
[
"There may be a better way of conditionally handling objects returned by the xpath() function, but I'm not sufficiently conversant with lxml to know what it is, so I had to write a function to return the text value of a node. But that said, this shows a general approach to the problem:\n>>> from lxml import etree\n>>> from StringIO import StringIO\n>>> def node_text(n):\n try:\n return etree.tostring(n, method='html', with_tail=False)\n except TypeError:\n return str(n)\n\n>>> f = StringIO('<strings><string>This is <b>not</b> how I plan to escape.</string></strings>')\n>>> x = etree.parse(f)\n>>> ''.join(node_text(n) for n in x.xpath('/strings/string/node()'))\n'This is <b>not</b> how I plan to escape.'\n\n",
"try etree.tostring\nouter = etree.tostring(string_elem, method='html')\ninner = re.match(\"^[^>]+>(.*)<[^<]+$\", outer).groups(1)[0]\n\n",
"Regardless of the language, relatively simple XSLT template would do the trick.\nSomething like defining patterns to tags you want to keep, converting to text others.\nYou can of course use a recursive function with a compliant DOM implementation (minidom maybe?) and process tags by hand.\n(pseudocode)\ndef Function(tag):\n if tag.NodeType = \"#text\": return tag.innerText\n text=\"\"\n if tag.ElementName in allowedTags:\n text=\"<%s>\"%tag.ElementName\n text += [Function(subtag) for subtag in tag.childs]\n if tag.ElementName in allowedTags:\n text+=\"</%s>\"%tag.ElementName\n return text\n\n"
] |
[
3,
2,
0
] |
[
"Not using parser, but just pure string manipulation\nmystring=\"\"\"\n <strings>\n <string>Bla <b>One & Two</b> Foo</string>\n </strings>\n\"\"\"\nfor s in mystring.split(\"</string>\"):\n if \"<string>\" in s:\n i = s.index(\"<string>\")\n print s[i+len(\"<string>\"):].replace(\"&\",\"\")\n\n"
] |
[
-1
] |
[
"html",
"lxml",
"python",
"xml"
] |
stackoverflow_0001814923_html_lxml_python_xml.txt
|
Q:
Python py2exe - memory load error
I am creating a medium level application in Python.
Everything works well now, and I am trying to make this a windows executable with py2exe.
The executable is created fine, but when I try to run it, it fails with the following error.
File "zipextimporter.pyo", line 82, in load_module
File "ffhandler.pyo", line 33, in ?
File "zipextimporter.pyo", line 82, in load_module
File "pyAA\__init__.pyo", line 1, in ?
File "zipextimporter.pyo", line 82, in load_module
File "pyAA\AA.pyo", line 8, in ?
File "zipextimporter.pyo", line 82, in load_module
File "pyAA\pyAAc.pyo", line 5, in ?
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd
I am using pyAA in this application. I searched internet, but was unable to get any solution.
I copied msvcp71.dll to windows/system32, but still issue is there.
I had solved it earlier (around 7 months back), but my hard drive crashed and when I try to recreate it, I cannot seem to solve it now. :-(
I would be much obliged if someone could help me out here.
EDIT:
When I use py2exe without bundle files option, it is working perfectly. But when I use bundle file option, it is failing.
I tried without zipfile option, wherein it creates a library.zip alongwith the executable. Again it failed. I did unzip of library.zip using 7-zip, and found that _pyAAc.pyd is there in pyAA folder inside the zip file. So, it looks like some issue with memoryloadlibrary function.
When I tried to unzip using windows unzip function, it failed. I had to use 7-zip to unzip it. Is it a possible clue?
A:
You're missing some DLL's in your build...
First search your hard drive for the file _pyAAC.pyd. Make sure it is included (shipped) in your build.
Then use 'dependency walker' on the .pyd file (in your py2exe compiled version!) to see what it is that is still missing (other DLL's which are causing the MemoryLoadLibrary message for the .pyd file). Make sure these dependencies are also shipped, ...
|
Python py2exe - memory load error
|
I am creating a medium level application in Python.
Everything works well now, and I am trying to make this a windows executable with py2exe.
The executable is created fine, but when I try to run it, it fails with the following error.
File "zipextimporter.pyo", line 82, in load_module
File "ffhandler.pyo", line 33, in ?
File "zipextimporter.pyo", line 82, in load_module
File "pyAA\__init__.pyo", line 1, in ?
File "zipextimporter.pyo", line 82, in load_module
File "pyAA\AA.pyo", line 8, in ?
File "zipextimporter.pyo", line 82, in load_module
File "pyAA\pyAAc.pyo", line 5, in ?
File "zipextimporter.pyo", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd
I am using pyAA in this application. I searched internet, but was unable to get any solution.
I copied msvcp71.dll to windows/system32, but still issue is there.
I had solved it earlier (around 7 months back), but my hard drive crashed and when I try to recreate it, I cannot seem to solve it now. :-(
I would be much obliged if someone could help me out here.
EDIT:
When I use py2exe without bundle files option, it is working perfectly. But when I use bundle file option, it is failing.
I tried without zipfile option, wherein it creates a library.zip alongwith the executable. Again it failed. I did unzip of library.zip using 7-zip, and found that _pyAAc.pyd is there in pyAA folder inside the zip file. So, it looks like some issue with memoryloadlibrary function.
When I tried to unzip using windows unzip function, it failed. I had to use 7-zip to unzip it. Is it a possible clue?
|
[
"You're missing some DLL's in your build...\nFirst search your hard drive for the file _pyAAC.pyd. Make sure it is included (shipped) in your build.\nThen use 'dependency walker' on the .pyd file (in your py2exe compiled version!) to see what it is that is still missing (other DLL's which are causing the MemoryLoadLibrary message for the .pyd file). Make sure these dependencies are also shipped, ...\n"
] |
[
0
] |
[] |
[] |
[
"py2exe",
"python"
] |
stackoverflow_0001816439_py2exe_python.txt
|
Q:
Get process argument info in windows with python/pywin32?
In linux, I know with 'ps' you can get the arguments that a command was run with. I need the equivalent in windows
Right now in python I'm doing
Process[i] = subprocess.Popen(cmd + " --daemon --config " + str(i) + ".conf", shell=False)
But I'm doing this in a daemon that is meant to be up all (or most) of the time. Since I'm having to debug and modify this daemon regularly it's starting up 3 processes; but when I shut it down, the processes stay up. (like should happen, just in case)...
When I start it back up again, I need to re-map the PID to the config file used by the processes that already exist, but I don't know of any way of retrieving this information (and parsing it) in windows. Does such a thing exist?
A:
This one might give you some inspiration.
|
Get process argument info in windows with python/pywin32?
|
In linux, I know with 'ps' you can get the arguments that a command was run with. I need the equivalent in windows
Right now in python I'm doing
Process[i] = subprocess.Popen(cmd + " --daemon --config " + str(i) + ".conf", shell=False)
But I'm doing this in a daemon that is meant to be up all (or most) of the time. Since I'm having to debug and modify this daemon regularly it's starting up 3 processes; but when I shut it down, the processes stay up. (like should happen, just in case)...
When I start it back up again, I need to re-map the PID to the config file used by the processes that already exist, but I don't know of any way of retrieving this information (and parsing it) in windows. Does such a thing exist?
|
[
"This one might give you some inspiration.\n"
] |
[
1
] |
[] |
[] |
[
"api",
"process",
"python",
"pywin32",
"winapi"
] |
stackoverflow_0001815733_api_process_python_pywin32_winapi.txt
|
Q:
Dynamic URL's inside Google's AppEngine
Good Afternoon,
I'm currently trying to build something incredibly simple inside of the Google AppEngine. The goal is to build a simple photo sharing application that will connect back to my iPhone application. It's all a learning experience for both Python and Objective-C.
(I've been a PHP programmer for quite some time).
The goal, create URL's that look like the following:
/img/{{ model.key.id }}
The problem is that it seems no matter how I do the python script, I either end up with an error or simply get nothing to display on my template page that's wrapped in the FOR statement.
My App.yaml File:
application: randomwebappname
version: 1
runtime: python
api_version: 1
handlers:
- url: /media
static_dir: media
- url: /b/.*
script: beta.py
login: required
- url: /.*
script: main.py
My Model (inside beta.py):
class Photo(db.Model):
author = db.StringProperty()
title = db.StringProperty()
slugline = db.StringProperty()
content = db.StringProperty(multiline=True)
coordinates = db.StringProperty()
avatar = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
My Class For Viewing The Image Page:
class ViewPage(webapp.RequestHandler):
def get(self, id):
template_values = {
'image': image,
}
path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
self.response.out.write(template.render(path, template_values))
I tried all of the following in my class, but they all end in failure. I tried them with key, key.name, and key.id in the URL:
photos = db.Query(Photo).filter('key', slug).fetch(limit=1)
photos = Photo.get_by_key_name(id)
photos = Photo.get_by_key_name(key)
key = db.Key.from_path('Photo', id)
photos = db.GqlQuery("SELECT * FROM Photo WHERE __key__ = :key", key=key)
photos = db.get(photo_key)
photos = self.request.get("id")
My URL's:
application = webapp.WSGIApplication([
('/b/', HomePage),
('/b/upload', UploadPage),
('/b/add', MainPage),
('/b/img', Image),
('/b/img/([-\w]+)', ViewPage),
('/b/submit', Submission)
], debug=True)
The Template Query:
{% for photo in photos %}
<img alt="" title="" src="img?img_id={{ photo.key }}" alt="main image" />
{% endfor %}
This seems like it would be something incredibly simple and I know I'm missing something, but I'm just not sure where it's at. I would write this in PHP, but I like the concept of AppEngine and I've said above, it's a good Python learning experience.
As a side note, this application does work on the homepage of the site. I simply have a GQL query and it outputs the images fine, it just fails when I try to go to the /img/id pages.
Any advice guys (and gals)? Thanks in advance!
UPDATE #1:
As per Jonathan's request, the following is the Image class:
class Image (webapp.RequestHandler):
def get(self):
photo = db.get(self.request.get("img_id"))
if photo.avatar:
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(photo.avatar)
else:
self.response.out.write("No image")
Also, after posting this, I realized that this was part of the problem as I was trying to do /img as the actual image and /img/ to display the view page. I've since changed this and now have a working model. But it's based upon the Key and not key.id:
URL:
('/b/i', ViewPage)
New ViewPage Class:
class ViewPage(webapp.RequestHandler):
def get(self):
image = db.get(self.request.get("id"))
template_values = {
'image': image,
}
path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
self.response.out.write(template.render(path, template_values))
So... to get to the View page (which includes comments and such), you now have to go to the following URL:
/b/i?img_id={{ image.key }}
Atleast the page is working now, but I would much prefer to get the page to look like the following as stated above:
/b/img/{{ image.key.id }}
Update #2: ViewPage class updated as well as URL's:
class ViewPageV2(webapp.RequestHandler):
def get(self, id):
images = [ db.get(id) ]
template_values = {
'image': image,
}
path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
self.response.out.write(template.render(path, template_values))
New URL:
('/b/image/([-\w]+)', ViewPageV2),
The following are two screenshots with one being proof of id "1" existing and the error that is coming with it currently.
alt text http://img215.imageshack.us/img215/9123/screenshot20091130at937.png
alt text http://img215.imageshack.us/img215/2207/screenshot20091130at938.png
Again, Thanks All!
A:
A simple way to grab them all:
photos = Photo.gql('ORDER BY __key__')
For more, see Queries on Keys in the App Engine docs.
Are you storing your photos with predefined keys?
photo = Photo(key_name="xzy123")
photo.put()
Then you can retrieve it in your ViewPage:
photos = [ Photo(key_name="%s" % id) ]
See Getting an Entity Using a Key.
Finally, to retrieve a photo based on its appengine-assigned key and assuming this key is present in the URL (e.g., http://host/b/img/ahByY..., so change your template to generate URLs of this form), use
class ViewPage(webapp.RequestHandler):
def get(self, id):
photos = [ db.get(id) ]
...
|
Dynamic URL's inside Google's AppEngine
|
Good Afternoon,
I'm currently trying to build something incredibly simple inside of the Google AppEngine. The goal is to build a simple photo sharing application that will connect back to my iPhone application. It's all a learning experience for both Python and Objective-C.
(I've been a PHP programmer for quite some time).
The goal, create URL's that look like the following:
/img/{{ model.key.id }}
The problem is that it seems no matter how I do the python script, I either end up with an error or simply get nothing to display on my template page that's wrapped in the FOR statement.
My App.yaml File:
application: randomwebappname
version: 1
runtime: python
api_version: 1
handlers:
- url: /media
static_dir: media
- url: /b/.*
script: beta.py
login: required
- url: /.*
script: main.py
My Model (inside beta.py):
class Photo(db.Model):
author = db.StringProperty()
title = db.StringProperty()
slugline = db.StringProperty()
content = db.StringProperty(multiline=True)
coordinates = db.StringProperty()
avatar = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
My Class For Viewing The Image Page:
class ViewPage(webapp.RequestHandler):
def get(self, id):
template_values = {
'image': image,
}
path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
self.response.out.write(template.render(path, template_values))
I tried all of the following in my class, but they all end in failure. I tried them with key, key.name, and key.id in the URL:
photos = db.Query(Photo).filter('key', slug).fetch(limit=1)
photos = Photo.get_by_key_name(id)
photos = Photo.get_by_key_name(key)
key = db.Key.from_path('Photo', id)
photos = db.GqlQuery("SELECT * FROM Photo WHERE __key__ = :key", key=key)
photos = db.get(photo_key)
photos = self.request.get("id")
My URL's:
application = webapp.WSGIApplication([
('/b/', HomePage),
('/b/upload', UploadPage),
('/b/add', MainPage),
('/b/img', Image),
('/b/img/([-\w]+)', ViewPage),
('/b/submit', Submission)
], debug=True)
The Template Query:
{% for photo in photos %}
<img alt="" title="" src="img?img_id={{ photo.key }}" alt="main image" />
{% endfor %}
This seems like it would be something incredibly simple and I know I'm missing something, but I'm just not sure where it's at. I would write this in PHP, but I like the concept of AppEngine and I've said above, it's a good Python learning experience.
As a side note, this application does work on the homepage of the site. I simply have a GQL query and it outputs the images fine, it just fails when I try to go to the /img/id pages.
Any advice guys (and gals)? Thanks in advance!
UPDATE #1:
As per Jonathan's request, the following is the Image class:
class Image (webapp.RequestHandler):
def get(self):
photo = db.get(self.request.get("img_id"))
if photo.avatar:
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(photo.avatar)
else:
self.response.out.write("No image")
Also, after posting this, I realized that this was part of the problem as I was trying to do /img as the actual image and /img/ to display the view page. I've since changed this and now have a working model. But it's based upon the Key and not key.id:
URL:
('/b/i', ViewPage)
New ViewPage Class:
class ViewPage(webapp.RequestHandler):
def get(self):
image = db.get(self.request.get("id"))
template_values = {
'image': image,
}
path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
self.response.out.write(template.render(path, template_values))
So... to get to the View page (which includes comments and such), you now have to go to the following URL:
/b/i?img_id={{ image.key }}
Atleast the page is working now, but I would much prefer to get the page to look like the following as stated above:
/b/img/{{ image.key.id }}
Update #2: ViewPage class updated as well as URL's:
class ViewPageV2(webapp.RequestHandler):
def get(self, id):
images = [ db.get(id) ]
template_values = {
'image': image,
}
path = os.path.join(os.path.dirname(__file__), 'templates/view.html')
self.response.out.write(template.render(path, template_values))
New URL:
('/b/image/([-\w]+)', ViewPageV2),
The following are two screenshots with one being proof of id "1" existing and the error that is coming with it currently.
alt text http://img215.imageshack.us/img215/9123/screenshot20091130at937.png
alt text http://img215.imageshack.us/img215/2207/screenshot20091130at938.png
Again, Thanks All!
|
[
"A simple way to grab them all:\nphotos = Photo.gql('ORDER BY __key__')\n\nFor more, see Queries on Keys in the App Engine docs.\nAre you storing your photos with predefined keys?\nphoto = Photo(key_name=\"xzy123\")\nphoto.put()\n\nThen you can retrieve it in your ViewPage:\nphotos = [ Photo(key_name=\"%s\" % id) ]\n\nSee Getting an Entity Using a Key.\nFinally, to retrieve a photo based on its appengine-assigned key and assuming this key is present in the URL (e.g., http://host/b/img/ahByY..., so change your template to generate URLs of this form), use\nclass ViewPage(webapp.RequestHandler):\n def get(self, id):\n photos = [ db.get(id) ]\n ...\n\n"
] |
[
3
] |
[] |
[] |
[
"dynamic_url",
"google_app_engine",
"python"
] |
stackoverflow_0001816529_dynamic_url_google_app_engine_python.txt
|
Q:
How can I translate this XPath expression to BeautifulSoup?
In answer to a previous question, several people suggested that I use BeautifulSoup for my project. I've been struggling with their documentation and I just cannot parse it. Can somebody point me to the section where I should be able to translate this expression to a BeautifulSoup expression?
hxs.select('//td[@class="altRow"][2]/a/@href').re('/.a\w+')
The above expression is from Scrapy. I'm trying to apply the regex re('\.a\w+') to td class altRow to get the links from there.
I would also appreciate pointers to any other tutorials or documentation. I couldn't find any.
Thanks for your help.
Edit:
I am looking at this page:
>>> soup.head.title
<title>White & Case LLP - Lawyers</title>
>>> soup.find(href=re.compile("/cabel"))
>>> soup.find(href=re.compile("/diversity"))
<a href="/diversity/committee">Committee</a>
Yet, if you look at the page source "/cabel" is there:
<td class="altRow" valign="middle" width="34%">
<a href='/cabel'>Abel, Christian</a>
For some reason, search results are not visible to BeautifulSoup, but they are visible to XPath because hxs.select('//td[@class="altRow"][2]/a/@href').re('/.a\w+') catches "/cabel"
Edit:
cobbal: It is still not working. But when I search this:
>>>soup.findAll(href=re.compile(r'/.a\w+'))
[<link href="/FCWSite/Include/styles/main.css" rel="stylesheet" type="text/css" />, <link rel="shortcut icon" type="image/ico" href="/FCWSite/Include/main_favicon.ico" />, <a href="/careers/northamerica">North America</a>, <a href="/careers/middleeastafrica">Middle East Africa</a>, <a href="/careers/europe">Europe</a>, <a href="/careers/latinamerica">Latin America</a>, <a href="/careers/asia">Asia</a>, <a href="/diversity/manager">Diversity Director</a>]
>>>
it returns all the links with second character "a" but not the lawyer names. So for some reason those links (such as "/cabel") are not visible to BeautifulSoup. I don't understand why.
A:
one option is to use lxml (I'm not familiar with beautifulsoup, so I can't say how to do with it), it defaultly supports XPath
Edit:
try (untested) tested:
soup.findAll('td', 'altRow')[1].findAll('a', href=re.compile(r'/.a\w+'), recursive=False)
I used docs at http://www.crummy.com/software/BeautifulSoup/documentation.html
soup should be a BeautifulSoup object
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup(html_string)
A:
I know BeautifulSoup is the canonical HTML parsing module, but sometimes you just want to scrape out some substrings from some HTML, and pyparsing has some useful methods to do this. Using this code:
from pyparsing import makeHTMLTags, withAttribute, SkipTo
import urllib
# get the HTML from your URL
url = "http://www.whitecase.com/Attorneys/List.aspx?LastName=&FirstName="
page = urllib.urlopen(url)
html = page.read()
page.close()
# define opening and closing tag expressions for <td> and <a> tags
# (makeHTMLTags also comprehends tag variations, including attributes,
# upper/lower case, etc.)
tdStart,tdEnd = makeHTMLTags("td")
aStart,aEnd = makeHTMLTags("a")
# only interested in tdStarts if they have "class=altRow" attribute
tdStart.setParseAction(withAttribute(("class","altRow")))
# compose total matching pattern (add trailing tdStart to filter out
# extraneous <td> matches)
patt = tdStart + aStart("a") + SkipTo(aEnd)("text") + aEnd + tdEnd + tdStart
# scan input HTML source for matching refs, and print out the text and
# href values
for ref,s,e in patt.scanString(html):
print ref.text, ref.a.href
I extracted 914 references from your page, from Abel to Zupikova.
Abel, Christian /cabel
Acevedo, Linda Jeannine /jacevedo
Acuña, Jennifer /jacuna
Adeyemi, Ike /igbadegesin
Adler, Avraham /aadler
...
Zhu, Jie /jzhu
ZÃdek, AleÅ¡ /azidek
Ziółek, Agnieszka /aziolek
Zitter, Adam /azitter
Zupikova, Jana /jzupikova
A:
I just answered this on the Beautiful Soup mailing list as a response to Zeynel's email to the list. Basically, there is an error in the web page that totally kills Beautiful Soup 3.1 during parsing, but is merely mangled by Beautiful Soup 3.0.
The thread is located at the Google Groups archive.
A:
It seems that you are using BeautifulSoup 3.1
I suggest reverting to BeautifulSoup 3.0.7 (because of this problem)
I just tested with 3.0.7 and got the results you expect:
>>> soup.findAll(href=re.compile(r'/cabel'))
[<a href="/cabel">Abel, Christian</a>]
Testing with BeautifulSoup 3.1 gets the results you are seeing. There is probably a malformed tag in the html but I didn't see what it was in a quick look.
|
How can I translate this XPath expression to BeautifulSoup?
|
In answer to a previous question, several people suggested that I use BeautifulSoup for my project. I've been struggling with their documentation and I just cannot parse it. Can somebody point me to the section where I should be able to translate this expression to a BeautifulSoup expression?
hxs.select('//td[@class="altRow"][2]/a/@href').re('/.a\w+')
The above expression is from Scrapy. I'm trying to apply the regex re('\.a\w+') to td class altRow to get the links from there.
I would also appreciate pointers to any other tutorials or documentation. I couldn't find any.
Thanks for your help.
Edit:
I am looking at this page:
>>> soup.head.title
<title>White & Case LLP - Lawyers</title>
>>> soup.find(href=re.compile("/cabel"))
>>> soup.find(href=re.compile("/diversity"))
<a href="/diversity/committee">Committee</a>
Yet, if you look at the page source "/cabel" is there:
<td class="altRow" valign="middle" width="34%">
<a href='/cabel'>Abel, Christian</a>
For some reason, search results are not visible to BeautifulSoup, but they are visible to XPath because hxs.select('//td[@class="altRow"][2]/a/@href').re('/.a\w+') catches "/cabel"
Edit:
cobbal: It is still not working. But when I search this:
>>>soup.findAll(href=re.compile(r'/.a\w+'))
[<link href="/FCWSite/Include/styles/main.css" rel="stylesheet" type="text/css" />, <link rel="shortcut icon" type="image/ico" href="/FCWSite/Include/main_favicon.ico" />, <a href="/careers/northamerica">North America</a>, <a href="/careers/middleeastafrica">Middle East Africa</a>, <a href="/careers/europe">Europe</a>, <a href="/careers/latinamerica">Latin America</a>, <a href="/careers/asia">Asia</a>, <a href="/diversity/manager">Diversity Director</a>]
>>>
it returns all the links with second character "a" but not the lawyer names. So for some reason those links (such as "/cabel") are not visible to BeautifulSoup. I don't understand why.
|
[
"one option is to use lxml (I'm not familiar with beautifulsoup, so I can't say how to do with it), it defaultly supports XPath\nEdit:\ntry (untested) tested:\nsoup.findAll('td', 'altRow')[1].findAll('a', href=re.compile(r'/.a\\w+'), recursive=False)\n\nI used docs at http://www.crummy.com/software/BeautifulSoup/documentation.html\nsoup should be a BeautifulSoup object\nimport BeautifulSoup\nsoup = BeautifulSoup.BeautifulSoup(html_string)\n\n",
"I know BeautifulSoup is the canonical HTML parsing module, but sometimes you just want to scrape out some substrings from some HTML, and pyparsing has some useful methods to do this. Using this code:\nfrom pyparsing import makeHTMLTags, withAttribute, SkipTo\nimport urllib\n\n# get the HTML from your URL\nurl = \"http://www.whitecase.com/Attorneys/List.aspx?LastName=&FirstName=\"\npage = urllib.urlopen(url)\nhtml = page.read()\npage.close()\n\n# define opening and closing tag expressions for <td> and <a> tags\n# (makeHTMLTags also comprehends tag variations, including attributes, \n# upper/lower case, etc.)\ntdStart,tdEnd = makeHTMLTags(\"td\")\naStart,aEnd = makeHTMLTags(\"a\")\n\n# only interested in tdStarts if they have \"class=altRow\" attribute\ntdStart.setParseAction(withAttribute((\"class\",\"altRow\")))\n\n# compose total matching pattern (add trailing tdStart to filter out \n# extraneous <td> matches)\npatt = tdStart + aStart(\"a\") + SkipTo(aEnd)(\"text\") + aEnd + tdEnd + tdStart\n\n# scan input HTML source for matching refs, and print out the text and \n# href values\nfor ref,s,e in patt.scanString(html):\n print ref.text, ref.a.href\n\nI extracted 914 references from your page, from Abel to Zupikova.\nAbel, Christian /cabel\nAcevedo, Linda Jeannine /jacevedo\nAcuña, Jennifer /jacuna\nAdeyemi, Ike /igbadegesin\nAdler, Avraham /aadler\n...\nZhu, Jie /jzhu\nZÃdek, AleÅ¡ /azidek\nZiółek, Agnieszka /aziolek\nZitter, Adam /azitter\nZupikova, Jana /jzupikova\n\n",
"I just answered this on the Beautiful Soup mailing list as a response to Zeynel's email to the list. Basically, there is an error in the web page that totally kills Beautiful Soup 3.1 during parsing, but is merely mangled by Beautiful Soup 3.0.\nThe thread is located at the Google Groups archive.\n",
"It seems that you are using BeautifulSoup 3.1\nI suggest reverting to BeautifulSoup 3.0.7 (because of this problem)\nI just tested with 3.0.7 and got the results you expect:\n>>> soup.findAll(href=re.compile(r'/cabel'))\n[<a href=\"/cabel\">Abel, Christian</a>]\n\nTesting with BeautifulSoup 3.1 gets the results you are seeing. There is probably a malformed tag in the html but I didn't see what it was in a quick look.\n"
] |
[
6,
4,
2,
1
] |
[] |
[] |
[
"beautifulsoup",
"python",
"xpath"
] |
stackoverflow_0001814750_beautifulsoup_python_xpath.txt
|
Q:
How to create a generator/iterator with the Python C API?
How do I replicate the following Python code with the Python C API?
class Sequence():
def __init__(self, max):
self.max = max
def data(self):
i = 0
while i < self.max:
yield i
i += 1
So far, I have this:
#include <Python/Python.h>
#include <Python/structmember.h>
/* Define a new object class, Sequence. */
typedef struct {
PyObject_HEAD
size_t max;
} SequenceObject;
/* Instance variables */
static PyMemberDef Sequence_members[] = {
{"max", T_UINT, offsetof(SequenceObject, max), 0, NULL},
{NULL} /* Sentinel */
};
static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds)
{
if (!PyArg_ParseTuple(args, "k", &(self->max))) {
return -1;
}
return 0;
}
static PyObject *Sequence_data(SequenceObject *self, PyObject *args);
/* Methods */
static PyMethodDef Sequence_methods[] = {
{"data", (PyCFunction)Sequence_data, METH_NOARGS,
"sequence.data() -> iterator object\n"
"Returns iterator of range [0, sequence.max)."},
{NULL} /* Sentinel */
};
/* Define new object type */
PyTypeObject Sequence_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"Sequence", /* tp_name */
sizeof(SequenceObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
"Test generator object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
Sequence_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Sequence_init, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject *Sequence_data(SequenceObject *self, PyObject *args)
{
/* Now what? */
}
But I'm not sure where to go next. Could anyone offer some suggestions?
Edit
I suppose the main problem I'm having with this is simulating the yield statement. As I understand it, it is a pretty simple-looking, but in reality complex, statement — it creates a generator with its own __iter__() and next() methods which are called automatically. Searching through the docs, it seems to be associated with the PyGenObject; however, how to create a new instance of this object is unclear. PyGen_New() takes as its argument a PyFrameObject, the only reference to which I can find is PyEval_GetFrame(), which doesn't seem to be what I want (or am I mistaken?). Does anyone have any experience with this they can share?
Further Edit
I found this to be clearer when I (essentially) expanded what Python was doing behind the scenes:
class IterObject():
def __init__(self, max):
self.max = max
def __iter__(self):
self.i = 0
return self
def next(self):
if self.i >= self.max:
raise StopIteration
self.i += 1
return self.i
class Sequence():
def __init__(self, max):
self.max = max
def data(self):
return IterObject(self.max)
Technically the sequence is off by one but you get the idea.
The only problem with this is it's very annoying to create a new object every time one needs a generator — even more so in Python than C because of the required monstrosity that comes with defining a new type. And there can be no yield statement in C because C has no closures. What I did instead (since I couldn't find it in the Python API — please point me to a standard object if it already exists!) was create a simple, generic generator object class that called back a C function for every next() method call. Here it is (note that I have not yet tried compiling this because it is not complete — see below):
#include <Python/Python.h>
#include <Python/structmember.h>
#include <stdlib.h>
/* A convenient, generic generator object. */
typedef PyObject *(*callback)(PyObject *callee, void *info) PyGeneratorCallback;
typedef struct {
PyObject HEAD
PyGeneratorCallback callback;
PyObject *callee;
void *callbackInfo; /* info to be passed along to callback function. */
bool freeInfo; /* true if |callbackInfo| should be free'()d when object
* dealloc's, false if not. */
} GeneratorObject;
static PyObject *Generator_iter(PyObject *self, PyObject *args)
{
Py_INCREF(self);
return self;
}
static PyObject *Generator_next(PyObject *self, PyObject *args)
{
return self->callback(self->callee, self->callbackInfo);
}
static PyMethodDef Generator_methods[] = {
{"__iter__", (PyCFunction)Generator_iter, METH_NOARGS, NULL},
{"next", (PyCFunction)Generator_next, METH_NOARGS, NULL},
{NULL} /* Sentinel */
};
static void Generator_dealloc(GenericEventObject *self)
{
if (self->freeInfo && self->callbackInfo != NULL) {
free(self->callbackInfo);
}
self->ob_type->tp_free((PyObject *)self);
}
PyTypeObject Generator_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"Generator", /* tp_name */
sizeof(GeneratorObject), /* tp_basicsize */
0, /* tp_itemsize */
Generator_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
/* Returns a new generator object with the given callback function
* and arguments. */
PyObject *Generator_New(PyObject *callee, void *info,
bool freeInfo, PyGeneratorCallback callback)
{
GeneratorObject *generator = (GeneratorObject *)_PyObject_New(&Generator_Type);
if (generator == NULL) return NULL;
generator->callee = callee;
generator->info = info;
generator->callback = callback;
self->freeInfo = freeInfo;
return (PyObject *)generator;
}
/* End of Generator definition. */
/* Define a new object class, Sequence. */
typedef struct {
PyObject_HEAD
size_t max;
} SequenceObject;
/* Instance variables */
static PyMemberDef Sequence_members[] = {
{"max", T_UINT, offsetof(SequenceObject, max), 0, NULL},
{NULL} /* Sentinel */
}
static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds)
{
if (!PyArg_ParseTuple(args, "k", &self->max)) {
return -1;
}
return 0;
}
static PyObject *Sequence_data(SequenceObject *self, PyObject *args);
/* Methods */
static PyMethodDef Sequence_methods[] = {
{"data", (PyCFunction)Sequence_data, METH_NOARGS,
"sequence.data() -> iterator object\n"
"Returns generator of range [0, sequence.max)."},
{NULL} /* Sentinel */
};
/* Define new object type */
PyTypeObject Sequence_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"Sequence", /* tp_name */
sizeof(SequenceObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
"Test generator object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
Sequence_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Sequence_init, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject *Sequence_data(SequenceObject *self, PyObject *args)
{
size_t *info = malloc(sizeof(size_t));
if (info == NULL) return NULL;
*info = 0;
/* |info| will be free'()d by the returned generator object. */
GeneratorObject *ret = Generator_New(self, info, true,
&Sequence_data_next_callback);
if (ret == NULL) {
free(info); /* Watch out for memory leaks! */
}
return ret;
}
PyObject *Sequence_data_next_callback(PyObject *self, void *info)
{
size_t i = info;
if (i > self->max) {
return NULL; /* TODO: How do I raise StopIteration here? I can't seem to find
* a standard exception. */
} else {
return Py_BuildValue("k", i++);
}
}
However, unfortunately, I'm still not finished. The only question I have left is: How do I raise a StopIteration exception with the C API? I can't seem to find it listed in the Standard Exceptions. Also, perhaps more importantly, is this the correct way to approach this problem?
Thanks to anyone that's still following this.
A:
Below is a simple implementation of module spam with one function myiter(int) returning iterator:
import spam
for i in spam.myiter(10):
print i
prints numbers from 0 to 9.
It is simpler then your case but shows main points: defining object with standard __iter__() and next() methods, and implementing iterator behaviour including raising StopIteration when appropriate.
In your case iterator object needs to hold reference to Sequence (so you'll need deallocator method for it to Py_DECREF it).
The sequence itself needs to implement __iter()__ and create an iterator inside it.
Structure containing state of iterator.
(In your version instead of m, it would have reference to Sequence.)
typedef struct {
PyObject_HEAD
long int m;
long int i;
} spam_MyIter;
Iterator's __iter__() method.
It always simply returns self.
It allows for both iterator and collection to be treated the same
in constructs like for ... in ....
PyObject* spam_MyIter_iter(PyObject *self)
{
Py_INCREF(self);
return self;
}
Implementation of our iteration: next() method.
PyObject* spam_MyIter_iternext(PyObject *self)
{
spam_MyIter *p = (spam_MyIter *)self;
if (p->i < p->m) {
PyObject *tmp = Py_BuildValue("l", p->i);
(p->i)++;
return tmp;
} else {
/* Raising of standard StopIteration exception with empty value. */
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
}
We need extended version of PyTypeObject structure to provide Python with
information about __iter__() and next().
We want them to be called efficiently, so no name-based lookup in dictionary.
static PyTypeObject spam_MyIterType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"spam._MyIter", /*tp_name*/
sizeof(spam_MyIter), /*tp_basicsize*/
0, /*tp_itemsize*/
0, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,
/* tp_flags: Py_TPFLAGS_HAVE_ITER tells python to
use tp_iter and tp_iternext fields. */
"Internal myiter iterator object.", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
spam_MyIter_iter, /* tp_iter: __iter__() method */
spam_MyIter_iternext /* tp_iternext: next() method */
};
myiter(int) function creates iterator.
static PyObject *
spam_myiter(PyObject *self, PyObject *args)
{
long int m;
spam_MyIter *p;
if (!PyArg_ParseTuple(args, "l", &m)) return NULL;
/* I don't need python callable __init__() method for this iterator,
so I'll simply allocate it as PyObject and initialize it by hand. */
p = PyObject_New(spam_MyIter, &spam_MyIterType);
if (!p) return NULL;
/* I'm not sure if it's strictly necessary. */
if (!PyObject_Init((PyObject *)p, &spam_MyIterType)) {
Py_DECREF(p);
return NULL;
}
p->m = m;
p->i = 0;
return (PyObject *)p;
}
The rest is pretty boring...
static PyMethodDef SpamMethods[] = {
{"myiter", spam_myiter, METH_VARARGS, "Iterate from i=0 while i<m."},
{NULL, NULL, 0, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initspam(void)
{
PyObject* m;
spam_MyIterType.tp_new = PyType_GenericNew;
if (PyType_Ready(&spam_MyIterType) < 0) return;
m = Py_InitModule("spam", SpamMethods);
Py_INCREF(&spam_MyIterType);
PyModule_AddObject(m, "_MyIter", (PyObject *)&spam_MyIterType);
}
A:
In Sequence_data, you must either return a new PyInt instance or throw a StopIteration exception which tells the code outside that there are no more values. See PEP 255 for details and 9.10 Generators.
See Iterator Protocol for helper functions in the Python/C API.
|
How to create a generator/iterator with the Python C API?
|
How do I replicate the following Python code with the Python C API?
class Sequence():
def __init__(self, max):
self.max = max
def data(self):
i = 0
while i < self.max:
yield i
i += 1
So far, I have this:
#include <Python/Python.h>
#include <Python/structmember.h>
/* Define a new object class, Sequence. */
typedef struct {
PyObject_HEAD
size_t max;
} SequenceObject;
/* Instance variables */
static PyMemberDef Sequence_members[] = {
{"max", T_UINT, offsetof(SequenceObject, max), 0, NULL},
{NULL} /* Sentinel */
};
static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds)
{
if (!PyArg_ParseTuple(args, "k", &(self->max))) {
return -1;
}
return 0;
}
static PyObject *Sequence_data(SequenceObject *self, PyObject *args);
/* Methods */
static PyMethodDef Sequence_methods[] = {
{"data", (PyCFunction)Sequence_data, METH_NOARGS,
"sequence.data() -> iterator object\n"
"Returns iterator of range [0, sequence.max)."},
{NULL} /* Sentinel */
};
/* Define new object type */
PyTypeObject Sequence_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"Sequence", /* tp_name */
sizeof(SequenceObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
"Test generator object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
Sequence_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Sequence_init, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject *Sequence_data(SequenceObject *self, PyObject *args)
{
/* Now what? */
}
But I'm not sure where to go next. Could anyone offer some suggestions?
Edit
I suppose the main problem I'm having with this is simulating the yield statement. As I understand it, it is a pretty simple-looking, but in reality complex, statement — it creates a generator with its own __iter__() and next() methods which are called automatically. Searching through the docs, it seems to be associated with the PyGenObject; however, how to create a new instance of this object is unclear. PyGen_New() takes as its argument a PyFrameObject, the only reference to which I can find is PyEval_GetFrame(), which doesn't seem to be what I want (or am I mistaken?). Does anyone have any experience with this they can share?
Further Edit
I found this to be clearer when I (essentially) expanded what Python was doing behind the scenes:
class IterObject():
def __init__(self, max):
self.max = max
def __iter__(self):
self.i = 0
return self
def next(self):
if self.i >= self.max:
raise StopIteration
self.i += 1
return self.i
class Sequence():
def __init__(self, max):
self.max = max
def data(self):
return IterObject(self.max)
Technically the sequence is off by one but you get the idea.
The only problem with this is it's very annoying to create a new object every time one needs a generator — even more so in Python than C because of the required monstrosity that comes with defining a new type. And there can be no yield statement in C because C has no closures. What I did instead (since I couldn't find it in the Python API — please point me to a standard object if it already exists!) was create a simple, generic generator object class that called back a C function for every next() method call. Here it is (note that I have not yet tried compiling this because it is not complete — see below):
#include <Python/Python.h>
#include <Python/structmember.h>
#include <stdlib.h>
/* A convenient, generic generator object. */
typedef PyObject *(*callback)(PyObject *callee, void *info) PyGeneratorCallback;
typedef struct {
PyObject HEAD
PyGeneratorCallback callback;
PyObject *callee;
void *callbackInfo; /* info to be passed along to callback function. */
bool freeInfo; /* true if |callbackInfo| should be free'()d when object
* dealloc's, false if not. */
} GeneratorObject;
static PyObject *Generator_iter(PyObject *self, PyObject *args)
{
Py_INCREF(self);
return self;
}
static PyObject *Generator_next(PyObject *self, PyObject *args)
{
return self->callback(self->callee, self->callbackInfo);
}
static PyMethodDef Generator_methods[] = {
{"__iter__", (PyCFunction)Generator_iter, METH_NOARGS, NULL},
{"next", (PyCFunction)Generator_next, METH_NOARGS, NULL},
{NULL} /* Sentinel */
};
static void Generator_dealloc(GenericEventObject *self)
{
if (self->freeInfo && self->callbackInfo != NULL) {
free(self->callbackInfo);
}
self->ob_type->tp_free((PyObject *)self);
}
PyTypeObject Generator_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"Generator", /* tp_name */
sizeof(GeneratorObject), /* tp_basicsize */
0, /* tp_itemsize */
Generator_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
/* Returns a new generator object with the given callback function
* and arguments. */
PyObject *Generator_New(PyObject *callee, void *info,
bool freeInfo, PyGeneratorCallback callback)
{
GeneratorObject *generator = (GeneratorObject *)_PyObject_New(&Generator_Type);
if (generator == NULL) return NULL;
generator->callee = callee;
generator->info = info;
generator->callback = callback;
self->freeInfo = freeInfo;
return (PyObject *)generator;
}
/* End of Generator definition. */
/* Define a new object class, Sequence. */
typedef struct {
PyObject_HEAD
size_t max;
} SequenceObject;
/* Instance variables */
static PyMemberDef Sequence_members[] = {
{"max", T_UINT, offsetof(SequenceObject, max), 0, NULL},
{NULL} /* Sentinel */
}
static int Sequence_Init(SequenceObject *self, PyObject *args, PyObject *kwds)
{
if (!PyArg_ParseTuple(args, "k", &self->max)) {
return -1;
}
return 0;
}
static PyObject *Sequence_data(SequenceObject *self, PyObject *args);
/* Methods */
static PyMethodDef Sequence_methods[] = {
{"data", (PyCFunction)Sequence_data, METH_NOARGS,
"sequence.data() -> iterator object\n"
"Returns generator of range [0, sequence.max)."},
{NULL} /* Sentinel */
};
/* Define new object type */
PyTypeObject Sequence_Type = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
"Sequence", /* tp_name */
sizeof(SequenceObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
"Test generator object", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
Sequence_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)Sequence_init, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
static PyObject *Sequence_data(SequenceObject *self, PyObject *args)
{
size_t *info = malloc(sizeof(size_t));
if (info == NULL) return NULL;
*info = 0;
/* |info| will be free'()d by the returned generator object. */
GeneratorObject *ret = Generator_New(self, info, true,
&Sequence_data_next_callback);
if (ret == NULL) {
free(info); /* Watch out for memory leaks! */
}
return ret;
}
PyObject *Sequence_data_next_callback(PyObject *self, void *info)
{
size_t i = info;
if (i > self->max) {
return NULL; /* TODO: How do I raise StopIteration here? I can't seem to find
* a standard exception. */
} else {
return Py_BuildValue("k", i++);
}
}
However, unfortunately, I'm still not finished. The only question I have left is: How do I raise a StopIteration exception with the C API? I can't seem to find it listed in the Standard Exceptions. Also, perhaps more importantly, is this the correct way to approach this problem?
Thanks to anyone that's still following this.
|
[
"Below is a simple implementation of module spam with one function myiter(int) returning iterator:\nimport spam\nfor i in spam.myiter(10):\n print i\n\nprints numbers from 0 to 9.\nIt is simpler then your case but shows main points: defining object with standard __iter__() and next() methods, and implementing iterator behaviour including raising StopIteration when appropriate.\nIn your case iterator object needs to hold reference to Sequence (so you'll need deallocator method for it to Py_DECREF it).\nThe sequence itself needs to implement __iter()__ and create an iterator inside it.\n\nStructure containing state of iterator.\n(In your version instead of m, it would have reference to Sequence.)\ntypedef struct {\n PyObject_HEAD\n long int m;\n long int i;\n} spam_MyIter;\n\nIterator's __iter__() method.\nIt always simply returns self.\nIt allows for both iterator and collection to be treated the same\nin constructs like for ... in ....\nPyObject* spam_MyIter_iter(PyObject *self)\n{\n Py_INCREF(self);\n return self;\n}\n\nImplementation of our iteration: next() method.\nPyObject* spam_MyIter_iternext(PyObject *self)\n{\n spam_MyIter *p = (spam_MyIter *)self;\n if (p->i < p->m) {\n PyObject *tmp = Py_BuildValue(\"l\", p->i);\n (p->i)++;\n return tmp;\n } else {\n /* Raising of standard StopIteration exception with empty value. */\n PyErr_SetNone(PyExc_StopIteration);\n return NULL;\n }\n}\n\nWe need extended version of PyTypeObject structure to provide Python with\ninformation about __iter__() and next().\nWe want them to be called efficiently, so no name-based lookup in dictionary.\nstatic PyTypeObject spam_MyIterType = {\n PyObject_HEAD_INIT(NULL)\n 0, /*ob_size*/\n \"spam._MyIter\", /*tp_name*/\n sizeof(spam_MyIter), /*tp_basicsize*/\n 0, /*tp_itemsize*/\n 0, /*tp_dealloc*/\n 0, /*tp_print*/\n 0, /*tp_getattr*/\n 0, /*tp_setattr*/\n 0, /*tp_compare*/\n 0, /*tp_repr*/\n 0, /*tp_as_number*/\n 0, /*tp_as_sequence*/\n 0, /*tp_as_mapping*/\n 0, /*tp_hash */\n 0, /*tp_call*/\n 0, /*tp_str*/\n 0, /*tp_getattro*/\n 0, /*tp_setattro*/\n 0, /*tp_as_buffer*/\n Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,\n /* tp_flags: Py_TPFLAGS_HAVE_ITER tells python to\n use tp_iter and tp_iternext fields. */\n \"Internal myiter iterator object.\", /* tp_doc */\n 0, /* tp_traverse */\n 0, /* tp_clear */\n 0, /* tp_richcompare */\n 0, /* tp_weaklistoffset */\n spam_MyIter_iter, /* tp_iter: __iter__() method */\n spam_MyIter_iternext /* tp_iternext: next() method */\n};\n\nmyiter(int) function creates iterator.\nstatic PyObject *\nspam_myiter(PyObject *self, PyObject *args)\n{\n long int m;\n spam_MyIter *p;\n\n if (!PyArg_ParseTuple(args, \"l\", &m)) return NULL;\n\n /* I don't need python callable __init__() method for this iterator,\n so I'll simply allocate it as PyObject and initialize it by hand. */\n\n p = PyObject_New(spam_MyIter, &spam_MyIterType);\n if (!p) return NULL;\n\n /* I'm not sure if it's strictly necessary. */\n if (!PyObject_Init((PyObject *)p, &spam_MyIterType)) {\n Py_DECREF(p);\n return NULL;\n }\n\n p->m = m;\n p->i = 0;\n return (PyObject *)p;\n}\n\nThe rest is pretty boring...\nstatic PyMethodDef SpamMethods[] = {\n {\"myiter\", spam_myiter, METH_VARARGS, \"Iterate from i=0 while i<m.\"},\n {NULL, NULL, 0, NULL} /* Sentinel */\n};\n\nPyMODINIT_FUNC\ninitspam(void)\n{\n PyObject* m;\n\n spam_MyIterType.tp_new = PyType_GenericNew;\n if (PyType_Ready(&spam_MyIterType) < 0) return;\n\n m = Py_InitModule(\"spam\", SpamMethods);\n\n Py_INCREF(&spam_MyIterType);\n PyModule_AddObject(m, \"_MyIter\", (PyObject *)&spam_MyIterType);\n}\n\n",
"In Sequence_data, you must either return a new PyInt instance or throw a StopIteration exception which tells the code outside that there are no more values. See PEP 255 for details and 9.10 Generators.\nSee Iterator Protocol for helper functions in the Python/C API.\n"
] |
[
65,
5
] |
[] |
[] |
[
"c",
"generator",
"iterator",
"python",
"python_c_api"
] |
stackoverflow_0001815812_c_generator_iterator_python_python_c_api.txt
|
Q:
Adding custom JS to a django admin field
In a django application I have the following model:
class Appointment(models.Model):
#some other fields
#address fields
zipcode=models.CharField(max_length=5)
address=models.CharField(max_length=120)
latitude=models.FloatField()
longitude=models.FloatField()
When I'm rendering an Appointment, I'm just putting a marker at the position specified by longitude and latitude with the address as text, however I need the latitude and longitude to do that.
Currently, latitude and longitude have to be entered manually in the admin backend, but opening Google Maps/OSM, searching for the address and entering latitude and longitude is work that shouldn't have to be done by hand, so I want to retrieve it through the Google Maps API (keyword Geocoding).
Ideally, I want a button "Get coordinates" next to the address, which, when pressed, starts a Geocoding request and fills in latitude and longitude when the address is unambiguous and presents a map with the results and fills in the coordinates when the user clicks on the right marker.
I know how to do that, but I'm not sure how I should insert the markup and the code into the admin backend.
Some things I already considered but don't want to do as they don't seem natural or seem to be too much work for such a simple task:
putting the code in the address field's description in field_options in a class derived from admin.ModelAdmin
putting everything address related in a separate model and using a custom form (with a separate template
create an address picker widget
use GeoDjango
A:
What is primarily being dealt with is client-side markup and client-side javascript. Being the case, it would seem that using a facility that's designed to handle those would be the proper choice. I'd also recommend making a custom admin widget. I've used this pattern myself. Depending on the size of the client-side markup, you can even make use of a Django template to render the widget.
As an alternative, you could write non-intrusive javascript to re-render that area of the page after the page has loaded. In this method, you could simply include that javascript media file with class Media: on the admin model.
This is more like pseudo-code than anything but it gives the idea:
admin.py
class AppointmentAdmin(admin.ModelAdmin):
# ...
class Media:
from django.conf import settings
media_url = getattr(settings, 'MEDIA_URL', '/media')
js = [ media_url+'/admin/long-lat-render.js', ]
long-lat-render.js
// Written for jQuery
$(function(){
// on page load...
$('#_LongitudeTag').html('');
var getCoordButton = $('<button id="get-coords"></button>');
$('#_LongitudeTag').append(getCoordButton);
addGMap($('#_LongitudeTag').get(0));
});
function addGMap(element) {
// do whatevers
}
A:
There are several ways of doing this. You already mentioned some yourself.
An option would be to override the template for the save page in your admin and add the needed code to the template. The needed media, Javascript, Css, etc, could be added using an inner Media class in your ModelAdmin class. This media class has two different attributes, a tuple with css stylesheets and a tuple with javascript files
I think for myself, that the best option in this case would be a custom address picker widget as you already mention in the your list of ways you don't want to do it.
|
Adding custom JS to a django admin field
|
In a django application I have the following model:
class Appointment(models.Model):
#some other fields
#address fields
zipcode=models.CharField(max_length=5)
address=models.CharField(max_length=120)
latitude=models.FloatField()
longitude=models.FloatField()
When I'm rendering an Appointment, I'm just putting a marker at the position specified by longitude and latitude with the address as text, however I need the latitude and longitude to do that.
Currently, latitude and longitude have to be entered manually in the admin backend, but opening Google Maps/OSM, searching for the address and entering latitude and longitude is work that shouldn't have to be done by hand, so I want to retrieve it through the Google Maps API (keyword Geocoding).
Ideally, I want a button "Get coordinates" next to the address, which, when pressed, starts a Geocoding request and fills in latitude and longitude when the address is unambiguous and presents a map with the results and fills in the coordinates when the user clicks on the right marker.
I know how to do that, but I'm not sure how I should insert the markup and the code into the admin backend.
Some things I already considered but don't want to do as they don't seem natural or seem to be too much work for such a simple task:
putting the code in the address field's description in field_options in a class derived from admin.ModelAdmin
putting everything address related in a separate model and using a custom form (with a separate template
create an address picker widget
use GeoDjango
|
[
"What is primarily being dealt with is client-side markup and client-side javascript. Being the case, it would seem that using a facility that's designed to handle those would be the proper choice. I'd also recommend making a custom admin widget. I've used this pattern myself. Depending on the size of the client-side markup, you can even make use of a Django template to render the widget.\nAs an alternative, you could write non-intrusive javascript to re-render that area of the page after the page has loaded. In this method, you could simply include that javascript media file with class Media: on the admin model.\nThis is more like pseudo-code than anything but it gives the idea:\nadmin.py\nclass AppointmentAdmin(admin.ModelAdmin):\n # ...\n\n class Media:\n from django.conf import settings\n media_url = getattr(settings, 'MEDIA_URL', '/media')\n js = [ media_url+'/admin/long-lat-render.js', ]\n\nlong-lat-render.js\n// Written for jQuery\n$(function(){\n // on page load...\n\n $('#_LongitudeTag').html('');\n\n var getCoordButton = $('<button id=\"get-coords\"></button>');\n $('#_LongitudeTag').append(getCoordButton);\n\n addGMap($('#_LongitudeTag').get(0));\n});\n\nfunction addGMap(element) {\n // do whatevers\n}\n\n",
"There are several ways of doing this. You already mentioned some yourself.\nAn option would be to override the template for the save page in your admin and add the needed code to the template. The needed media, Javascript, Css, etc, could be added using an inner Media class in your ModelAdmin class. This media class has two different attributes, a tuple with css stylesheets and a tuple with javascript files\nI think for myself, that the best option in this case would be a custom address picker widget as you already mention in the your list of ways you don't want to do it.\n"
] |
[
20,
4
] |
[] |
[] |
[
"django",
"django_admin",
"google_maps",
"python",
"user_interface"
] |
stackoverflow_0001816444_django_django_admin_google_maps_python_user_interface.txt
|
Q:
Getting Unique Foreign Keys in Django?
Suppose my model looks like this:
class Farm(models.Model):
name = ...
class Tree(models.Model):
farm = models.ForeignKey(Farm)
...and I get a QuerySet of Tree objects. How do I determine what farms are represented in that QuerySet?
A:
http://docs.djangoproject.com/en/dev/ref/models/querysets/#in
Farm.objects.filter(tree__in=TreeQuerySet)
A:
There might be a better way to do it with the Django ORM and keep it lazy but you can get what you want with regular python (off the top of my head):
>>> set([ t.farm for t in qs ])
A:
Here is a way to have the database do the work for you:
farms = qs.values_list('farm', flat=True).distinct()
#values_list() is new in Django 1.0
return value should evaluate to something like:
(<Farm instance 1>, <Farm instance5>)
were farms will be those that have trees in that particular query set.
For all farms that have trees, use qs = Tree.objects
Keep in mind that if you add order_by('some_other_column') then distinct will apply to the distinct combinations of 'farm' and 'some_other_column', because other column will also be in the sql query for ordering. I think it's a limitation (not an intended feature) in the api, it's described in the documentation.
|
Getting Unique Foreign Keys in Django?
|
Suppose my model looks like this:
class Farm(models.Model):
name = ...
class Tree(models.Model):
farm = models.ForeignKey(Farm)
...and I get a QuerySet of Tree objects. How do I determine what farms are represented in that QuerySet?
|
[
"http://docs.djangoproject.com/en/dev/ref/models/querysets/#in\nFarm.objects.filter(tree__in=TreeQuerySet)\n\n",
"There might be a better way to do it with the Django ORM and keep it lazy but you can get what you want with regular python (off the top of my head):\n>>> set([ t.farm for t in qs ])\n\n",
"Here is a way to have the database do the work for you:\nfarms = qs.values_list('farm', flat=True).distinct() \n#values_list() is new in Django 1.0\n\nreturn value should evaluate to something like:\n(<Farm instance 1>, <Farm instance5>)\n\nwere farms will be those that have trees in that particular query set.\nFor all farms that have trees, use qs = Tree.objects\nKeep in mind that if you add order_by('some_other_column') then distinct will apply to the distinct combinations of 'farm' and 'some_other_column', because other column will also be in the sql query for ordering. I think it's a limitation (not an intended feature) in the api, it's described in the documentation.\n"
] |
[
6,
4,
0
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0001816572_django_django_models_python.txt
|
Q:
Why does PIP install of python-couchdb experimental branch from SVN fail?
I'm setting up a Fabric/virtualenv/pip automated deployment for a project and I need to install the latest experimental branch of python-couchdb. Naturally, I stick it in my pip requirements file, like so:
-e svn+http://couchdb-python.googlecode.com/svn/branches/experimental/httplib@195#egg=CouchDB-dev_r195
However, when I run my deployment I receive the following error and traceback:
[192.168.1.200] out: Obtaining CouchDB from svn+http://couchdb-python.googlecode.com/svn/branches/experimental/httplib/#egg=CouchDB (from -r requirements.txt (line 1))
[192.168.1.200] out: Checking out http://couchdb-python.googlecode.com/svn/branches/experimental/httplib/ to ./src/couchdb
[192.168.1.200] out: Error [Errno 2] No such file or directory while executing command svn checkout -q http://couchdb-python.googlecode.com/svn/branches/experimental/httplib/ /home/sk/votersdaily/src/couchdb
[192.168.1.200] out: Exception:
[192.168.1.200] out: Traceback (most recent call last):
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main
[192.168.1.200] out: self.run(options, args)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run
[192.168.1.200] out: requirement_set.install_files(finder, force_root_egg_info=self.bundle)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 2409, in install_files
[192.168.1.200] out: req_to_install.update_editable(not self.is_download)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 1970, in update_editable
[192.168.1.200] out: vcs_backend.obtain(self.source_dir)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 3420, in obtain
[192.168.1.200] out: ['svn', 'checkout', '-q'] + rev_options + [url, dest])
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 4320, in call_subprocess
[192.168.1.200] out: cwd=cwd, env=env)
[192.168.1.200] out: File "/usr/lib/python2.6/subprocess.py", line 621, in __init__
[192.168.1.200] out: errread, errwrite)
[192.168.1.200] out: File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child
[192.168.1.200] out: raise child_exception
[192.168.1.200] out: OSError: [Errno 2] No such file or directory
Here is what I know:
The error relates to it not finding setup.py, as the files are never downloaded. It seems to be refusing to create the path /home/sk/votersdaily/src/couchdb, but for other packages it has always created this path as needed.
I can run as both root and as a local user and it fails the same.
If I create the directory manually then it pitches a prompt telling me the directory is not currently an SVN repo and asking if I would like to overwrite it. If I wipe it out it still doesn't checkout the repo.
I have reinstalled pip and recreated the virtualenv and the bug is reproduced.
I can execute this pip install on my local workstation (in virtualenv) successfully.
Suggestions? I know this must be some sort of library or permission conflict, but I can't seem top pin it down,
Thanks.
A:
Per John Paulett's comment--you must indeed have subversion installed on the server in order to execute it on the server.
I would like the egg delivered to my face chilled, if possible.
|
Why does PIP install of python-couchdb experimental branch from SVN fail?
|
I'm setting up a Fabric/virtualenv/pip automated deployment for a project and I need to install the latest experimental branch of python-couchdb. Naturally, I stick it in my pip requirements file, like so:
-e svn+http://couchdb-python.googlecode.com/svn/branches/experimental/httplib@195#egg=CouchDB-dev_r195
However, when I run my deployment I receive the following error and traceback:
[192.168.1.200] out: Obtaining CouchDB from svn+http://couchdb-python.googlecode.com/svn/branches/experimental/httplib/#egg=CouchDB (from -r requirements.txt (line 1))
[192.168.1.200] out: Checking out http://couchdb-python.googlecode.com/svn/branches/experimental/httplib/ to ./src/couchdb
[192.168.1.200] out: Error [Errno 2] No such file or directory while executing command svn checkout -q http://couchdb-python.googlecode.com/svn/branches/experimental/httplib/ /home/sk/votersdaily/src/couchdb
[192.168.1.200] out: Exception:
[192.168.1.200] out: Traceback (most recent call last):
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 482, in main
[192.168.1.200] out: self.run(options, args)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 675, in run
[192.168.1.200] out: requirement_set.install_files(finder, force_root_egg_info=self.bundle)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 2409, in install_files
[192.168.1.200] out: req_to_install.update_editable(not self.is_download)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 1970, in update_editable
[192.168.1.200] out: vcs_backend.obtain(self.source_dir)
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 3420, in obtain
[192.168.1.200] out: ['svn', 'checkout', '-q'] + rev_options + [url, dest])
[192.168.1.200] out: File "/usr/local/lib/python2.6/dist-packages/pip-0.6.1-py2.6.egg/pip.py", line 4320, in call_subprocess
[192.168.1.200] out: cwd=cwd, env=env)
[192.168.1.200] out: File "/usr/lib/python2.6/subprocess.py", line 621, in __init__
[192.168.1.200] out: errread, errwrite)
[192.168.1.200] out: File "/usr/lib/python2.6/subprocess.py", line 1126, in _execute_child
[192.168.1.200] out: raise child_exception
[192.168.1.200] out: OSError: [Errno 2] No such file or directory
Here is what I know:
The error relates to it not finding setup.py, as the files are never downloaded. It seems to be refusing to create the path /home/sk/votersdaily/src/couchdb, but for other packages it has always created this path as needed.
I can run as both root and as a local user and it fails the same.
If I create the directory manually then it pitches a prompt telling me the directory is not currently an SVN repo and asking if I would like to overwrite it. If I wipe it out it still doesn't checkout the repo.
I have reinstalled pip and recreated the virtualenv and the bug is reproduced.
I can execute this pip install on my local workstation (in virtualenv) successfully.
Suggestions? I know this must be some sort of library or permission conflict, but I can't seem top pin it down,
Thanks.
|
[
"Per John Paulett's comment--you must indeed have subversion installed on the server in order to execute it on the server.\nI would like the egg delivered to my face chilled, if possible.\n"
] |
[
1
] |
[] |
[] |
[
"deployment",
"fabric",
"pip",
"python",
"virtualenv"
] |
stackoverflow_0001815963_deployment_fabric_pip_python_virtualenv.txt
|
Q:
get `object.__doc__` as raw string
Is there a way to get object.__doc__ as a raw string, apart from adding an 'r' in-front of the doctring itself in the source code?
I have latex code inside and the '\r's, '\f's etc are creating problems.
A:
There's no such Python type as "raw string" -- there are raw string literals, which are just one syntax approach (out of many) to specify constants (i.e., literals) that are of string types. So "getting" something "as a raw string" just makes no sense. You can write docstrings as raw string literals (i.e., with the prefix r -- that's exactly what denotes a raw string literal, the specific syntax that identifies such a constant to the Python compiler), or else double up any backslashes in them (an alternative way to specify constant strings including backslash characters), but that has nothing to do with "getting" them one way or another.
A:
No, you have to add the r. If you don't add the r, there's no way you can be sure to get back the original string no matter what you do.
If you don't like raw strings the other alternative is to escape your backslashes in the strings with an extra backslash.
A:
the difference between a raw string and otherwise is just a matter of source code literal syntax. once parsed, there is no 'raw' string object. the result of repr(object.__doc__) will always be such that you can copy and paste the result into a python source script and get the original string.
consider:
>>> def foo():
... 'foo\nbar'
... pass
...
>>> foo.__doc__
'foo\nbar'
>>> print foo.__doc__
foo
bar
>>>
|
get `object.__doc__` as raw string
|
Is there a way to get object.__doc__ as a raw string, apart from adding an 'r' in-front of the doctring itself in the source code?
I have latex code inside and the '\r's, '\f's etc are creating problems.
|
[
"There's no such Python type as \"raw string\" -- there are raw string literals, which are just one syntax approach (out of many) to specify constants (i.e., literals) that are of string types. So \"getting\" something \"as a raw string\" just makes no sense. You can write docstrings as raw string literals (i.e., with the prefix r -- that's exactly what denotes a raw string literal, the specific syntax that identifies such a constant to the Python compiler), or else double up any backslashes in them (an alternative way to specify constant strings including backslash characters), but that has nothing to do with \"getting\" them one way or another.\n",
"No, you have to add the r. If you don't add the r, there's no way you can be sure to get back the original string no matter what you do.\nIf you don't like raw strings the other alternative is to escape your backslashes in the strings with an extra backslash.\n",
"the difference between a raw string and otherwise is just a matter of source code literal syntax. once parsed, there is no 'raw' string object. the result of repr(object.__doc__) will always be such that you can copy and paste the result into a python source script and get the original string. \nconsider:\n>>> def foo():\n... 'foo\\nbar'\n... pass\n...\n>>> foo.__doc__\n'foo\\nbar'\n>>> print foo.__doc__\nfoo\nbar\n>>>\n\n"
] |
[
7,
2,
2
] |
[] |
[] |
[
"pydoc",
"python"
] |
stackoverflow_0001817064_pydoc_python.txt
|
Q:
MySQL driver issues with INFORMATION_SCHEMA?
I'm trying out the Concurrence framework for Stackless Python. It includes a MySQL driver and when running some code that previously ran fine with MySQLdb it fails.
What I am doing:
Connecting to the MySQL database using dbapi with username/password/port/database.
Executing SELECT * FROM INFORMATION_SCHEMA.COLUMNS
This fails with message:
Table 'mydatabase.columns' doesn't exist
"mydatabase" is the database I specified in step 1.
When doing the same query in the MySQL console after issuing "USE mydatabase", it works perfectly.
Checking the network communication yields something like this:
>>>myusername
>>>scrambled password
>>>mydatabase
>>>CMD 3 SET AUTOCOMMIT = 0
<<<0
>>>CMD 3 SELECT * FROM INFORMATION_SCHEMA.COLUMNS
<<<255
<<<Table 'mydatabase.columns' doesn't exist
Is this a driver issue (since it works in MySQLdb)? Or am I not supposed to be able to query INFORMATION_SCHEMA this way?
If I send a specific "USE INFORMATION_SCHEMA" before trying to query it, I get the expected result. But, I do not want to have to sprinkle my code all over with "USE" queries.
A:
It definitely looks like a driver issue. Maybe the python driver don't support the DB prefix.
Just to be sure, try the other way around: first use INFORMATION_SCHEMA and then SELECT * FROM mydatabase.sometable
A:
I finally found the reason.
The driver just echoed the server capability flags back in the protocol handshake, with the exception of compression:
## concurrence/database/mysql/client.py ##
client_caps = server_caps
#always turn off compression
client_caps &= ~CAPS.COMPRESS
As the server has the capability...
CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
...that was echoed back to the server, telling it not to allow that syntax.
Adding client_caps &= ~CAPS.NO_SCHEMA did the trick.
|
MySQL driver issues with INFORMATION_SCHEMA?
|
I'm trying out the Concurrence framework for Stackless Python. It includes a MySQL driver and when running some code that previously ran fine with MySQLdb it fails.
What I am doing:
Connecting to the MySQL database using dbapi with username/password/port/database.
Executing SELECT * FROM INFORMATION_SCHEMA.COLUMNS
This fails with message:
Table 'mydatabase.columns' doesn't exist
"mydatabase" is the database I specified in step 1.
When doing the same query in the MySQL console after issuing "USE mydatabase", it works perfectly.
Checking the network communication yields something like this:
>>>myusername
>>>scrambled password
>>>mydatabase
>>>CMD 3 SET AUTOCOMMIT = 0
<<<0
>>>CMD 3 SELECT * FROM INFORMATION_SCHEMA.COLUMNS
<<<255
<<<Table 'mydatabase.columns' doesn't exist
Is this a driver issue (since it works in MySQLdb)? Or am I not supposed to be able to query INFORMATION_SCHEMA this way?
If I send a specific "USE INFORMATION_SCHEMA" before trying to query it, I get the expected result. But, I do not want to have to sprinkle my code all over with "USE" queries.
|
[
"It definitely looks like a driver issue. Maybe the python driver don't support the DB prefix.\nJust to be sure, try the other way around: first use INFORMATION_SCHEMA and then SELECT * FROM mydatabase.sometable\n",
"I finally found the reason.\nThe driver just echoed the server capability flags back in the protocol handshake, with the exception of compression:\n## concurrence/database/mysql/client.py ##\n\nclient_caps = server_caps \n\n#always turn off compression\nclient_caps &= ~CAPS.COMPRESS\n\nAs the server has the capability...\nCLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */ \n...that was echoed back to the server, telling it not to allow that syntax.\nAdding client_caps &= ~CAPS.NO_SCHEMA did the trick.\n"
] |
[
1,
1
] |
[] |
[] |
[
"mysql",
"python",
"python_db_api",
"python_stackless"
] |
stackoverflow_0001814408_mysql_python_python_db_api_python_stackless.txt
|
Q:
Python MySQL: clean multiple foreign keys table
I am working with Python MySQL, and need to clean a table in my database that has 13328 rows.
I can not make a simple drop table, because this table is child and also father of other child foreign-keys linked on it. If I try drop table, the system forbidden me. The table is defined with ON UPDATE CASCADE, ON DELETE CASCADE and InnoDB; The primary_key index to that table is defined as
productID INT(6) NOT NULL AUTO_INCREMENT ...
PRIMARY KEY (productID,productNO)
Therefore, I just have to clean; this will automatically restore the table primary key index to 1 for the next input. Right?
This procedure worked fine for another table that was a father table, but not also a father and child table. But, for this table, which is child and father of other tables, I got stuck on it.
Here is the code - productID is my primary index key to this table:
def clean_tableProduct(self):
getMaxID_MySQLQuery = """SELECT MAX(productID)
FROM product;"""
cleanTabeMySQLQuery="""DELETE FROM product WHERE productID <=%s;"""
self.cursorMySQL.execute(getMaxID_MySQLQuery)
for row in self.cursorMySQL:
self.cursorMySQL.execute(cleanTabeMySQLQuery,(row[0],))
If I go to the MySQL console to check the processing results, it gets me:
mysql> SELECT MIN(productID)
FROM product;
4615748
mysql> SELECT MAX(productID)
FROM product;
4629075
If I run the same command on console to clean the table, it works:
mysql> DELETE FROM product WHERE productID <='4629075';
Query OK, 13328 rows affected (0.64 sec)
and shows me what I would normally expect.
However, if I go to Python function after having cleaned the table on console, and run the program again, and clean the table to restart the processing, it restarts the table index not with MIN:1, but instead 4629076.
Any suggestion?
All comments and suggestions are highly appreciated and welcome.
A:
To remove all records from the table:
truncate table product
To reset next ID to 1:
ALTER TABLE product AUTO_INCREMENT = 1
or
SET insert_id;
INSERT INTO product ...;
(I haven't tested this. But i should work)
A:
If you clean a table with truncate:
TRUNCATE TABLE product
As a side effect, that will reset the auto-increment counter. But you can also reset it manually:
ALTER TABLE product AUTO_INCREMENT = 1
A:
Thanks a lot for all input and quick feedback. It did the trick!
Here is how it looks now:
def clean_tableProduct(self):
cleanTabeMySQLQuery = """TRUNCATE TABLE product;"""
self.cursorMySQL.execute(cleanTabeMySQLQuery)
setIndexMySQLQuery = """ALTER TABLE product AUTO_INCREMENT = 1;"""
self.cursorMySQL.execute(setIndexMySQLQuery)
|
Python MySQL: clean multiple foreign keys table
|
I am working with Python MySQL, and need to clean a table in my database that has 13328 rows.
I can not make a simple drop table, because this table is child and also father of other child foreign-keys linked on it. If I try drop table, the system forbidden me. The table is defined with ON UPDATE CASCADE, ON DELETE CASCADE and InnoDB; The primary_key index to that table is defined as
productID INT(6) NOT NULL AUTO_INCREMENT ...
PRIMARY KEY (productID,productNO)
Therefore, I just have to clean; this will automatically restore the table primary key index to 1 for the next input. Right?
This procedure worked fine for another table that was a father table, but not also a father and child table. But, for this table, which is child and father of other tables, I got stuck on it.
Here is the code - productID is my primary index key to this table:
def clean_tableProduct(self):
getMaxID_MySQLQuery = """SELECT MAX(productID)
FROM product;"""
cleanTabeMySQLQuery="""DELETE FROM product WHERE productID <=%s;"""
self.cursorMySQL.execute(getMaxID_MySQLQuery)
for row in self.cursorMySQL:
self.cursorMySQL.execute(cleanTabeMySQLQuery,(row[0],))
If I go to the MySQL console to check the processing results, it gets me:
mysql> SELECT MIN(productID)
FROM product;
4615748
mysql> SELECT MAX(productID)
FROM product;
4629075
If I run the same command on console to clean the table, it works:
mysql> DELETE FROM product WHERE productID <='4629075';
Query OK, 13328 rows affected (0.64 sec)
and shows me what I would normally expect.
However, if I go to Python function after having cleaned the table on console, and run the program again, and clean the table to restart the processing, it restarts the table index not with MIN:1, but instead 4629076.
Any suggestion?
All comments and suggestions are highly appreciated and welcome.
|
[
"To remove all records from the table: \ntruncate table product\n\nTo reset next ID to 1:\nALTER TABLE product AUTO_INCREMENT = 1\n\nor \nSET insert_id;\nINSERT INTO product ...;\n\n(I haven't tested this. But i should work) \n",
"If you clean a table with truncate:\nTRUNCATE TABLE product\n\nAs a side effect, that will reset the auto-increment counter. But you can also reset it manually:\nALTER TABLE product AUTO_INCREMENT = 1\n\n",
"Thanks a lot for all input and quick feedback. It did the trick!\nHere is how it looks now:\ndef clean_tableProduct(self):\n cleanTabeMySQLQuery = \"\"\"TRUNCATE TABLE product;\"\"\"\n self.cursorMySQL.execute(cleanTabeMySQLQuery)\n\n setIndexMySQLQuery = \"\"\"ALTER TABLE product AUTO_INCREMENT = 1;\"\"\"\n self.cursorMySQL.execute(setIndexMySQLQuery)\n\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"auto_increment",
"foreign_keys",
"mysql",
"python"
] |
stackoverflow_0001812191_auto_increment_foreign_keys_mysql_python.txt
|
Q:
SQL syntax error using Python and psycopg
How can you fix this SQL-code?
My Python code:
import os, pg, sys, re, psycopg2
conn = psycopg2.connect("dbname=tk user=masi password=123")
cur = conn.cursor()
cur.execute("""INSERT INTO courses ('course_nro')
VALUES ( `:1` )""", ['hen'])
I get:
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
psycopg2.ProgrammingError: syntax error at or near "'course_nro'"
LINE 1: INSERT INTO courses ('course_nro')
^
A:
You made 3 different errors in the same query:
Field names should not be quoted.
psycopg2 uses tuples, not lists for arguments.
Positional arguments like ":1" are not supported.
Change your query into:
cur.execute("""INSERT INTO courses (course_nro)
VALUES (%s)""", ('hen',))
A:
Remove the quotes around the fieldname:
INSERT INTO courses (course_nro)
|
SQL syntax error using Python and psycopg
|
How can you fix this SQL-code?
My Python code:
import os, pg, sys, re, psycopg2
conn = psycopg2.connect("dbname=tk user=masi password=123")
cur = conn.cursor()
cur.execute("""INSERT INTO courses ('course_nro')
VALUES ( `:1` )""", ['hen'])
I get:
Traceback (most recent call last):
File "<stdin>", line 13, in <module>
psycopg2.ProgrammingError: syntax error at or near "'course_nro'"
LINE 1: INSERT INTO courses ('course_nro')
^
|
[
"You made 3 different errors in the same query:\n\nField names should not be quoted.\npsycopg2 uses tuples, not lists for arguments.\nPositional arguments like \":1\" are not supported.\n\nChange your query into:\ncur.execute(\"\"\"INSERT INTO courses (course_nro)\n VALUES (%s)\"\"\", ('hen',))\n",
"Remove the quotes around the fieldname:\nINSERT INTO courses (course_nro)\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"python",
"sql",
"sql_injection"
] |
stackoverflow_0001778778_python_sql_sql_injection.txt
|
Q:
Constants in python?
I have the following variables declared in a lot of functions, as I need those values in each one of them. Is there anyway I can declare them at a global scope or something, such as I won't have to declare them in all my methods? I am using all this methods on instance methods of a class of mine.
x = 0
y = 1
t = 2
In c# I'd just declare them as global class variables, but the problem is that I don't want to have to use them always as self.x, self.y and self.z, as it gets my algorithm's code uglier than it already is. How would you do this?
A typical usage of this would be:
def _GetStateFromAction(self, state, action):
x = 0
y = 1
t = 2
if (action == 0):
return (state[x], state[y] - 1, state[t])
if (action == 1):
return (state[x] - 1, state[y], state[t])
A:
If they're all within a single module, then they only live in that module's namespace and you don't have to worry about name clashes. (And you can still import them into other namesapaces)
For example
MyModWithContstants.py
x = 0
y = 0
def someFunc():
dosomethingwithconstants(x,y)
and we can also do
anotherMod.py
from MyModWithConstants import x
# and also we can do
import MyModWithConstants as MMWC
def somOtherFunc():
dosomethingNew(x, MMWC.y)
## x and MMWC.y both refer to things in the other file
A:
In addition to the separate module trick, if I want them in the same module I'll often put them in a class, like this:
class PathConstants(object):
CSIDL_DESKTOP = 0
CSIDL_PROGRAMS = 2
def get_desktop():
return _get_path_buf(PathConstants.CSIDL_DESKTOP)
If you want to make them more constant-y, then you can make setattr throw:
class ConstantExeption(Exception):
pass
class ProgramConstants(object):
foo = 10
bar = 13
def __setattr__(self, key, val):
raise ConstantExeption("Cannot change value of %s" % key)
# got to use an instance...
constants = ProgramConstants()
print constants.foo
constants.bar = "spam"
The traceback:
10
Traceback (most recent call last):
File "...", line 14, in <module>
constants.bar = "spam"
File "...", line 9, in __setattr__
raise ConstantExeption("Cannot change value of %s" % key)
__main__.ConstantExeption: Cannot change value of bar
A:
You could simply declare these variables at the module level (i.e. the top level of the .py source file) and there will be no need to use self or anything like that. In that case I think the convention would be to give them uppercase names.
By the way, I can't help but point out that you could be declaring them like this:
x, y, t = 0, 1, 2
A:
If these "variables" are truly constants declaring them at module level seems logical. If you have to modify them from inside a function you just have to declare them global in that function.
A:
Have you considered
global x, y, z
x=0
y=1
z=2
?
|
Constants in python?
|
I have the following variables declared in a lot of functions, as I need those values in each one of them. Is there anyway I can declare them at a global scope or something, such as I won't have to declare them in all my methods? I am using all this methods on instance methods of a class of mine.
x = 0
y = 1
t = 2
In c# I'd just declare them as global class variables, but the problem is that I don't want to have to use them always as self.x, self.y and self.z, as it gets my algorithm's code uglier than it already is. How would you do this?
A typical usage of this would be:
def _GetStateFromAction(self, state, action):
x = 0
y = 1
t = 2
if (action == 0):
return (state[x], state[y] - 1, state[t])
if (action == 1):
return (state[x] - 1, state[y], state[t])
|
[
"If they're all within a single module, then they only live in that module's namespace and you don't have to worry about name clashes. (And you can still import them into other namesapaces)\nFor example\nMyModWithContstants.py\nx = 0\ny = 0\n\ndef someFunc():\n dosomethingwithconstants(x,y)\n\nand we can also do\nanotherMod.py\nfrom MyModWithConstants import x\n# and also we can do\nimport MyModWithConstants as MMWC\n\ndef somOtherFunc():\n dosomethingNew(x, MMWC.y) \n ## x and MMWC.y both refer to things in the other file\n\n",
"In addition to the separate module trick, if I want them in the same module I'll often put them in a class, like this:\nclass PathConstants(object):\n CSIDL_DESKTOP = 0\n CSIDL_PROGRAMS = 2\n\ndef get_desktop():\n return _get_path_buf(PathConstants.CSIDL_DESKTOP)\n\nIf you want to make them more constant-y, then you can make setattr throw:\nclass ConstantExeption(Exception):\n pass\n\nclass ProgramConstants(object):\n foo = 10\n bar = 13\n def __setattr__(self, key, val):\n raise ConstantExeption(\"Cannot change value of %s\" % key)\n\n# got to use an instance...\nconstants = ProgramConstants()\nprint constants.foo\nconstants.bar = \"spam\"\n\nThe traceback:\n10\nTraceback (most recent call last):\n File \"...\", line 14, in <module>\n constants.bar = \"spam\"\n File \"...\", line 9, in __setattr__\n raise ConstantExeption(\"Cannot change value of %s\" % key)\n__main__.ConstantExeption: Cannot change value of bar\n\n",
"You could simply declare these variables at the module level (i.e. the top level of the .py source file) and there will be no need to use self or anything like that. In that case I think the convention would be to give them uppercase names.\nBy the way, I can't help but point out that you could be declaring them like this:\nx, y, t = 0, 1, 2\n\n",
"If these \"variables\" are truly constants declaring them at module level seems logical. If you have to modify them from inside a function you just have to declare them global in that function.\n",
"Have you considered \nglobal x, y, z\nx=0\ny=1\nz=2\n\n?\n"
] |
[
12,
5,
1,
1,
0
] |
[
"import __builtin__\n__builtin__.__dict__[\"X\"] = 5\nThis will store the X constant in all modules executed until the interpreter exits.\nRemember though to use it with care, as other python developers are not likely to expect this.\nI use it mainly for storing the translation function '_'.\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0001817144_python.txt
|
Q:
Override default User model method
I've been trying to override the default __unicode__() method for the django.contrib.auth.models User model but I can't get it to work.
I tried it like this:
from django.db import models
from django.contrib.auth.models import User
class User(models.Model):
def __unicode__(self):
return "pie"
and
from django.db import models
from django.contrib.auth.models import User
class User(User):
def __unicode__(self):
return "pie"
but it's not working, I know it's wrong like that but I have no idea how to do it properly.
All I want it to do is to say "pie" instead of the user name inside the admin panel.
edit:
Managed to do it like this:
class MyUser(User):
class Meta:
proxy = True
def __unicode__(self):
if self.get_full_name() == '':
return "pie"
else:
return self.get_full_name()
I used the MyUser class when making ForeignKey references, instead of User.
A:
You might want to look at Django's Proxy Model concept. They even show an example using User as a base class.
On the other hand, if you are trying to change the actual __unicode__() method in the actual User class, you probably will have to MonkeyPatch it. It's not difficult, but I'll leave the specifics as a learning experience for you.
|
Override default User model method
|
I've been trying to override the default __unicode__() method for the django.contrib.auth.models User model but I can't get it to work.
I tried it like this:
from django.db import models
from django.contrib.auth.models import User
class User(models.Model):
def __unicode__(self):
return "pie"
and
from django.db import models
from django.contrib.auth.models import User
class User(User):
def __unicode__(self):
return "pie"
but it's not working, I know it's wrong like that but I have no idea how to do it properly.
All I want it to do is to say "pie" instead of the user name inside the admin panel.
edit:
Managed to do it like this:
class MyUser(User):
class Meta:
proxy = True
def __unicode__(self):
if self.get_full_name() == '':
return "pie"
else:
return self.get_full_name()
I used the MyUser class when making ForeignKey references, instead of User.
|
[
"You might want to look at Django's Proxy Model concept. They even show an example using User as a base class.\nOn the other hand, if you are trying to change the actual __unicode__() method in the actual User class, you probably will have to MonkeyPatch it. It's not difficult, but I'll leave the specifics as a learning experience for you.\n"
] |
[
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001817244_django_python.txt
|
Q:
PyKDE4 documentation
I'm trying to get started using Python for KDE development. What is the canonical source for PyKDE4 reference documentation? The Python page of KDE TechBase is surprisingly sparse on details, and googling hasn't helped.
A:
Here.
|
PyKDE4 documentation
|
I'm trying to get started using Python for KDE development. What is the canonical source for PyKDE4 reference documentation? The Python page of KDE TechBase is surprisingly sparse on details, and googling hasn't helped.
|
[
"Here.\n"
] |
[
1
] |
[] |
[] |
[
"pykde",
"python"
] |
stackoverflow_0001817751_pykde_python.txt
|
Q:
What are these errors and how do I handle them?
I am using this simple code
for l in bios:
OpenThisLink = url + l
response = urllib2.urlopen(OpenThisLink)
to open about 200 urls and search them with regex (and BeautifulSoup), but after a dozen or so I get these errors and IDLE quits. What do they mean? How can I handle them?
Thank you.
Traceback (most recent call last):
File "\PROJECTS\JD\jd10.py", line 15, in <module> response = urllib2.urlopen(OpenThisLink)
File "C:\Python26\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout)
File "C:\Python26\lib\urllib2.py", line 389, in open response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 421, in error result = self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args)
File "C:\Python26\lib\urllib2.py", line 597, in http_error_302 return self.parent.open(new)
File "C:\Python26\lib\urllib2.py", line 389, in open response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 421, in error result = self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args)
File "C:\Python26\lib\urllib2.py", line 597, in http_error_302 return self.parent.open(new)
File "C:\Python26\lib\urllib2.py", line 389, in open response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 427, in error return self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args)
File "C:\Python26\lib\urllib2.py", line 510, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 404: Not Found
A:
The error being raised is HTTPError - specifically, a 404 is being thrown for one of your URLs. You could either ignore it:
for l in bios:
OpenThisLink = url + l
try:
response = urllib2.urlopen(OpenThisLink)
except urllib2.HTTPError:
pass
Or, you could re-raise the error with a (marginally) more meaningful message:
for l in bios:
OpenThisLink = url + l
try:
response = urllib2.urlopen(OpenThisLink)
except urllib2.HTTPError as e:
raise Exception('Error opening %s: %s' % (e.geturl(), e))
A:
I don't know anything about the particular libraries you're using. However, this looks to me like one big stack trace that leads to this original error at the very end:
HTTPError: HTTP Error 404: Not Found
I think one of the links was bad and that triggered an exception which wasn't caught.
Edit: By "bad" I mean the page couldn't be retrieved by the server, hence the 404 error.
|
What are these errors and how do I handle them?
|
I am using this simple code
for l in bios:
OpenThisLink = url + l
response = urllib2.urlopen(OpenThisLink)
to open about 200 urls and search them with regex (and BeautifulSoup), but after a dozen or so I get these errors and IDLE quits. What do they mean? How can I handle them?
Thank you.
Traceback (most recent call last):
File "\PROJECTS\JD\jd10.py", line 15, in <module> response = urllib2.urlopen(OpenThisLink)
File "C:\Python26\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data, timeout)
File "C:\Python26\lib\urllib2.py", line 389, in open response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 421, in error result = self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args)
File "C:\Python26\lib\urllib2.py", line 597, in http_error_302 return self.parent.open(new)
File "C:\Python26\lib\urllib2.py", line 389, in open response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 421, in error result = self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args)
File "C:\Python26\lib\urllib2.py", line 597, in http_error_302 return self.parent.open(new)
File "C:\Python26\lib\urllib2.py", line 389, in open response = meth(req, response)
File "C:\Python26\lib\urllib2.py", line 502, in http_response 'http', request, response, code, msg, hdrs)
File "C:\Python26\lib\urllib2.py", line 427, in error return self._call_chain(*args)
File "C:\Python26\lib\urllib2.py", line 361, in _call_chain result = func(*args)
File "C:\Python26\lib\urllib2.py", line 510, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 404: Not Found
|
[
"The error being raised is HTTPError - specifically, a 404 is being thrown for one of your URLs. You could either ignore it:\nfor l in bios:\n OpenThisLink = url + l\n try:\n response = urllib2.urlopen(OpenThisLink)\n except urllib2.HTTPError:\n pass\n\nOr, you could re-raise the error with a (marginally) more meaningful message:\nfor l in bios:\n OpenThisLink = url + l\n try:\n response = urllib2.urlopen(OpenThisLink)\n except urllib2.HTTPError as e:\n raise Exception('Error opening %s: %s' % (e.geturl(), e))\n\n",
"I don't know anything about the particular libraries you're using. However, this looks to me like one big stack trace that leads to this original error at the very end:\n\nHTTPError: HTTP Error 404: Not Found\n\nI think one of the links was bad and that triggered an exception which wasn't caught.\nEdit: By \"bad\" I mean the page couldn't be retrieved by the server, hence the 404 error.\n"
] |
[
3,
2
] |
[] |
[] |
[
"beautifulsoup",
"python"
] |
stackoverflow_0001817815_beautifulsoup_python.txt
|
Q:
Format Python List to SQL script?
I have a list need to be format it to SQL scripte
list =
[['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0\n'],
['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0\n'],
['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0\n'],
To sql script like this:
INSERT INTO `Tbl_ABC` VALUES (11, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (12, 0, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (13, 0, '2 STRUCTURES', '2D STRUCTURES', NULL, NULL, 0)
This I have try
import pickle
import re
#RX = re.compile(r'^.*?\(\d+,\s0,.*\s0\)\s*$')
outfile = open('destination.sql', 'wb')
data = []
for ln in open('source.sql', 'r').xreadlines():
replace1 = ln.replace("INSERT INTO `Tbl_ABC` VALUES (", "")
replace2 = replace1.replace(")", "")
list_replace = replace2.split(',')
data.append(list_replace)
destinationdata = [d for d in data if d[1] == ' 0' and d[6]==' 0\n']#print '%s ,%s' % (list_replace[1], list_replace[6])
#start write line to destination.sql
#if RX.match(ln):
pickle.dump(destinationdata, outfile)
outfile.close()
Thank for your help !
A:
Iterate over each element in the list
Unpack the element (which is also a list) into its fields
Generate a SQL line from these fields
The simplest and ugliest way that just gets the job done is:
list = [
['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0'],
['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0'],
['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0']]
for elem in list:
print 'INSERT INTO \'Tbl_ABS\' VALUES (%s, %s, %s, %s, %s, %s, %s)' % tuple(elem)
Note I cleaned the '\n' after the 0 (adapt accordingly if it's needed there).
This is OK for one-off scripts. For more serious reporting and conversions, look at some template libraries to separate your data and presentation.
A:
Basically, this should work
print "\n".join(["INSERT INTO `Tbl_ABC` VALUES ("+",".join(x).strip()+")" for x in list1])
result
INSERT INTO `Tbl_ABC` VALUES (11, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (12, 0, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (13, 0, '2 STRUCTURES', '2D STRUCTURES', NULL, NULL, 0)
Adjust it if there is minor difference, depends on your need.
ps: I intentionally changed list to list1 in my code, because overriding built-in function is not good idea.
A:
Technically it's fairly easy to take a list and convert it into sql by hand, but .... you might consider checking out SQLAlchemy http://www.sqlalchemy.org. It is I feel really superb. It will do all your conversions for you from Python objects into database table rows, and can retrieve python objects back from the tables.
You can do things like this:
# retrieve each row from the company table and print it :-O
for company in session.query(Company):
print company.name + " " + company.address
# add a new company to the company table:
company = Company("Fred Flintstone", "The Quarry")
session.add(company)
session.commit()
|
Format Python List to SQL script?
|
I have a list need to be format it to SQL scripte
list =
[['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0\n'],
['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0\n'],
['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0\n'],
To sql script like this:
INSERT INTO `Tbl_ABC` VALUES (11, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (12, 0, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)
INSERT INTO `Tbl_ABC` VALUES (13, 0, '2 STRUCTURES', '2D STRUCTURES', NULL, NULL, 0)
This I have try
import pickle
import re
#RX = re.compile(r'^.*?\(\d+,\s0,.*\s0\)\s*$')
outfile = open('destination.sql', 'wb')
data = []
for ln in open('source.sql', 'r').xreadlines():
replace1 = ln.replace("INSERT INTO `Tbl_ABC` VALUES (", "")
replace2 = replace1.replace(")", "")
list_replace = replace2.split(',')
data.append(list_replace)
destinationdata = [d for d in data if d[1] == ' 0' and d[6]==' 0\n']#print '%s ,%s' % (list_replace[1], list_replace[6])
#start write line to destination.sql
#if RX.match(ln):
pickle.dump(destinationdata, outfile)
outfile.close()
Thank for your help !
|
[
"Iterate over each element in the list\n Unpack the element (which is also a list) into its fields\n Generate a SQL line from these fields\n\nThe simplest and ugliest way that just gets the job done is:\nlist = [\n ['11', ' 0', \" 'MMB'\", \" '2 MB INTERNATIONAL'\", ' NULL', ' NULL', ' 0'], \n ['12', ' 0', \" '3D STRUCTURES'\", \" '3D STRUCTURES'\", ' NULL', ' NULL', ' 0'],\n ['13', ' 0', \" '2 STRUCTURES'\", \" '2D STRUCTURES'\", ' NULL', ' NULL', ' 0']]\n\nfor elem in list:\n print 'INSERT INTO \\'Tbl_ABS\\' VALUES (%s, %s, %s, %s, %s, %s, %s)' % tuple(elem)\n\nNote I cleaned the '\\n' after the 0 (adapt accordingly if it's needed there).\nThis is OK for one-off scripts. For more serious reporting and conversions, look at some template libraries to separate your data and presentation.\n",
"Basically, this should work\nprint \"\\n\".join([\"INSERT INTO `Tbl_ABC` VALUES (\"+\",\".join(x).strip()+\")\" for x in list1])\n\nresult\nINSERT INTO `Tbl_ABC` VALUES (11, 0, 'MMB', '2 MB INTERNATIONAL', NULL, NULL, 0)\nINSERT INTO `Tbl_ABC` VALUES (12, 0, '3D STRUCTURES', '3D STRUCTURES', NULL, NULL, 0)\nINSERT INTO `Tbl_ABC` VALUES (13, 0, '2 STRUCTURES', '2D STRUCTURES', NULL, NULL, 0)\n\nAdjust it if there is minor difference, depends on your need.\nps: I intentionally changed list to list1 in my code, because overriding built-in function is not good idea.\n",
"Technically it's fairly easy to take a list and convert it into sql by hand, but .... you might consider checking out SQLAlchemy http://www.sqlalchemy.org. It is I feel really superb. It will do all your conversions for you from Python objects into database table rows, and can retrieve python objects back from the tables.\nYou can do things like this:\n# retrieve each row from the company table and print it :-O\nfor company in session.query(Company):\n print company.name + \" \" + company.address\n\n# add a new company to the company table:\ncompany = Company(\"Fred Flintstone\", \"The Quarry\")\nsession.add(company)\nsession.commit()\n\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0001817886_python.txt
|
Q:
How to convert seconds to hh:mm:ss with the Django's date template tag?
Edit : is there a way to easily convert {{ value|date:"Z" }} to one of the +hh:mm or -hh:mm formats (because date:"Z" returns xxxx or -xxxx seconds).
Show this for more explanations about the needed format.
Thank you and sorry for my ugly english. ;)
A:
Just clarifying here, it's the timezone offset that needs the colon, ie 2009-11-29T14:33:59-0600 in the above example should be 2009-11-29T14:33:59-06:00 to conform to the W3C guidelines.
Looking at the code at django/utils/dateformat.py:
def O(self):
"Difference to Greenwich time in hours; e.g. '+0200'"
seconds = self.Z()
return u"%+03d%02d" % (seconds // 3600, (seconds // 60) % 60)
You could edit your local copy of django to add the ':' so; return u"%+03d:%02d" % (seconds // 3600, (seconds // 60) % 60) or create your own template tag to do effectively the same thing. But probably the easiest is to compose the string in your view, and pass that along as a variable to the template.
It doesn't look like the HTML5 version of timezone is available out of the box.
[update]
On reflection you could probably do this;
>>> from django.utils import dateformat
>>> fmt = "Y-m-d\TH:i:sO"
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 12, 1, 12, 39, 48, 655867)
>>> str = dateformat.format(now, fmt)
>>> print str
2009-12-01T12:39:48+0000
>>>
and then add the ':'
>>> s = str[:-2] + ':' + str[-2:]
>>> s
u'2009-12-01T12:39:48+00:00'
>>>
A:
Instead of Z you need O (that's an "oh", not a "zero").
>>> from django.template import *
>>> Template('{% now "Y-m-d\TH:i:sO" %}').render(Context())
u'2009-11-29T14:33:59-0600'
|
How to convert seconds to hh:mm:ss with the Django's date template tag?
|
Edit : is there a way to easily convert {{ value|date:"Z" }} to one of the +hh:mm or -hh:mm formats (because date:"Z" returns xxxx or -xxxx seconds).
Show this for more explanations about the needed format.
Thank you and sorry for my ugly english. ;)
|
[
"Just clarifying here, it's the timezone offset that needs the colon, ie 2009-11-29T14:33:59-0600 in the above example should be 2009-11-29T14:33:59-06:00 to conform to the W3C guidelines.\nLooking at the code at django/utils/dateformat.py:\n def O(self):\n \"Difference to Greenwich time in hours; e.g. '+0200'\"\n seconds = self.Z()\n return u\"%+03d%02d\" % (seconds // 3600, (seconds // 60) % 60)\n\nYou could edit your local copy of django to add the ':' so; return u\"%+03d:%02d\" % (seconds // 3600, (seconds // 60) % 60) or create your own template tag to do effectively the same thing. But probably the easiest is to compose the string in your view, and pass that along as a variable to the template.\nIt doesn't look like the HTML5 version of timezone is available out of the box.\n[update]\nOn reflection you could probably do this;\n>>> from django.utils import dateformat\n>>> fmt = \"Y-m-d\\TH:i:sO\"\n>>> import datetime\n>>> now = datetime.datetime.now()\n>>> now\ndatetime.datetime(2009, 12, 1, 12, 39, 48, 655867)\n>>> str = dateformat.format(now, fmt)\n>>> print str\n2009-12-01T12:39:48+0000\n>>>\n\nand then add the ':' \n>>> s = str[:-2] + ':' + str[-2:]\n>>> s\nu'2009-12-01T12:39:48+00:00'\n>>> \n\n",
"Instead of Z you need O (that's an \"oh\", not a \"zero\").\n>>> from django.template import *\n>>> Template('{% now \"Y-m-d\\TH:i:sO\" %}').render(Context())\nu'2009-11-29T14:33:59-0600'\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"django_templates",
"python"
] |
stackoverflow_0001816176_django_django_templates_python.txt
|
Q:
Choosing and deploying a comet server
I want to push data to the browser over HTTP without killing my django/python application.
I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).
I've looked into the following engines:
orbited
cometd
ejabberd
jetty
Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.
A:
I would recommend looking into Twisted, their twisted.web server, and the comet work done on top of it at Divmod. They can handle far more concurrent connections than traditional thread or process based servers, which is exactly what you need for something like this. And, yes, I've architected systems using Twisted for COMET stuff, while using other things for the more front-facing web applications beside it. It works out well with each part doing what it does best.
A:
I need to do something very similar. I found this, but haven't had the time to look at it properly yet:
django_evserver is simple http server
for Django applications. It's based on
libevent library. The main advantage
of django_evserver is that it provides
methods of preempting django views.
You can render a site in several
chunks, each of them can be handled by
different django view.
Using this idea it's possible to use
django_evserver as comet server for
django applications.
http://code.google.com/p/django-evserver/
A:
If you can run Java I would recommend StreamHub Comet Server.
Firstly, regarding your need not to 'kill' your existing application, the JavaScript include has a really low footprint at less than 10K. I use it for pushing user updates and chat on the social networking site I'm building. I tested with a 1000+ hits a day and there was no noticeable effect on the CPU.
Secondly, on deploying, I followed some of the examples and was up and running really quickly compared to banging my head against a wall with CometD. There is a good Comet Hello World getting started guide and a Google Group if you get stuck on anything.
A:
One option is Netty, client-server socket framework based on Java NIO from JBoss. For a comparison and discussion see here. It reportedly handles 100000 simultaneous open connections on a quad-core server.
A:
If you're running IIS, you can check out WebSync (http://www.frozenmountain.com/websync), a standards-compliant (bayeux) comet server and client for .NET/IIS. If you don't want the additional load, the On-Demand version is a SaaS option that offloads the heavy lifting.
A:
If you're looking to combine Django with a Comet server (Orbited), check this project I have going to integrate Django and Orbited in as "clean" and "real-world" as possible here: http://github.com/clemesha/hotdot
The project addresses "real-world" problems like security and logging/filtering/modifying the in-transit Comet messages, etc - but is still a work in progress.
|
Choosing and deploying a comet server
|
I want to push data to the browser over HTTP without killing my django/python application.
I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).
I've looked into the following engines:
orbited
cometd
ejabberd
jetty
Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.
|
[
"I would recommend looking into Twisted, their twisted.web server, and the comet work done on top of it at Divmod. They can handle far more concurrent connections than traditional thread or process based servers, which is exactly what you need for something like this. And, yes, I've architected systems using Twisted for COMET stuff, while using other things for the more front-facing web applications beside it. It works out well with each part doing what it does best.\n",
"I need to do something very similar. I found this, but haven't had the time to look at it properly yet:\n\ndjango_evserver is simple http server\n for Django applications. It's based on\n libevent library. The main advantage\n of django_evserver is that it provides\n methods of preempting django views.\n You can render a site in several\n chunks, each of them can be handled by\n different django view.\nUsing this idea it's possible to use\n django_evserver as comet server for\n django applications.\n\nhttp://code.google.com/p/django-evserver/\n",
"If you can run Java I would recommend StreamHub Comet Server. \nFirstly, regarding your need not to 'kill' your existing application, the JavaScript include has a really low footprint at less than 10K. I use it for pushing user updates and chat on the social networking site I'm building. I tested with a 1000+ hits a day and there was no noticeable effect on the CPU.\nSecondly, on deploying, I followed some of the examples and was up and running really quickly compared to banging my head against a wall with CometD. There is a good Comet Hello World getting started guide and a Google Group if you get stuck on anything.\n",
"One option is Netty, client-server socket framework based on Java NIO from JBoss. For a comparison and discussion see here. It reportedly handles 100000 simultaneous open connections on a quad-core server. \n",
"If you're running IIS, you can check out WebSync (http://www.frozenmountain.com/websync), a standards-compliant (bayeux) comet server and client for .NET/IIS. If you don't want the additional load, the On-Demand version is a SaaS option that offloads the heavy lifting.\n",
"If you're looking to combine Django with a Comet server (Orbited), check this project I have going to integrate Django and Orbited in as \"clean\" and \"real-world\" as possible here: http://github.com/clemesha/hotdot\nThe project addresses \"real-world\" problems like security and logging/filtering/modifying the in-transit Comet messages, etc - but is still a work in progress. \n"
] |
[
5,
2,
2,
2,
2,
2
] |
[] |
[] |
[
"comet",
"daemon",
"django",
"python"
] |
stackoverflow_0000621802_comet_daemon_django_python.txt
|
Q:
what functional tools remain in Python 3k?
I have have read several entries regarding dropping several functional functions from future python, including map and reduce.
What is the official policy regarding functional extensions?
is lambda function going to stay?
A:
Well, Python 3.0 and 3.1 are already released, so you can check this out for yourself. The end result was that map and filter were kept as built-ins, and lambda was also kept. The only change was that reduce was moved to the functools module; you just need to do
from functools import reduce
to use it.
Future 3.x releases can be expected to remain backwards-compatible with 3.0 and 3.1 in this respect.
A:
In Python 3.x, Python continues to have a rich set of functional-ish tools built in: list comprehensions, generator expressions, iterators and generators, and functions like any() and all() that have short-circuit evaluation wherever possible.
Python's "Benevolent Dictator For Life" floated the idea of removing map() because you can trivially reproduce its effects with a list comprehension:
lst2 = map(foo, lst)
lst3 = [foo(x) for x in lst]
lst2 == lst3 # evaluates True
Python's lambda feature has not been removed or renamed, and likely never will be. However, it will likely never become more powerful, either. Python's lambda is restricted to a single expression; it cannot include statements and it cannot include multiple lines of Python code.
Python's plain-old-standard def defines a function object, which can be passed around just as easily as a lambda object. You can even unbind the name of the function after you define it, if you really want to do so.
Example:
# NOT LEGAL PYTHON
lst2 = map(lambda x: if foo(x): x**2; else: x, lst)
# perfectly legal Python
def lambda_function(x):
if foo(x):
return x**2
else:
return x
lst2 = map(lambda_function, lst)
del(lambda_function) # can unbind the name if you wish
Note that you could actually use the "ternary operator" in a lambda so the above example is a bit contrived.
lst2 = map(lambda x: x**2 if foo(x) else x, lst)
But some multiline functions are difficult to force into a lambda and are better handled as simple ordinary multiline functions.
Python 3.x has lost none of its functional power. There is some general feeling that list comprehensions and generator expressions are probably preferable to map(); in particular, generator expressions can sometimes be used to do the equivalent of a map() but without allocating a list and then freeing it again. For example:
total = sum(map(lst, foo))
total2 = sum(foo(x) for x in lst)
assert total == total2 # same result
In Python 2.x, the map() allocates a new list, which is summed and immediately freed. The generator expression gets the values one at a time and never ties up the memory of a whole list of values.
In Python 3.x, map() is "lazy" so both are about equally efficient. But as a result, in Python 3.x the ternary lambda example needs to be forced to expand into a list:
lst2 = list(map(lambda x: x**2 if foo(x) else x, lst))
Easier to just write the list comprehension!
lst2 = [x**2 if foo(x) else x for x in lst]
|
what functional tools remain in Python 3k?
|
I have have read several entries regarding dropping several functional functions from future python, including map and reduce.
What is the official policy regarding functional extensions?
is lambda function going to stay?
|
[
"Well, Python 3.0 and 3.1 are already released, so you can check this out for yourself. The end result was that map and filter were kept as built-ins, and lambda was also kept. The only change was that reduce was moved to the functools module; you just need to do\nfrom functools import reduce\n\nto use it.\nFuture 3.x releases can be expected to remain backwards-compatible with 3.0 and 3.1 in this respect.\n",
"In Python 3.x, Python continues to have a rich set of functional-ish tools built in: list comprehensions, generator expressions, iterators and generators, and functions like any() and all() that have short-circuit evaluation wherever possible.\nPython's \"Benevolent Dictator For Life\" floated the idea of removing map() because you can trivially reproduce its effects with a list comprehension:\nlst2 = map(foo, lst)\n\nlst3 = [foo(x) for x in lst]\n\nlst2 == lst3 # evaluates True\n\nPython's lambda feature has not been removed or renamed, and likely never will be. However, it will likely never become more powerful, either. Python's lambda is restricted to a single expression; it cannot include statements and it cannot include multiple lines of Python code.\nPython's plain-old-standard def defines a function object, which can be passed around just as easily as a lambda object. You can even unbind the name of the function after you define it, if you really want to do so.\nExample:\n# NOT LEGAL PYTHON\nlst2 = map(lambda x: if foo(x): x**2; else: x, lst)\n\n# perfectly legal Python\ndef lambda_function(x):\n if foo(x):\n return x**2\n else:\n return x\n\nlst2 = map(lambda_function, lst)\n\ndel(lambda_function) # can unbind the name if you wish\n\nNote that you could actually use the \"ternary operator\" in a lambda so the above example is a bit contrived.\nlst2 = map(lambda x: x**2 if foo(x) else x, lst)\n\nBut some multiline functions are difficult to force into a lambda and are better handled as simple ordinary multiline functions.\nPython 3.x has lost none of its functional power. There is some general feeling that list comprehensions and generator expressions are probably preferable to map(); in particular, generator expressions can sometimes be used to do the equivalent of a map() but without allocating a list and then freeing it again. For example:\ntotal = sum(map(lst, foo))\n\ntotal2 = sum(foo(x) for x in lst)\n\nassert total == total2 # same result\n\nIn Python 2.x, the map() allocates a new list, which is summed and immediately freed. The generator expression gets the values one at a time and never ties up the memory of a whole list of values.\nIn Python 3.x, map() is \"lazy\" so both are about equally efficient. But as a result, in Python 3.x the ternary lambda example needs to be forced to expand into a list:\nlst2 = list(map(lambda x: x**2 if foo(x) else x, lst))\n\nEasier to just write the list comprehension!\nlst2 = [x**2 if foo(x) else x for x in lst]\n\n"
] |
[
10,
3
] |
[] |
[] |
[
"functional_programming",
"python",
"python_3.x"
] |
stackoverflow_0001817771_functional_programming_python_python_3.x.txt
|
Q:
SQLAlchemy not returning selected data
I'm using SQLAlchemy as the ORM within an application i've been building for some time.
So far, it's been quite a painless ORM to implement and use, however, a recent feature I'm working on requires a persistent & distributed queue (list & worker) style implementation, which I've built in MySQL and Python.
It's all worked quite well until I tested it in a scaled environment.
I've used InnoDB row level locking to ensure each row is only read once, while the row is locked, I update an 'in_use' value, to make sure that others don't grab at the entry.
Since MySQL doesn't offer a "NOWAIT" method like Postgre or Oracle does, I've run into locking issues where worker threads hang and wait for the locked row to become available.
In an attempt to overcome this limitation, I've tried to put all the required processing into a single statement, and run it through the ORM's execute() method, although, SQLAlchemy is refusing to return the query result.
Here's an example.
My SQL statement is:
SELECT id INTO @update_id FROM myTable WHERE in_use=0 ORDER BY id LIMIT 1 FOR UPDATE;
UPDATE myTable SET in_use=1 WHERE id=@update_id;
SELECT * FROM myTable WHERE id=@update_id;
And I run this code in the console:
engine = create_engine('mysql://<user details>@<server details>/myDatabase', pool_recycle=90, echo=True)
result = engine.execute(sqlStatement)
result.fetchall()
Only to get this result
[]
I'm certain the statement is running since I can see the update take effect in the database, and if I execute through the mysql terminal or other tools, I get the modified row returned.
It just seems to be SQLAlchemy that doesn't want to acknowledge the returned row.
Is there anything specific that needs to be done to ensure that the ORM picks up the response?
Cheers
A:
You have executed 3 queries and MySQLdb creates a result set for each. You have to fetch first result, then call cursor.nextset(), fetch second and so on.
This answers your question, but won't be useful for you, because it won't solve locking issue. You have to understand how FOR UPDATE works first: it locks returned rows till the end of transaction. To avoid long lock wait you have to make it as short as possible: SELECT ... FOR UPDATE, UPDATE SET in_use=1 ..., COMMIT. You actually don't need to put them into single SQL statement, 3 execute() calls will be OK too. But you have have to commit before long computation, otherwise lock will be held too long and updating in_use (offline lock) is meaningless. And sure you can do the same thing using ORM too.
|
SQLAlchemy not returning selected data
|
I'm using SQLAlchemy as the ORM within an application i've been building for some time.
So far, it's been quite a painless ORM to implement and use, however, a recent feature I'm working on requires a persistent & distributed queue (list & worker) style implementation, which I've built in MySQL and Python.
It's all worked quite well until I tested it in a scaled environment.
I've used InnoDB row level locking to ensure each row is only read once, while the row is locked, I update an 'in_use' value, to make sure that others don't grab at the entry.
Since MySQL doesn't offer a "NOWAIT" method like Postgre or Oracle does, I've run into locking issues where worker threads hang and wait for the locked row to become available.
In an attempt to overcome this limitation, I've tried to put all the required processing into a single statement, and run it through the ORM's execute() method, although, SQLAlchemy is refusing to return the query result.
Here's an example.
My SQL statement is:
SELECT id INTO @update_id FROM myTable WHERE in_use=0 ORDER BY id LIMIT 1 FOR UPDATE;
UPDATE myTable SET in_use=1 WHERE id=@update_id;
SELECT * FROM myTable WHERE id=@update_id;
And I run this code in the console:
engine = create_engine('mysql://<user details>@<server details>/myDatabase', pool_recycle=90, echo=True)
result = engine.execute(sqlStatement)
result.fetchall()
Only to get this result
[]
I'm certain the statement is running since I can see the update take effect in the database, and if I execute through the mysql terminal or other tools, I get the modified row returned.
It just seems to be SQLAlchemy that doesn't want to acknowledge the returned row.
Is there anything specific that needs to be done to ensure that the ORM picks up the response?
Cheers
|
[
"You have executed 3 queries and MySQLdb creates a result set for each. You have to fetch first result, then call cursor.nextset(), fetch second and so on. \nThis answers your question, but won't be useful for you, because it won't solve locking issue. You have to understand how FOR UPDATE works first: it locks returned rows till the end of transaction. To avoid long lock wait you have to make it as short as possible: SELECT ... FOR UPDATE, UPDATE SET in_use=1 ..., COMMIT. You actually don't need to put them into single SQL statement, 3 execute() calls will be OK too. But you have have to commit before long computation, otherwise lock will be held too long and updating in_use (offline lock) is meaningless. And sure you can do the same thing using ORM too.\n"
] |
[
3
] |
[] |
[] |
[
"mysql",
"python",
"sqlalchemy"
] |
stackoverflow_0001818054_mysql_python_sqlalchemy.txt
|
Q:
Sound Monitoring in C++/Python
I'm looking for an API (or some information as to where to look/start) that will ultimately allow me to monitor sound being played by the computer.
My end goal (well, certain to eventually be a stepping-stone) is an oscilloscope.
Where should I begin to look (aside from Google, which has yielded unsatisfactory results) to learn more about sound as processed by computers (particularly, Macs) and how to get to it.
Thanks!
A:
As @cobbal noted, on Mac OS X you would need to use PortAudio in some way to get the audio as it plays. The only other way to do it would be to use an audio player that has a plugin API, then write your code as a plugin for that one player. But a CoreAudio solution should make it possible for you to monitor all sounds played on the Mac.
Your CoreAudio code will not be portable at all to Windows and Linux. There is no portable solution at this time. On Windows you would probably want to use the WaveIn/WaveOut API, unless you have pro gear, in which case you would probably want to use ASIO. On Linux, I'm not sure; I think you could probably hook in to ALSA/PulseAudio to grab audio. Unless you have pro gear, in which case you would probably want to use JACK.
If you wanted a portable solution, you might want to look seriously at the plugin option. Find a portable free software media player that works on all your platforms, and make a scope plugin for that.
For an oscilloscope, you are going to want to get a book on Digital Signal Processing ("DSP"). You will probably want to use a Discrete Fourier Transform ("DFT") to get frequency information out of your discrete audio samples; a DFT library will likely be called an "FFT" library ("FFT" being short for "Fast Fourier Transform").
My favorite single book on DSP is: Understanding Digital Signal Processing by Richard G. Lyons.
EDIT: And by the way, most media players have "visualization" plugins, and some of them are displays based on frequencies. (Some even have names like "scope".) Is it possible that there is a media player that already does exactly the display you want?
A:
I have in the past used a combination of Soundflower and PyAudio for a similar purpose.
Soundflower allows you to route all audio output into an input that can then be read by PyAudio.
If you wish to use c++ instead of python, use PortAudio, the library PyAudio is based on.
|
Sound Monitoring in C++/Python
|
I'm looking for an API (or some information as to where to look/start) that will ultimately allow me to monitor sound being played by the computer.
My end goal (well, certain to eventually be a stepping-stone) is an oscilloscope.
Where should I begin to look (aside from Google, which has yielded unsatisfactory results) to learn more about sound as processed by computers (particularly, Macs) and how to get to it.
Thanks!
|
[
"As @cobbal noted, on Mac OS X you would need to use PortAudio in some way to get the audio as it plays. The only other way to do it would be to use an audio player that has a plugin API, then write your code as a plugin for that one player. But a CoreAudio solution should make it possible for you to monitor all sounds played on the Mac.\nYour CoreAudio code will not be portable at all to Windows and Linux. There is no portable solution at this time. On Windows you would probably want to use the WaveIn/WaveOut API, unless you have pro gear, in which case you would probably want to use ASIO. On Linux, I'm not sure; I think you could probably hook in to ALSA/PulseAudio to grab audio. Unless you have pro gear, in which case you would probably want to use JACK.\nIf you wanted a portable solution, you might want to look seriously at the plugin option. Find a portable free software media player that works on all your platforms, and make a scope plugin for that.\nFor an oscilloscope, you are going to want to get a book on Digital Signal Processing (\"DSP\"). You will probably want to use a Discrete Fourier Transform (\"DFT\") to get frequency information out of your discrete audio samples; a DFT library will likely be called an \"FFT\" library (\"FFT\" being short for \"Fast Fourier Transform\").\nMy favorite single book on DSP is: Understanding Digital Signal Processing by Richard G. Lyons.\nEDIT: And by the way, most media players have \"visualization\" plugins, and some of them are displays based on frequencies. (Some even have names like \"scope\".) Is it possible that there is a media player that already does exactly the display you want?\n",
"I have in the past used a combination of Soundflower and PyAudio for a similar purpose.\nSoundflower allows you to route all audio output into an input that can then be read by PyAudio.\nIf you wish to use c++ instead of python, use PortAudio, the library PyAudio is based on.\n"
] |
[
2,
1
] |
[] |
[] |
[
"audio",
"c",
"c++",
"macos",
"python"
] |
stackoverflow_0001817733_audio_c_c++_macos_python.txt
|
Q:
Python - Overridding print()
I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).
Doing this doesn't work:
print = myPrintFunction
Since it's a syntax error. :(
A:
Print is not a function in Python 2.x, so this is not directly possible.
You can, however, override sys.stdout.
If you are on Python 3.0 in which print is now a function what you have would then work, assuming you have the right signature. Also see a related question in this site.
A:
Would
import sys
sys.stdout = MyFileWrapper()
or something similar work?
A:
If you are using 3.0, print is a function. If you are using 2.6, you can from __future__ import print_function and continue with a print function.
If <= 2.5, you can replace stdout like others have suggested, but be very careful if your wsgi server will call your app in multiple threads simultaneously. You WILL end up with simultaneous requests being sent down the same pipe.
I haven't tested it, but you could try something like this:
import sys
import threading
class ThreadedStdout(object):
def __init__(self):
self.local = threading.local()
def register(self, fh):
self.local.fh = fh
def write(self, stuff):
self.local.fh.write(stuff)
sys.stdout = ThreadedStdout()
def app(environ, start):
sys.stdout.register(environ['wsgi.stdout'])
# Whatever.
A:
It is worth noting that use of 'print' to sys.stdout in Apache/mod_wsgi was deliberately restricted. This is because a portable WSGI application should not use either sys.stdin or sys.stdout as some WSGI implementations use them to communicate to the server.
Apache/mod_wsgi is therefore trying to force you to write your WSGI application such that it will be portable to other WSGI implementations.
Unfortunately, too many people seem not to care about writing good code and so mod_wsgi 3.0 will allow you to write to sys.stdout and thus use 'print' without redirecting output to 'sys.stderr' as you should be doing.
Either way, the mod_wsgi documentation details how to remove the restriction in versions of mod_wsgi prior to 3.0. In particular, see documentation about the WSGIRestrictStdout directive. The documentation about debugging techniques also talks about the issue and about mapping sys.stdout to sys.stderr.
You can read a commentary which summaries this issue at:
http://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html
A:
While you can redirect stdout to different sources like file for logging, as Paolo mentions, you probably wouldn't need it. I didn't need it. If you really needed to log stuff, you would be using logging itself in the first place, wouldn't you? Also, even when you don't print a thing, the third party libraries you use may do. Just redirect it and get going.
The simplest solution to this problem is to redirect all stdout into stderr. In the wsgi configuration file, just redirect as necessary.
sys.stdout = sys.stderr
|
Python - Overridding print()
|
I'm using mod_wsgi and was wondering if it's possible to over-write the print() command (since it's useless).
Doing this doesn't work:
print = myPrintFunction
Since it's a syntax error. :(
|
[
"Print is not a function in Python 2.x, so this is not directly possible.\nYou can, however, override sys.stdout.\nIf you are on Python 3.0 in which print is now a function what you have would then work, assuming you have the right signature. Also see a related question in this site.\n",
"Would\nimport sys\nsys.stdout = MyFileWrapper()\n\nor something similar work?\n",
"If you are using 3.0, print is a function. If you are using 2.6, you can from __future__ import print_function and continue with a print function.\nIf <= 2.5, you can replace stdout like others have suggested, but be very careful if your wsgi server will call your app in multiple threads simultaneously. You WILL end up with simultaneous requests being sent down the same pipe.\nI haven't tested it, but you could try something like this:\nimport sys\nimport threading\n\nclass ThreadedStdout(object):\n def __init__(self):\n self.local = threading.local()\n def register(self, fh):\n self.local.fh = fh\n def write(self, stuff):\n self.local.fh.write(stuff)\n\nsys.stdout = ThreadedStdout()\n\ndef app(environ, start):\n sys.stdout.register(environ['wsgi.stdout'])\n\n # Whatever.\n\n",
"It is worth noting that use of 'print' to sys.stdout in Apache/mod_wsgi was deliberately restricted. This is because a portable WSGI application should not use either sys.stdin or sys.stdout as some WSGI implementations use them to communicate to the server.\nApache/mod_wsgi is therefore trying to force you to write your WSGI application such that it will be portable to other WSGI implementations.\nUnfortunately, too many people seem not to care about writing good code and so mod_wsgi 3.0 will allow you to write to sys.stdout and thus use 'print' without redirecting output to 'sys.stderr' as you should be doing.\nEither way, the mod_wsgi documentation details how to remove the restriction in versions of mod_wsgi prior to 3.0. In particular, see documentation about the WSGIRestrictStdout directive. The documentation about debugging techniques also talks about the issue and about mapping sys.stdout to sys.stderr.\nYou can read a commentary which summaries this issue at:\nhttp://blog.dscpl.com.au/2009/04/wsgi-and-printing-to-standard-output.html\n",
"While you can redirect stdout to different sources like file for logging, as Paolo mentions, you probably wouldn't need it. I didn't need it. If you really needed to log stuff, you would be using logging itself in the first place, wouldn't you? Also, even when you don't print a thing, the third party libraries you use may do. Just redirect it and get going.\nThe simplest solution to this problem is to redirect all stdout into stderr. In the wsgi configuration file, just redirect as necessary.\nsys.stdout = sys.stderr\n\n"
] |
[
13,
6,
1,
1,
0
] |
[] |
[] |
[
"mod_wsgi",
"python",
"python_3.x",
"wsgi"
] |
stackoverflow_0000770657_mod_wsgi_python_python_3.x_wsgi.txt
|
Q:
python 2.3 regex problem
how do i set the regular expressions flags like multiline and ignorecase in python 2.3?
in python 2.6 its like this
re.findall(pattern,string, re.multiline | re.ignorecase)
but this doesn't seem to wok for python 2.3, any ideas?
pointers appreciated
edit: sorry, it was python 2.3 not 2.4
A:
Compile the regexp in advance with re.compile(pattern[, flags]). Then you can pass the options as the second parameter.
A:
the flags are uppercase in 2.4, e.g.:
re.findall(pattern,string, re.MULTILINE | re.IGNORECASE)
works for me;
Python 2.4.3 (#1, Sep 3 2009, 15:37:37)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> re.findall("Test","Test\ntest\nTEST",re.MULTILINE|re.IGNORECASE)
['Test', 'test', 'TEST']
|
python 2.3 regex problem
|
how do i set the regular expressions flags like multiline and ignorecase in python 2.3?
in python 2.6 its like this
re.findall(pattern,string, re.multiline | re.ignorecase)
but this doesn't seem to wok for python 2.3, any ideas?
pointers appreciated
edit: sorry, it was python 2.3 not 2.4
|
[
"Compile the regexp in advance with re.compile(pattern[, flags]). Then you can pass the options as the second parameter.\n",
"the flags are uppercase in 2.4, e.g.:\nre.findall(pattern,string, re.MULTILINE | re.IGNORECASE)\n\nworks for me;\nPython 2.4.3 (#1, Sep 3 2009, 15:37:37) \n[GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import re\n>>> re.findall(\"Test\",\"Test\\ntest\\nTEST\",re.MULTILINE|re.IGNORECASE)\n['Test', 'test', 'TEST']\n\n"
] |
[
1,
1
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0001818622_python_regex.txt
|
Q:
How to have a URL like this in Django?
How can I have URLs like example.com/category/catename-operation/ in Django?
Also in some cases the user enters a space separated category, how can I handle that?
E.g if the user enters the category as "my home", then the URL for this category will become
example.com/my home/ which is not a valid URL.
How can I handle these things?
A:
If you want to keep your URLs pretty, for example when a user enters "my category" you could have "my-category" instead of "my%20category" in the URL. I suggest you look into SlugField (http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield) and prepopulating that slugfield using ModelAdmin's prepopulated_fields attribute.
A:
http://example.com/my%20home/ is a valid URL where space character is escaped and Django will do all escaping/unescaping for you.
A:
You can use the slugify template tag within your views to deal with spaces and such like so:
from django.template.defaultfilters import slugify
slugify("This is a slug!") # Will return u'this-is-a-slug'
A:
You can try an improved version of SlugField called AutoSlugField which is part of Django Custom Management Command Extensions.
A:
You could consider adding a URL-friendly name to your category and using that in the URL instead.
As another example you could have example.com/tv/ and have the category called "Televisions."
A:
How can I handle these things?
If you want to handle this thing, to obtain my-url, then use the form field clean method to return the valid url. Thats what it is meant for.
|
How to have a URL like this in Django?
|
How can I have URLs like example.com/category/catename-operation/ in Django?
Also in some cases the user enters a space separated category, how can I handle that?
E.g if the user enters the category as "my home", then the URL for this category will become
example.com/my home/ which is not a valid URL.
How can I handle these things?
|
[
"If you want to keep your URLs pretty, for example when a user enters \"my category\" you could have \"my-category\" instead of \"my%20category\" in the URL. I suggest you look into SlugField (http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield) and prepopulating that slugfield using ModelAdmin's prepopulated_fields attribute.\n",
"http://example.com/my%20home/ is a valid URL where space character is escaped and Django will do all escaping/unescaping for you.\n",
"You can use the slugify template tag within your views to deal with spaces and such like so:\nfrom django.template.defaultfilters import slugify\nslugify(\"This is a slug!\") # Will return u'this-is-a-slug'\n\n",
"You can try an improved version of SlugField called AutoSlugField which is part of Django Custom Management Command Extensions.\n",
"You could consider adding a URL-friendly name to your category and using that in the URL instead.\nAs another example you could have example.com/tv/ and have the category called \"Televisions.\"\n",
"\nHow can I handle these things?\n\nIf you want to handle this thing, to obtain my-url, then use the form field clean method to return the valid url. Thats what it is meant for.\n"
] |
[
6,
3,
1,
1,
0,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0001788432_django_python.txt
|
Q:
GAE Image Posting to Datastore through Django Form
I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "Using the Images Python API" on the GAE web site.
The sample they provide doesn't seem to work with Django though. Searching around here, I found a thread with a similar issue, but said the resolution came from using a newer version of Django with GAE. I'm trying to avoid this work around, and get it running with the build in API. I am new to both Python and Django, but from what I can gather, the image isn't properly being posted to the function that transforms the image and sends it to the Datastore. Here is my code:
def post(self):
contacts = Contact()
if users.get_current_user():
contacts.owner = users.get_current_user()
else:
self.redirect('/')
contacts.fname = self.request.get('fname')
contacts.lname = self.request.get('lname')
contacts.pnum = self.request.get('pnum')
img = self.request.FILES['file'].read()
img.resize(32,32)
contacts.avatar = db.Blob(images.resize(img,32,32))
contacts.put()
self.redirect('/')
All the other fields are added correctly, except the avatar field. The modified request string comes from the previously stated thread that contained a fix. When attempting to access the avatar, and this gets kind of odd, the page displays a broken image, rather than the default image I setup. This leads me to believe that, although the field is null or missing, there is still something there to draw a unique key when requesting it. Here is the display image function:
class Image (webapp.RequestHandler):
def get(self):
contacts = db.get(self.request.get("img_id"))
if contacts.avatar:
image = contacts.avatar
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(HttpResponseRedirect(contacts.avatar))
else:
self.response.out.wrute(HttpResponseRedirect("/static/image_not_found.gif"))
I've tried a number of different variations when trying to get this working as well, so please trust that I did, initially, use the block of code from the instructions.
Any help is greatly appreciated.
Thanks in advance.
A:
In your image serving code, you're writing out a redirect, with the 'URL' for the redirect being the image data - eg, you're redirecting users to "%PNG...". You need to write out the response data directly.
Besides that, what is HttpResponseRedirect? It's not part of the webapp framework.
Also, have you checked the datastore viewer to see if the image is being uploaded correctly? Try hashing the image before uploading it, and comparing it to the hash you see in the datastore (remove the resize call first). Is it the same?
A:
The following line won't work in Django 0.96, which is the default version on GAE:
img = self.request.FILES['file'].read()
I was the one who posted a similar question before (I think this is the thread you're referring to: Storing Images on App Engine using Django)
In your question you mention that you don't want to use a newer version of Django because it's a "workaround". I think what you're missing is that they Google App Engine already comes with Django 1.0 and 1.1 installed, they just made it so you have to explicitly specify which version you want to run in order to avoid breaking the apps that were first deployed built on 0.96.
You don't have to include the whole django library with your deploy. You just have to change your bootstrap file to tell App Engine that you when you say:
import django
That you want it to hand you Django 1.1.
You can read more about that here: http://code.google.com/appengine/docs/python/tools/libraries.html
However, if you the solution described in that other thread, it will work: Storing Images on App Engine using Django
Hope that helps.
A:
Here's my code:
if 'image' in request.FILES:
imageFile = request.FILES['image'] #in forms.py: image = forms.FileField(required=False)
fileSize = imageFile.size
fileType = imageFile.content_type
filename = imageFile.name
cPhoto = CarPhoto(car=car)
cPhoto.content = db.Blob(imageFile.read())
cPhoto.filename = User.objects.make_random_password(32) +'.jpg'
cPhoto.put()
then I display the image like this:
def show_car_photo(request, filename):
cPhoto = CarPhoto.gql('Where filename=:filename', filename=filename).get()
if cPhoto is None:
return HttpResponse(filename + ': Image Not Found')
response = HttpResponse(mimetype="image/jpeg")
response.content = cPhoto.content
return response
|
GAE Image Posting to Datastore through Django Form
|
I'm working on a little side project that involves posting an avatar to a users profile page, seems straight forward enough. I'm following the instructions from the "Using the Images Python API" on the GAE web site.
The sample they provide doesn't seem to work with Django though. Searching around here, I found a thread with a similar issue, but said the resolution came from using a newer version of Django with GAE. I'm trying to avoid this work around, and get it running with the build in API. I am new to both Python and Django, but from what I can gather, the image isn't properly being posted to the function that transforms the image and sends it to the Datastore. Here is my code:
def post(self):
contacts = Contact()
if users.get_current_user():
contacts.owner = users.get_current_user()
else:
self.redirect('/')
contacts.fname = self.request.get('fname')
contacts.lname = self.request.get('lname')
contacts.pnum = self.request.get('pnum')
img = self.request.FILES['file'].read()
img.resize(32,32)
contacts.avatar = db.Blob(images.resize(img,32,32))
contacts.put()
self.redirect('/')
All the other fields are added correctly, except the avatar field. The modified request string comes from the previously stated thread that contained a fix. When attempting to access the avatar, and this gets kind of odd, the page displays a broken image, rather than the default image I setup. This leads me to believe that, although the field is null or missing, there is still something there to draw a unique key when requesting it. Here is the display image function:
class Image (webapp.RequestHandler):
def get(self):
contacts = db.get(self.request.get("img_id"))
if contacts.avatar:
image = contacts.avatar
self.response.headers['Content-Type'] = "image/png"
self.response.out.write(HttpResponseRedirect(contacts.avatar))
else:
self.response.out.wrute(HttpResponseRedirect("/static/image_not_found.gif"))
I've tried a number of different variations when trying to get this working as well, so please trust that I did, initially, use the block of code from the instructions.
Any help is greatly appreciated.
Thanks in advance.
|
[
"In your image serving code, you're writing out a redirect, with the 'URL' for the redirect being the image data - eg, you're redirecting users to \"%PNG...\". You need to write out the response data directly.\nBesides that, what is HttpResponseRedirect? It's not part of the webapp framework.\nAlso, have you checked the datastore viewer to see if the image is being uploaded correctly? Try hashing the image before uploading it, and comparing it to the hash you see in the datastore (remove the resize call first). Is it the same?\n",
"The following line won't work in Django 0.96, which is the default version on GAE:\nimg = self.request.FILES['file'].read()\n\nI was the one who posted a similar question before (I think this is the thread you're referring to: Storing Images on App Engine using Django)\nIn your question you mention that you don't want to use a newer version of Django because it's a \"workaround\". I think what you're missing is that they Google App Engine already comes with Django 1.0 and 1.1 installed, they just made it so you have to explicitly specify which version you want to run in order to avoid breaking the apps that were first deployed built on 0.96.\nYou don't have to include the whole django library with your deploy. You just have to change your bootstrap file to tell App Engine that you when you say:\nimport django\n\nThat you want it to hand you Django 1.1. \nYou can read more about that here: http://code.google.com/appengine/docs/python/tools/libraries.html\nHowever, if you the solution described in that other thread, it will work: Storing Images on App Engine using Django\nHope that helps.\n",
"Here's my code:\n if 'image' in request.FILES:\n imageFile = request.FILES['image'] #in forms.py: image = forms.FileField(required=False)\n fileSize = imageFile.size \n fileType = imageFile.content_type \n filename = imageFile.name\n\n\n cPhoto = CarPhoto(car=car)\n cPhoto.content = db.Blob(imageFile.read()) \n cPhoto.filename = User.objects.make_random_password(32) +'.jpg' \n cPhoto.put()\n\nthen I display the image like this:\ndef show_car_photo(request, filename):\ncPhoto = CarPhoto.gql('Where filename=:filename', filename=filename).get()\nif cPhoto is None:\n return HttpResponse(filename + ': Image Not Found')\n\nresponse = HttpResponse(mimetype=\"image/jpeg\")\nresponse.content = cPhoto.content\nreturn response\n\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"google_cloud_datastore",
"python"
] |
stackoverflow_0001785637_django_google_app_engine_google_cloud_datastore_python.txt
|
Q:
Close and open a new browser in Selenium
I'm writing a script which needs the browser that selenium is operating close and re-open, without losing its cookies.
Any idea on how to go about it?
Basically, it's a check to see that if the user opens and closes his browser, his cookies stay intact.
A:
You should be able to use the stop and start commands. You will need to ensure that you are not clearing cookies between sessions, and depending on the browser you're launching you may also need to use the -browserSessionReuse command line option.
A:
This is a feature of the browser and not your concern: If there is a bug in the browser, then there is little you can do. If you need to know whether a certain version of the browser works correctly, then define a manual test (write a document that explains the steps), do it once and record the result somewhere (like "Browser XXX version YYY works").
When you know that a certain browser (version) works, then that's not going to change, so there is no need to repeat the test.
|
Close and open a new browser in Selenium
|
I'm writing a script which needs the browser that selenium is operating close and re-open, without losing its cookies.
Any idea on how to go about it?
Basically, it's a check to see that if the user opens and closes his browser, his cookies stay intact.
|
[
"You should be able to use the stop and start commands. You will need to ensure that you are not clearing cookies between sessions, and depending on the browser you're launching you may also need to use the -browserSessionReuse command line option.\n",
"This is a feature of the browser and not your concern: If there is a bug in the browser, then there is little you can do. If you need to know whether a certain version of the browser works correctly, then define a manual test (write a document that explains the steps), do it once and record the result somewhere (like \"Browser XXX version YYY works\").\nWhen you know that a certain browser (version) works, then that's not going to change, so there is no need to repeat the test.\n"
] |
[
3,
0
] |
[] |
[] |
[
"python",
"selenium"
] |
stackoverflow_0001818969_python_selenium.txt
|
Q:
python logging in django
I am using the basic python logger in django and it seems to be workng well. I have the logging setup in my setting.py as;
logging.baseConfig(level = logging.NOTSET,
format='a format',
datemt=' a datefmt',
filename='path to log',
filemode = 'a')
logging.getLogger('').setLevel(logging.NOTSET)
My question is with regard to propagating exceptions. In my code if I have a try/except clause and catch the exception so I can log it, what is the best way to then propagate that error so that I can redirect to my 500 page. I have been using
try:
do stuff
except Exception, e:
logging.error(e)
raise
but I find that this causes the exeption to be logged twice. Is there another way to do this or am I doing something wrong?
Regards
Andrew
A:
There's no need to catch the exception just so you can log it. You can log it and handle it, or else let it bubble up to some higher level which will log it and handle it. If you want to log exceptions which occur in some view, which you don't want to handle, then you can install some exception middleware which logs the exception and either returns a custom response which you determine, or None (to return whatever response Django would normally return).
There's an example of extensible exception middleware here, which doesn't actually use logging but whose log_exception() method you could subclass to log the exception, or just use that snippet as a guide to provide your own exception middleware - it's basically just a class with a method called process_exception:
class MyExceptionMiddleware:
def process_exception(self, request, exception):
#Do your logging here
Also, note that loggers have an exception() method which works like error() but includes traceback information in the log.
A:
There's a recipe: http://code.activestate.com/recipes/466332/
In any somewhat complex application, you likely want to log and handle most exceptions. The recipe shows a way to separate logging from handling, so that it is not necessary to explicitly invoke the logging mechanism in each try-except clause.
|
python logging in django
|
I am using the basic python logger in django and it seems to be workng well. I have the logging setup in my setting.py as;
logging.baseConfig(level = logging.NOTSET,
format='a format',
datemt=' a datefmt',
filename='path to log',
filemode = 'a')
logging.getLogger('').setLevel(logging.NOTSET)
My question is with regard to propagating exceptions. In my code if I have a try/except clause and catch the exception so I can log it, what is the best way to then propagate that error so that I can redirect to my 500 page. I have been using
try:
do stuff
except Exception, e:
logging.error(e)
raise
but I find that this causes the exeption to be logged twice. Is there another way to do this or am I doing something wrong?
Regards
Andrew
|
[
"There's no need to catch the exception just so you can log it. You can log it and handle it, or else let it bubble up to some higher level which will log it and handle it. If you want to log exceptions which occur in some view, which you don't want to handle, then you can install some exception middleware which logs the exception and either returns a custom response which you determine, or None (to return whatever response Django would normally return).\nThere's an example of extensible exception middleware here, which doesn't actually use logging but whose log_exception() method you could subclass to log the exception, or just use that snippet as a guide to provide your own exception middleware - it's basically just a class with a method called process_exception:\nclass MyExceptionMiddleware:\n\n def process_exception(self, request, exception):\n #Do your logging here\n\nAlso, note that loggers have an exception() method which works like error() but includes traceback information in the log.\n",
"There's a recipe: http://code.activestate.com/recipes/466332/\n\nIn any somewhat complex application, you likely want to log and handle most exceptions. The recipe shows a way to separate logging from handling, so that it is not necessary to explicitly invoke the logging mechanism in each try-except clause.\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"exception_handling",
"logging",
"python"
] |
stackoverflow_0001818236_django_exception_handling_logging_python.txt
|
Q:
Creating new list with values from two prior lists
Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2 , followed by the second to last element of list1 , followed by the second to last element of list2 , and so on (in other words the new list should consist of alternating elements of the reverse of list1 and list2 ). For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6] , then the new list should contain [3, 6, 2, 5, 1, 4] . Associate the new list with the variable list3 .
My code:
def new(list1,list2):
i = 0
j = 0
new_list = []
for j in list1:
new_list[i-1] = list2[j-1]
i+= 1
j += 1
new_list[i-1] = list2 [j-1]
i+= 1
j += 1
return new_list
I know, it's messy =_=, help?
A:
l1 = [1,2,3]
l2 = [4,5,6]
newl = []
for item1, item2 in zip(reversed(l1), reversed(l2)):
newl.append(item1)
newl.append(item2)
print newl
A:
list(sum(zip(list1,list2)[::-1],()))
A:
Yet another way,
from itertools import izip
l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
l = []
for _ in izip(reversed(l1), reversed(l2)): l.extend(_)
A:
May I suggest making your job much simpler by using the list .append() method instead?
>>> mylist = []
>>> mylist.append(1)
>>> mylist
[1]
>>> mylist.append(7)
>>> mylist
[1, 7]
Also another small suggestion, instead of iterating over one list or the other, I'd suggest iterating over numerical indices:
for i in range(len(list1)):
A:
One-liner:
reduce(lambda x,y: list(x+y), reversed(zip(list1,list2)))
list is necessary as the prior operations return a tuple.
|
Creating new list with values from two prior lists
|
Given the lists list1 and list2 that are of the same length, create a new list consisting of the last element of list1 followed by the last element of list2 , followed by the second to last element of list1 , followed by the second to last element of list2 , and so on (in other words the new list should consist of alternating elements of the reverse of list1 and list2 ). For example, if list1 contained [1, 2, 3] and list2 contained [4, 5, 6] , then the new list should contain [3, 6, 2, 5, 1, 4] . Associate the new list with the variable list3 .
My code:
def new(list1,list2):
i = 0
j = 0
new_list = []
for j in list1:
new_list[i-1] = list2[j-1]
i+= 1
j += 1
new_list[i-1] = list2 [j-1]
i+= 1
j += 1
return new_list
I know, it's messy =_=, help?
|
[
"l1 = [1,2,3]\nl2 = [4,5,6]\n\nnewl = []\nfor item1, item2 in zip(reversed(l1), reversed(l2)):\n newl.append(item1)\n newl.append(item2)\n\nprint newl\n\n",
"list(sum(zip(list1,list2)[::-1],()))\n\n",
"Yet another way,\nfrom itertools import izip\nl1 = [1, 2, 3, 4]\nl2 = [5, 6, 7, 8]\nl = []\nfor _ in izip(reversed(l1), reversed(l2)): l.extend(_)\n\n",
"May I suggest making your job much simpler by using the list .append() method instead?\n>>> mylist = []\n>>> mylist.append(1)\n>>> mylist\n[1]\n>>> mylist.append(7)\n>>> mylist\n[1, 7]\n\nAlso another small suggestion, instead of iterating over one list or the other, I'd suggest iterating over numerical indices:\nfor i in range(len(list1)):\n\n",
"One-liner:\nreduce(lambda x,y: list(x+y), reversed(zip(list1,list2)))\n\nlist is necessary as the prior operations return a tuple.\n"
] |
[
7,
2,
1,
0,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0001818763_list_python.txt
|
Q:
Executing a subprocess fails
I tried to call a process via Python with several arguments. Executing the batch file itself works fine for me but translating it into Python makes me scream. Here the contents of the batch file:
"C:\Program Files\bin\cspybat" "C:\Program Files\bin\armproc.dll" "C:\Program Files\bin\armjlink.dll" "C:\Documents and Settings\USER\Desktop\CAL\testing\Verification\FRT\Code\TC1\Output\Genericb\Debug\Exe\Gen.out" --download_only --backend -B "--endian=little" "--cpu=Cortex-M3" "--fpu=None" "-p" "C:\Program Files\CONFIG\debugger\ST\iostm32f10xxb.ddf" "--drv_verify_download" "--semihosting" "--device=STM32F10xxB" "-d" "jlink" "--drv_communication=USB0" "--jlink_speed=auto" "--jlink_initial_speed=32" "--jlink_reset_strategy=0,0"
The executable that is run by the batch file is named cspybat. The output of the executable provides the information: All parameters after--backendare passed to the back end.
Also note that some of the the parameters are strings and some not.
Solution
That works for me now:
""" MCU flashing function"""
params = [r"C:\Program Files\bin\cspy",
r"C:\Program Files\bin\arpro.dll",
r"C:\Program Files\bin\arjink.dll",
r"C:\Documents and Settings\USER\Desktop\Exe\GenerV530b.out",
"--download_only", "--backend", "-B", "--endian=little", "--cpu=Cort3", "--fpu=None", "-p",
r"C:\Program Files\CONFIG\debugger\ST\iostm32f10xxb.ddf",
"--drv_verify_download", "--semihosting", "--device=STM32F10xxB", "-d", "jlink", "--drv_communication=USB0",
"--jlink_speed=auto", "--jlink_initial_speed=32", "--jlink_reset_strategy=0,0" ]
print(subprocess.list2cmdline(params))
p = subprocess.Popen(subprocess.list2cmdline(params))
A:
To execute a batch file in Windows:
from subprocess import Popen
p = Popen("batchfile.bat", cwd=r"c:\directory\containing\batchfile")
stdout, stderr = p.communicate()
If you don't want to execute the batch file, but rather execute the command in your question directly from Python, you need to experiment a bit with the first argument to Popen.
First of all, the first argument can either be a string or a sequence.
So you either write:
p = Popen(r'"C:\Program Files\Systems\Emb Work 5.4\common\bin\run" "C:\Program Files\Systems\Emb Work 5.4\arm\bin\mpr.dll" ... ...', cwd=r"...")
or
p = Popen([r"C:\Program Files\Systems\Emb Work 5.4\common\bin\run", r"C:\Program Files\Systems\Emb Work 5.4\arm\bin\mpr.dll", ...], cwd=r"...")
# ... notice how you don't need to quote the elements containing spaces
According to the documentation:
On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline() method. Please note that not all MS Windows applications interpret the command line the same way: list2cmdline() is designed for applications using the same rules as the MS C runtime.
So if you use a sequence, it will be converted to a string. I would probably try with a sequence first, since then you won't have to quote all the elements that contain spaces (list2cmdline() does that for you).
For troubleshooting, I recommend you pass your sequence to subprocess.list2cmdline() and check the output.
Edit:
Here's what I'd do if I were you:
a) Create a simple Python script (testparams.py) like this:
import subprocess
params = [r"C:\Program Files\Systems\Emb Work 5.4\common\bin\run.exe", ...]
print subprocess.list2cmdline(params)
b) Run the script from the command line (python testparams.py), copy and paste the output to another command line, press enter and see what happens.
c) If it does not work, edit the python file and repeat until it works.
A:
First, you don't need all those quotes. So remove them. You only need quotes around parameters that have a filename when that filename has a space (stupidly, Windows does this often).
Your parameters are simply a list of strings, some of which need quotes. Because Windows uses non-standard \ for a path separator, use "raw" strings for these names.
params = [
r'"C:\Program Files\Systems\Emb Work 5.4\arm\bin\mpr.dll"',
r'"C:\Program Files\Systems\Emb Work 5.4\arm\bin\ajl.dll"',
r'"C:\Documents and Settings\USER\Desktop\abc.out"',
"--backend",
"-B",
"--endian=little",
"--cpu=Cortex",
"--fpu=None",
"-p",
r'"C:\Program Files\unknown\abc.ddf"',
"--drv_verify_download",
"--semihosting",
"--device=STM32F10xxB",
"-d",
"jjftk",
"--drv_communication=USB0",
"--speed=auto",
"--initial_speed=32",
"--reset_strategy=0,0"]
Use something like
program = r'"C:\Program Files\Systems\Emb Work 5.4\common\bin\run"'
subprocess.Popen( [program]+params )
|
Executing a subprocess fails
|
I tried to call a process via Python with several arguments. Executing the batch file itself works fine for me but translating it into Python makes me scream. Here the contents of the batch file:
"C:\Program Files\bin\cspybat" "C:\Program Files\bin\armproc.dll" "C:\Program Files\bin\armjlink.dll" "C:\Documents and Settings\USER\Desktop\CAL\testing\Verification\FRT\Code\TC1\Output\Genericb\Debug\Exe\Gen.out" --download_only --backend -B "--endian=little" "--cpu=Cortex-M3" "--fpu=None" "-p" "C:\Program Files\CONFIG\debugger\ST\iostm32f10xxb.ddf" "--drv_verify_download" "--semihosting" "--device=STM32F10xxB" "-d" "jlink" "--drv_communication=USB0" "--jlink_speed=auto" "--jlink_initial_speed=32" "--jlink_reset_strategy=0,0"
The executable that is run by the batch file is named cspybat. The output of the executable provides the information: All parameters after--backendare passed to the back end.
Also note that some of the the parameters are strings and some not.
Solution
That works for me now:
""" MCU flashing function"""
params = [r"C:\Program Files\bin\cspy",
r"C:\Program Files\bin\arpro.dll",
r"C:\Program Files\bin\arjink.dll",
r"C:\Documents and Settings\USER\Desktop\Exe\GenerV530b.out",
"--download_only", "--backend", "-B", "--endian=little", "--cpu=Cort3", "--fpu=None", "-p",
r"C:\Program Files\CONFIG\debugger\ST\iostm32f10xxb.ddf",
"--drv_verify_download", "--semihosting", "--device=STM32F10xxB", "-d", "jlink", "--drv_communication=USB0",
"--jlink_speed=auto", "--jlink_initial_speed=32", "--jlink_reset_strategy=0,0" ]
print(subprocess.list2cmdline(params))
p = subprocess.Popen(subprocess.list2cmdline(params))
|
[
"To execute a batch file in Windows:\nfrom subprocess import Popen\np = Popen(\"batchfile.bat\", cwd=r\"c:\\directory\\containing\\batchfile\")\nstdout, stderr = p.communicate()\n\nIf you don't want to execute the batch file, but rather execute the command in your question directly from Python, you need to experiment a bit with the first argument to Popen.\nFirst of all, the first argument can either be a string or a sequence.\nSo you either write:\np = Popen(r'\"C:\\Program Files\\Systems\\Emb Work 5.4\\common\\bin\\run\" \"C:\\Program Files\\Systems\\Emb Work 5.4\\arm\\bin\\mpr.dll\" ... ...', cwd=r\"...\")\n\nor\np = Popen([r\"C:\\Program Files\\Systems\\Emb Work 5.4\\common\\bin\\run\", r\"C:\\Program Files\\Systems\\Emb Work 5.4\\arm\\bin\\mpr.dll\", ...], cwd=r\"...\")\n# ... notice how you don't need to quote the elements containing spaces\n\nAccording to the documentation:\n\nOn Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline() method. Please note that not all MS Windows applications interpret the command line the same way: list2cmdline() is designed for applications using the same rules as the MS C runtime.\n\nSo if you use a sequence, it will be converted to a string. I would probably try with a sequence first, since then you won't have to quote all the elements that contain spaces (list2cmdline() does that for you).\nFor troubleshooting, I recommend you pass your sequence to subprocess.list2cmdline() and check the output.\nEdit:\nHere's what I'd do if I were you:\na) Create a simple Python script (testparams.py) like this:\nimport subprocess\nparams = [r\"C:\\Program Files\\Systems\\Emb Work 5.4\\common\\bin\\run.exe\", ...]\nprint subprocess.list2cmdline(params)\n\nb) Run the script from the command line (python testparams.py), copy and paste the output to another command line, press enter and see what happens.\nc) If it does not work, edit the python file and repeat until it works.\n",
"First, you don't need all those quotes. So remove them. You only need quotes around parameters that have a filename when that filename has a space (stupidly, Windows does this often).\nYour parameters are simply a list of strings, some of which need quotes. Because Windows uses non-standard \\ for a path separator, use \"raw\" strings for these names.\nparams = [\n r'\"C:\\Program Files\\Systems\\Emb Work 5.4\\arm\\bin\\mpr.dll\"',\n r'\"C:\\Program Files\\Systems\\Emb Work 5.4\\arm\\bin\\ajl.dll\"',\n r'\"C:\\Documents and Settings\\USER\\Desktop\\abc.out\"',\n \"--backend\",\n \"-B\", \n \"--endian=little\",\n \"--cpu=Cortex\",\n \"--fpu=None\",\n \"-p\",\n r'\"C:\\Program Files\\unknown\\abc.ddf\"',\n \"--drv_verify_download\",\n \"--semihosting\",\n \"--device=STM32F10xxB\",\n \"-d\",\n \"jjftk\",\n \"--drv_communication=USB0\",\n \"--speed=auto\",\n \"--initial_speed=32\",\n \"--reset_strategy=0,0\"]\n\nUse something like \nprogram = r'\"C:\\Program Files\\Systems\\Emb Work 5.4\\common\\bin\\run\"'\nsubprocess.Popen( [program]+params )\n\n"
] |
[
28,
0
] |
[] |
[] |
[
"python",
"subprocess"
] |
stackoverflow_0001818774_python_subprocess.txt
|
Q:
Are there functions in Python, or is everything a method?
Or is everything a method?
Since everything is an object, a
def whatever:
is just a method of that file.py, right?
A:
Python has functions. As everything is an object functions are objects too.
So, to use your example:
>>> def whatever():
... pass
...
>>> whatever
<function whatever at 0x00AF5F30>
When we use def we have created an object which is a function. We can, for example, look at an attribute of the object:
>>> whatever.func_name
'whatever'
In answer to your question - whatever() is not a method of file.py. It is better to think of it as a function object bound to the name whatever in the global namespace of file.py.
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__d
oc__': None, 'whatever': <function whatever at 0x00AF5EB0>}
Or to look at it another way, there's nothing stopping us from binding the name whatever to a different object altogether:
>>> whatever
<function whatever at 0x00AF5F30>
>>> whatever = "string"
>>> whatever
'string'
There are other ways to create function objects. For example, lambdas:
>>> somelambda = lambda x: x * 2
>>> somelambda
<function <lambda> at 0x00AF5F30>
A method is like attribute of an object that is a function. What makes it a method is that the methods get bound to the object. This causes the object to get passed to the function as the first argument which we normally call self.
Let's define a class SomeClass with a method somemethod and an instance someobject:
>>> class SomeClass:
... def somemethod(one="Not Passed", two="Not passed"):
... print "one = %s\ntwo = %s" % (one,two)
...
>>> someobject = SomeClass()
Let's look at somemethod as an attribute:
>>> SomeClass.somemethod
<unbound method SomeClass.somemethod>
>>> someobject.somemethod
<bound method SomeClass.somemethod of <__main__.SomeClass instance at 0x00AFE030
We can see it's a bound method on the object and an unbound method on the class. So now let's call the method and see what happens:
>>> someobject.somemethod("Hello world")
one = <__main__.SomeClass instance at 0x00AFE030>
two = Hello world
As it's a bound method the first argument received by somemethod is the object and the second argument is the first argument in the method call. Let's call the method on the class:
>>> SomeClass.somemethod("Hello world")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method somemethod() must be called with SomeClass instance as first argument (got str instance instead)
Python complains because we're trying to call the method without giving it an object of the appropriate type. So we can fix this by passing the object "by hand":
>>> SomeClass.somemethod(someobject,"Hello world")
one = <__main__.SomeClass instance at 0x00AFE030>
two = Hello world
You might use method calls of this type - calling a method on a class - when you want to call a specific method from a superclass.
(It is possible to take a function and bind it to class to make it a method, but this is not something that you'd normally ever need to do.)
A:
Unlike in Java in Python a file named file.py does not necessarily contain a class called file as you might expect if this was a java file named file.java.
In Python a file is a module which is really just a namespace (more comparable to a Java package than a Java class) and not a class. Consider the example file.py below:
def whatever_func():
print "What ever function"
class SomeClass(object):
def whatever_meth(self):
print "What ever method"
In the example above the file module/namespace contains an ordinary function named whatever_func and a class SomeClass which has a method whatever_meth.
A:
Hmm... You can work with "whatever" as an ordinary function in file namespace.
|
Are there functions in Python, or is everything a method?
|
Or is everything a method?
Since everything is an object, a
def whatever:
is just a method of that file.py, right?
|
[
"Python has functions. As everything is an object functions are objects too.\nSo, to use your example:\n>>> def whatever():\n... pass\n...\n>>> whatever\n<function whatever at 0x00AF5F30>\n\nWhen we use def we have created an object which is a function. We can, for example, look at an attribute of the object:\n>>> whatever.func_name\n'whatever'\n\nIn answer to your question - whatever() is not a method of file.py. It is better to think of it as a function object bound to the name whatever in the global namespace of file.py.\n>>> globals()\n{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__d\noc__': None, 'whatever': <function whatever at 0x00AF5EB0>}\n\nOr to look at it another way, there's nothing stopping us from binding the name whatever to a different object altogether:\n>>> whatever\n<function whatever at 0x00AF5F30>\n>>> whatever = \"string\"\n>>> whatever\n'string'\n\nThere are other ways to create function objects. For example, lambdas:\n>>> somelambda = lambda x: x * 2\n>>> somelambda\n<function <lambda> at 0x00AF5F30>\n\nA method is like attribute of an object that is a function. What makes it a method is that the methods get bound to the object. This causes the object to get passed to the function as the first argument which we normally call self.\nLet's define a class SomeClass with a method somemethod and an instance someobject:\n>>> class SomeClass:\n... def somemethod(one=\"Not Passed\", two=\"Not passed\"):\n... print \"one = %s\\ntwo = %s\" % (one,two)\n...\n>>> someobject = SomeClass()\n\nLet's look at somemethod as an attribute:\n>>> SomeClass.somemethod\n<unbound method SomeClass.somemethod>\n>>> someobject.somemethod\n<bound method SomeClass.somemethod of <__main__.SomeClass instance at 0x00AFE030\n\nWe can see it's a bound method on the object and an unbound method on the class. So now let's call the method and see what happens:\n>>> someobject.somemethod(\"Hello world\")\none = <__main__.SomeClass instance at 0x00AFE030>\ntwo = Hello world\n\nAs it's a bound method the first argument received by somemethod is the object and the second argument is the first argument in the method call. Let's call the method on the class:\n>>> SomeClass.somemethod(\"Hello world\")\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method somemethod() must be called with SomeClass instance as first argument (got str instance instead)\n\nPython complains because we're trying to call the method without giving it an object of the appropriate type. So we can fix this by passing the object \"by hand\":\n>>> SomeClass.somemethod(someobject,\"Hello world\")\none = <__main__.SomeClass instance at 0x00AFE030>\ntwo = Hello world\n\nYou might use method calls of this type - calling a method on a class - when you want to call a specific method from a superclass.\n(It is possible to take a function and bind it to class to make it a method, but this is not something that you'd normally ever need to do.)\n",
"Unlike in Java in Python a file named file.py does not necessarily contain a class called file as you might expect if this was a java file named file.java.\nIn Python a file is a module which is really just a namespace (more comparable to a Java package than a Java class) and not a class. Consider the example file.py below:\ndef whatever_func():\n print \"What ever function\"\n\nclass SomeClass(object):\n def whatever_meth(self):\n print \"What ever method\"\n\nIn the example above the file module/namespace contains an ordinary function named whatever_func and a class SomeClass which has a method whatever_meth.\n",
"Hmm... You can work with \"whatever\" as an ordinary function in file namespace.\n"
] |
[
31,
2,
0
] |
[] |
[] |
[
"function",
"methods",
"oop",
"python"
] |
stackoverflow_0001819372_function_methods_oop_python.txt
|
Q:
Database query across django ManyToManyField
I'd like to find how to select all objects whose ManyToMany field contains another object. I have the following models (stripped down)
class Category(models.Model):
pass
class Picture(models.Model):
categories = models.ManyToManyField(Category)
visible = models.BooleanField()
I need a function to select all the Pictures in one or more Categories:
def pics_in_cats(cat_ids=()):
pass
BUT it needs to return a QuerySet if possible so that I can do something like:
pics_in_cats((1,2,3)).filter(visible=True)
It could be done by loading all the relevant Category objects and merging their picture_set attributes, but that seems inefficient. I'd also like to avoid falling back to raw SQL if possible.
Thanks in advance
A:
Why write a custom function and not use something like this? (untested)
pics = Picture.objects.filter(categories__in = [1,2,3]).filter(visible=True)
|
Database query across django ManyToManyField
|
I'd like to find how to select all objects whose ManyToMany field contains another object. I have the following models (stripped down)
class Category(models.Model):
pass
class Picture(models.Model):
categories = models.ManyToManyField(Category)
visible = models.BooleanField()
I need a function to select all the Pictures in one or more Categories:
def pics_in_cats(cat_ids=()):
pass
BUT it needs to return a QuerySet if possible so that I can do something like:
pics_in_cats((1,2,3)).filter(visible=True)
It could be done by loading all the relevant Category objects and merging their picture_set attributes, but that seems inefficient. I'd also like to avoid falling back to raw SQL if possible.
Thanks in advance
|
[
"Why write a custom function and not use something like this? (untested)\npics = Picture.objects.filter(categories__in = [1,2,3]).filter(visible=True)\n\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_database",
"python"
] |
stackoverflow_0001819613_django_django_database_python.txt
|
Q:
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:
http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing
Can I find something similar to this for my Django application?
Can this be accomplished using Django inclusion tags?
A:
You are looking for the universal feed parser.
A:
http://www.djangosnippets.org/tags/rss/
|
Is there anything in the Django / Python world equivalent to SimplePie Plugin for Wordpress?
|
I know that SimplePie itself is derived from UFP, but the features I'm wondering about are the post-processing features that are available in SimplePie for WordPress plugin:
http://simplepie.org/wiki/plugins/wordpress/simplepie_plugin_for_wordpress/processing
Can I find something similar to this for my Django application?
Can this be accomplished using Django inclusion tags?
|
[
"You are looking for the universal feed parser.\n",
"http://www.djangosnippets.org/tags/rss/\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"django_templates",
"python",
"rss",
"simplepie"
] |
stackoverflow_0000795976_django_django_templates_python_rss_simplepie.txt
|
Q:
Getting value of TextCtrl from a different wxPanel
I was trying to get my first wxWindow application to work and I ran into following difficulty:
I create wxPanel and add a wxNotebook object to it. Then I add a page to notebook created from another wxPanel object. How do I access a value of TextCtrl from first wxPanel in the second one?
import wx
class BasicApp(wx.App):
def OnInit(self):
frame = BasicFrame(None, -1, "Test App")
panel = BasicPanel(frame, -1);
frame.Show(True)
self.SetTopWindow(frame)
return True;
class BasicFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title,
wx.DefaultPosition, wx.Size(400, 300))
self.CreateStatusBar()
class BasicPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.lblText1 = wx.StaticText(self, -1, "Text1:");
self.txtText1 = wx.TextCtrl(self, 1001, "Text1", size = wx.Size(140, -1));
self.line1 = wx.BoxSizer(wx.HORIZONTAL);
self.line1.Add(self.lblText1, 0, wx.EXPAND);
self.line1.Add(self.txtText1, proportion=1, flag=wx.LEFT, border=5);
self.nb = wx.Notebook(self, -1);
tab1 = Tab1(self.nb, -1);
self.nb.AddPage(tab1, "Tab1");
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.line1, 0, wx.EXPAND)
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)
self.Show(1)
class Tab1(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id);
self.lblText2 = wx.StaticText(self, -1, "Text2:");
self.txtText2 = wx.TextCtrl(self, 1101, "Text2", size = wx.Size(140, -1));
self.line1 = wx.BoxSizer(wx.HORIZONTAL);
self.line1.Add(self.lblText2, 0, wx.EXPAND);
self.line1.Add(self.txtText2, 0, wx.EXPAND);
self.lblMessage = wx.StaticText(self, -1, "Message:");
self.txtMessage = wx.TextCtrl(self, 1102, "", style = wx.TE_MULTILINE);
self.cmdCreate = wx.Button(self, 1103, "Create");
self.cmdCreate.Bind(wx.EVT_BUTTON, self.Create_OnClick)
self.line3 = wx.BoxSizer(wx.HORIZONTAL);
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.line1, 0, wx.EXPAND)
self.sizer.Add(self.lblMessage, 0, wx.EXPAND)
self.sizer.Add(self.txtMessage, 1, wx.EXPAND)
self.sizer.Add(self.cmdCreate, 0, wx.LEFT)
self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)
self.Show(1)
def Create_OnClick(self, event):
text1 = "";
text2 = self.txtText2.GetValue();
self.txtMessage.SetValue(text1 + " " + text2);
app = BasicApp(0)
app.MainLoop()
To be more specific I want to be able to access value of txtText1 in Create_OnClick() method. How could this be achieved?
A:
One solution is to pass the control to the constructor of the tab, then you can directly reference it. For example:
class Tab1(wx.Panel):
def __init__(self, parent, id, textCtrl1):
wx.Panel.__init__(self, parent, id);
self.textCtrl1 = textCtrl1
...
def Create_OnClick(self, event):
text1 = self.textCtrl1
Another solution is to move the Create_OnClick handler to the base panel since it knows about all of the other panels (and thus, their children). Or, create a separate controller class that knows about the various widgets and can have handlers that act on behalf of them all.
|
Getting value of TextCtrl from a different wxPanel
|
I was trying to get my first wxWindow application to work and I ran into following difficulty:
I create wxPanel and add a wxNotebook object to it. Then I add a page to notebook created from another wxPanel object. How do I access a value of TextCtrl from first wxPanel in the second one?
import wx
class BasicApp(wx.App):
def OnInit(self):
frame = BasicFrame(None, -1, "Test App")
panel = BasicPanel(frame, -1);
frame.Show(True)
self.SetTopWindow(frame)
return True;
class BasicFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title,
wx.DefaultPosition, wx.Size(400, 300))
self.CreateStatusBar()
class BasicPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
self.lblText1 = wx.StaticText(self, -1, "Text1:");
self.txtText1 = wx.TextCtrl(self, 1001, "Text1", size = wx.Size(140, -1));
self.line1 = wx.BoxSizer(wx.HORIZONTAL);
self.line1.Add(self.lblText1, 0, wx.EXPAND);
self.line1.Add(self.txtText1, proportion=1, flag=wx.LEFT, border=5);
self.nb = wx.Notebook(self, -1);
tab1 = Tab1(self.nb, -1);
self.nb.AddPage(tab1, "Tab1");
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.line1, 0, wx.EXPAND)
self.sizer.Add(self.nb, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)
self.Show(1)
class Tab1(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id);
self.lblText2 = wx.StaticText(self, -1, "Text2:");
self.txtText2 = wx.TextCtrl(self, 1101, "Text2", size = wx.Size(140, -1));
self.line1 = wx.BoxSizer(wx.HORIZONTAL);
self.line1.Add(self.lblText2, 0, wx.EXPAND);
self.line1.Add(self.txtText2, 0, wx.EXPAND);
self.lblMessage = wx.StaticText(self, -1, "Message:");
self.txtMessage = wx.TextCtrl(self, 1102, "", style = wx.TE_MULTILINE);
self.cmdCreate = wx.Button(self, 1103, "Create");
self.cmdCreate.Bind(wx.EVT_BUTTON, self.Create_OnClick)
self.line3 = wx.BoxSizer(wx.HORIZONTAL);
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.line1, 0, wx.EXPAND)
self.sizer.Add(self.lblMessage, 0, wx.EXPAND)
self.sizer.Add(self.txtMessage, 1, wx.EXPAND)
self.sizer.Add(self.cmdCreate, 0, wx.LEFT)
self.SetSizer(self.sizer)
self.SetAutoLayout(1)
self.sizer.Fit(self)
self.Show(1)
def Create_OnClick(self, event):
text1 = "";
text2 = self.txtText2.GetValue();
self.txtMessage.SetValue(text1 + " " + text2);
app = BasicApp(0)
app.MainLoop()
To be more specific I want to be able to access value of txtText1 in Create_OnClick() method. How could this be achieved?
|
[
"One solution is to pass the control to the constructor of the tab, then you can directly reference it. For example:\nclass Tab1(wx.Panel):\n def __init__(self, parent, id, textCtrl1):\n wx.Panel.__init__(self, parent, id);\n self.textCtrl1 = textCtrl1\n ...\n def Create_OnClick(self, event):\n text1 = self.textCtrl1\n\nAnother solution is to move the Create_OnClick handler to the base panel since it knows about all of the other panels (and thus, their children). Or, create a separate controller class that knows about the various widgets and can have handlers that act on behalf of them all.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0001816353_python_wxpython.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.